@wengine-ai/llms 2.3.18 → 2.3.19

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,124 +1,124 @@
1
- "use strict";var AC=Object.create;var fi=Object.defineProperty;var SC=Object.getOwnPropertyDescriptor;var vC=Object.getOwnPropertyNames;var TC=Object.getPrototypeOf,DC=Object.prototype.hasOwnProperty;var Le=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),hi=(t,e)=>{for(var n in e)fi(t,n,{get:e[n],enumerable:!0})},qh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vC(e))!DC.call(t,o)&&o!==n&&fi(t,o,{get:()=>e[o],enumerable:!(r=SC(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?AC(TC(t)):{},qh(e||!t||!t.__esModule?fi(n,"default",{value:t,enumerable:!0}):n,t)),zh=t=>qh(fi({},"__esModule",{value:!0}),t);var Hh=X((IR,pi)=>{pi.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;pi.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]/;pi.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 sc=X((NR,Wh)=>{var oc=Hh();Wh.exports={isSpaceSeparator(t){return typeof t=="string"&&oc.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||oc.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"||oc.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 Yh=X((BR,Kh)=>{var We=sc(),ac,ot,En,gi,Hn,Ut,Ge,lc,qo;Kh.exports=function(e,n){ac=String(e),ot="start",En=[],gi=0,Hn=1,Ut=0,Ge=void 0,lc=void 0,qo=void 0;do Ge=RC(),PC[ot]();while(Ge.type!=="eof");return typeof n=="function"?uc({"":qo},"",n):qo};function uc(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),a=uc(r,s,n);a===void 0?delete r[s]:Object.defineProperty(r,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=uc(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var _e,ge,$o,wn,Ee;function RC(){for(_e="default",ge="",$o=!1,wn=1;;){Ee=kn();let t=Jh[_e]();if(t)return t}}function kn(){if(ac[gi])return String.fromCodePoint(ac.codePointAt(gi))}function W(){let t=kn();return t===`
2
- `?(Hn++,Ut=0):t?Ut+=t.length:Ut++,t&&(gi+=t.length),t}var Jh={default(){switch(Ee){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
3
- `:case"\r":case"\u2028":case"\u2029":W();return;case"/":W(),_e="comment";return;case void 0:return W(),Ne("eof")}if(We.isSpaceSeparator(Ee)){W();return}return Jh[ot]()},comment(){switch(Ee){case"*":W(),_e="multiLineComment";return;case"/":W(),_e="singleLineComment";return}throw Be(W())},multiLineComment(){switch(Ee){case"*":W(),_e="multiLineCommentAsterisk";return;case void 0:throw Be(W())}W()},multiLineCommentAsterisk(){switch(Ee){case"*":W();return;case"/":W(),_e="default";return;case void 0:throw Be(W())}W(),_e="multiLineComment"},singleLineComment(){switch(Ee){case`
4
- `:case"\r":case"\u2028":case"\u2029":W(),_e="default";return;case void 0:return W(),Ne("eof")}W()},value(){switch(Ee){case"{":case"[":return Ne("punctuator",W());case"n":return W(),dr("ull"),Ne("null",null);case"t":return W(),dr("rue"),Ne("boolean",!0);case"f":return W(),dr("alse"),Ne("boolean",!1);case"-":case"+":W()==="-"&&(wn=-1),_e="sign";return;case".":ge=W(),_e="decimalPointLeading";return;case"0":ge=W(),_e="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ge=W(),_e="decimalInteger";return;case"I":return W(),dr("nfinity"),Ne("numeric",1/0);case"N":return W(),dr("aN"),Ne("numeric",NaN);case'"':case"'":$o=W()==='"',ge="",_e="string";return}throw Be(W())},identifierNameStartEscape(){if(Ee!=="u")throw Be(W());W();let t=cc();switch(t){case"$":case"_":break;default:if(!We.isIdStartChar(t))throw Gh();break}ge+=t,_e="identifierName"},identifierName(){switch(Ee){case"$":case"_":case"\u200C":case"\u200D":ge+=W();return;case"\\":W(),_e="identifierNameEscape";return}if(We.isIdContinueChar(Ee)){ge+=W();return}return Ne("identifier",ge)},identifierNameEscape(){if(Ee!=="u")throw Be(W());W();let t=cc();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!We.isIdContinueChar(t))throw Gh();break}ge+=t,_e="identifierName"},sign(){switch(Ee){case".":ge=W(),_e="decimalPointLeading";return;case"0":ge=W(),_e="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ge=W(),_e="decimalInteger";return;case"I":return W(),dr("nfinity"),Ne("numeric",wn*(1/0));case"N":return W(),dr("aN"),Ne("numeric",NaN)}throw Be(W())},zero(){switch(Ee){case".":ge+=W(),_e="decimalPoint";return;case"e":case"E":ge+=W(),_e="decimalExponent";return;case"x":case"X":ge+=W(),_e="hexadecimal";return}return Ne("numeric",wn*0)},decimalInteger(){switch(Ee){case".":ge+=W(),_e="decimalPoint";return;case"e":case"E":ge+=W(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=W();return}return Ne("numeric",wn*Number(ge))},decimalPointLeading(){if(We.isDigit(Ee)){ge+=W(),_e="decimalFraction";return}throw Be(W())},decimalPoint(){switch(Ee){case"e":case"E":ge+=W(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=W(),_e="decimalFraction";return}return Ne("numeric",wn*Number(ge))},decimalFraction(){switch(Ee){case"e":case"E":ge+=W(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=W();return}return Ne("numeric",wn*Number(ge))},decimalExponent(){switch(Ee){case"+":case"-":ge+=W(),_e="decimalExponentSign";return}if(We.isDigit(Ee)){ge+=W(),_e="decimalExponentInteger";return}throw Be(W())},decimalExponentSign(){if(We.isDigit(Ee)){ge+=W(),_e="decimalExponentInteger";return}throw Be(W())},decimalExponentInteger(){if(We.isDigit(Ee)){ge+=W();return}return Ne("numeric",wn*Number(ge))},hexadecimal(){if(We.isHexDigit(Ee)){ge+=W(),_e="hexadecimalInteger";return}throw Be(W())},hexadecimalInteger(){if(We.isHexDigit(Ee)){ge+=W();return}return Ne("numeric",wn*Number(ge))},string(){switch(Ee){case"\\":W(),ge+=xC();return;case'"':if($o)return W(),Ne("string",ge);ge+=W();return;case"'":if(!$o)return W(),Ne("string",ge);ge+=W();return;case`
5
- `:case"\r":throw Be(W());case"\u2028":case"\u2029":FC(Ee);break;case void 0:throw Be(W())}ge+=W()},start(){switch(Ee){case"{":case"[":return Ne("punctuator",W())}_e="value"},beforePropertyName(){switch(Ee){case"$":case"_":ge=W(),_e="identifierName";return;case"\\":W(),_e="identifierNameStartEscape";return;case"}":return Ne("punctuator",W());case'"':case"'":$o=W()==='"',_e="string";return}if(We.isIdStartChar(Ee)){ge+=W(),_e="identifierName";return}throw Be(W())},afterPropertyName(){if(Ee===":")return Ne("punctuator",W());throw Be(W())},beforePropertyValue(){_e="value"},afterPropertyValue(){switch(Ee){case",":case"}":return Ne("punctuator",W())}throw Be(W())},beforeArrayValue(){if(Ee==="]")return Ne("punctuator",W());_e="value"},afterArrayValue(){switch(Ee){case",":case"]":return Ne("punctuator",W())}throw Be(W())},end(){throw Be(W())}};function Ne(t,e){return{type:t,value:e,line:Hn,column:Ut}}function dr(t){for(let e of t){if(kn()!==e)throw Be(W());W()}}function xC(){switch(kn()){case"b":return W(),"\b";case"f":return W(),"\f";case"n":return W(),`
6
- `;case"r":return W(),"\r";case"t":return W()," ";case"v":return W(),"\v";case"0":if(W(),We.isDigit(kn()))throw Be(W());return"\0";case"x":return W(),OC();case"u":return W(),cc();case`
7
- `:case"\u2028":case"\u2029":return W(),"";case"\r":return W(),kn()===`
8
- `&&W(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Be(W());case void 0:throw Be(W())}return W()}function OC(){let t="",e=kn();if(!We.isHexDigit(e)||(t+=W(),e=kn(),!We.isHexDigit(e)))throw Be(W());return t+=W(),String.fromCodePoint(parseInt(t,16))}function cc(){let t="",e=4;for(;e-- >0;){let n=kn();if(!We.isHexDigit(n))throw Be(W());t+=W()}return String.fromCodePoint(parseInt(t,16))}var PC={start(){if(Ge.type==="eof")throw fr();ic()},beforePropertyName(){switch(Ge.type){case"identifier":case"string":lc=Ge.value,ot="afterPropertyName";return;case"punctuator":mi();return;case"eof":throw fr()}},afterPropertyName(){if(Ge.type==="eof")throw fr();ot="beforePropertyValue"},beforePropertyValue(){if(Ge.type==="eof")throw fr();ic()},beforeArrayValue(){if(Ge.type==="eof")throw fr();if(Ge.type==="punctuator"&&Ge.value==="]"){mi();return}ic()},afterPropertyValue(){if(Ge.type==="eof")throw fr();switch(Ge.value){case",":ot="beforePropertyName";return;case"}":mi()}},afterArrayValue(){if(Ge.type==="eof")throw fr();switch(Ge.value){case",":ot="beforeArrayValue";return;case"]":mi()}},end(){}};function ic(){let t;switch(Ge.type){case"punctuator":switch(Ge.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=Ge.value;break}if(qo===void 0)qo=t;else{let e=En[En.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,lc,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")En.push(t),Array.isArray(t)?ot="beforeArrayValue":ot="beforePropertyName";else{let e=En[En.length-1];e==null?ot="end":Array.isArray(e)?ot="afterArrayValue":ot="afterPropertyValue"}}function mi(){En.pop();let t=En[En.length-1];t==null?ot="end":Array.isArray(t)?ot="afterArrayValue":ot="afterPropertyValue"}function Be(t){return yi(t===void 0?`JSON5: invalid end of input at ${Hn}:${Ut}`:`JSON5: invalid character '${Vh(t)}' at ${Hn}:${Ut}`)}function fr(){return yi(`JSON5: invalid end of input at ${Hn}:${Ut}`)}function Gh(){return Ut-=5,yi(`JSON5: invalid identifier character at ${Hn}:${Ut}`)}function FC(t){console.warn(`JSON5: '${Vh(t)}' in strings is not valid ECMAScript; consider escaping`)}function Vh(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 n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function yi(t){let e=new SyntaxError(t);return e.lineNumber=Hn,e.columnNumber=Ut,e}});var Xh=X((MR,Qh)=>{var dc=sc();Qh.exports=function(e,n,r){let o=[],s="",a,u,l="",f;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,f=n.quote,n=n.replacer),typeof n=="function")u=n;else if(Array.isArray(n)){a=[];for(let y of n){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&a.indexOf(g)<0&&a.push(g)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),d("",{"":e});function d(y,g){let _=g[y];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(y):typeof _.toJSON=="function"&&(_=_.toJSON(y))),u&&(_=u.call(g,y,_)),_ instanceof Number?_=Number(_):_ instanceof String?_=String(_):_ instanceof Boolean&&(_=_.valueOf()),_){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof _=="string")return p(_,!1);if(typeof _=="number")return String(_);if(typeof _=="object")return Array.isArray(_)?w(_):m(_)}function p(y){let g={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},A="";for(let v=0;v<y.length;v++){let T=y[v];switch(T){case"'":case'"':g[T]++,A+=T;continue;case"\0":if(dc.isDigit(y[v+1])){A+="\\x00";continue}}if(_[T]){A+=_[T];continue}if(T<" "){let R=T.charCodeAt(0).toString(16);A+="\\x"+("00"+R).substring(R.length);continue}A+=T}let C=f||Object.keys(g).reduce((v,T)=>g[v]<g[T]?v:T);return A=A.replace(new RegExp(C,"g"),_[C]),C+A+C}function m(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let _=a||Object.keys(y),A=[];for(let v of _){let T=d(v,y);if(T!==void 0){let R=b(v)+":";l!==""&&(R+=" "),R+=T,A.push(R)}}let C;if(A.length===0)C="{}";else{let v;if(l==="")v=A.join(","),C="{"+v+"}";else{let T=`,
9
- `+s;v=A.join(T),C=`{
10
- `+s+v+`,
11
- `+g+"}"}}return o.pop(),s=g,C}function b(y){if(y.length===0)return p(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!dc.isIdStartChar(g))return p(y,!0);for(let _=g.length;_<y.length;_++)if(!dc.isIdContinueChar(String.fromCodePoint(y.codePointAt(_))))return p(y,!0);return y}function w(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let _=[];for(let C=0;C<y.length;C++){let v=d(String(C),y);_.push(v!==void 0?v:"null")}let A;if(_.length===0)A="[]";else if(l==="")A="["+_.join(",")+"]";else{let C=`,
12
- `+s,v=_.join(C);A=`[
13
- `+s+v+`,
14
- `+g+"]"}return o.pop(),s=g,A}}});var fc=X((LR,Zh)=>{var IC=Yh(),NC=Xh(),BC={parse:IC,stringify:NC};Zh.exports=BC});var pp={};hi(pp,{getFallbackPromotionStore:()=>Jr,resetFallbackPromotionStore:()=>$C});function Jr(t){return pr||(pr=new mc,t&&pr.configure(t)),pr}function $C(){pr&&(pr.clearAll(),pr=null)}var UC,mc,pr,wi=Le(()=>{"use strict";Wn();UC=600*1e3,mc=class{promotions=new Map;enabled=!0;ttlMs=UC;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let u=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(u,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...f]=a.promotedModel.split(","),d=f.join(",");if(!Je().isAvailable(l,d))return this.promotions.delete(s),null;let m=o.find(w=>w.name.toLowerCase()===l.toLowerCase()),b=m?.models?.find(w=>String(w).toLowerCase()===d.toLowerCase());return!m||!b||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${b}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},pr=null});function WC(t){try{if(!(0,An.existsSync)(_c))return;let e=JSON.parse((0,An.readFileSync)(_c,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function gp(t){try{let e=t.getAllStates();if(e.length===0)return;(0,An.existsSync)(yc)||(0,An.mkdirSync)(yc,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));(0,An.writeFileSync)(_c,JSON.stringify(n,null,2),"utf-8")}catch{}}function Ei(){if(mp)return;mp=!0;let t=Je();WC(t),HC=setInterval(()=>gp(t),6e4),process.on("exit",()=>gp(t))}function Je(t){return gc||(gc=new Ho(t)),gc}var An,bc,yp,qC,zC,Ho,yc,_c,mp,HC,gc,Wn=Le(()=>{"use strict";An=require("fs"),bc=require("path"),yp=require("@wengine-ai/claude-code-router-shared"),qC=120,zC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Ho=class{states=new Map;config;probeTimer;constructor(e){this.config={...zC,...e}}getKey(e,n){return!e||!n?null:`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n);if(!r)return;let o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(wi(),zh(pp));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n);if(!o)return;let s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){let r=this.getKey(e,n);if(r)return this.states.get(r)}isAvailable(e,n){if(!this.config.enabled)return!0;if(!this.getKey(e,n))return!1;let o=this.getState(e,n);return o?o.status==="open"&&o.rateLimitUntil?!(Date.now()<o.rateLimitUntil):o.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;if(!this.getKey(e,n))return 2;let o=this.getState(e,n);if(!o)return 0;switch(o.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n);if(!o)return;let s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let u=(r??qC)*1e3;a.rateLimitUntil=Date.now()+u}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n);if(!r)return;let o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);r&&this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){let n=this.getKey(e.provider,e.model);n&&this.states.set(n,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},yc=(0,bc.join)(yp.HOME_DIR,"runtime"),_c=(0,bc.join)(yc,"provider-health.json"),mp=!1,HC=null;gc=null});var Ic=X((Bx,tm)=>{"use strict";var Ui=Object.prototype.hasOwnProperty,em=Object.prototype.toString,Vp=Object.defineProperty,Kp=Object.getOwnPropertyDescriptor,Yp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):em.call(e)==="[object Array]"},Qp=function(e){if(!e||em.call(e)!=="[object Object]")return!1;var n=Ui.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Ui.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Ui.call(e,o)},Xp=function(e,n){Vp&&n.name==="__proto__"?Vp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Zp=function(e,n){if(n==="__proto__")if(Ui.call(e,n)){if(Kp)return Kp(e,n).value}else return;return e[n]};tm.exports=function t(){var e,n,r,o,s,a,u=arguments[0],l=1,f=arguments.length,d=!1;for(typeof u=="boolean"&&(d=u,u=arguments[1]||{},l=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});l<f;++l)if(e=arguments[l],e!=null)for(n in e)r=Zp(u,n),o=Zp(e,n),u!==o&&(d&&o&&(Qp(o)||(s=Yp(o)))?(s?(s=!1,a=r&&Yp(r)?r:[]):a=r&&Qp(r)?r:{},Xp(u,{name:n,newValue:t(d,a,o)})):typeof o<"u"&&Xp(u,{name:n,newValue:o}));return u}});var nm=X((Mx,ww)=>{ww.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 om=X((Lx,rm)=>{"use strict";var Ew=nm();rm.exports={pkg:Ew}});var Mc=X(Tt=>{"use strict";var im=Tt&&Tt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.GaxiosError=Tt.GAXIOS_ERROR_SYMBOL=void 0;Tt.defaultErrorRedactor=am;var sm=im(Ic()),kw=im(om()),Nc=kw.default.pkg;Tt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Nc.name}-gaxios-error`);var Bc=class t extends Error{config;response;code;status;error;[Tt.GAXIOS_ERROR_SYMBOL]=Nc.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Tt.GAXIOS_ERROR_SYMBOL in e&&e[Tt.GAXIOS_ERROR_SYMBOL]===Nc.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,sm.default)(!0,{},n),this.response&&(this.response.config=(0,sm.default)(!0,{},this.response.config)),this.response){try{this.response.data=Aw(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=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"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="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 a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
15
- `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Tt.GaxiosError=Bc;function Aw(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 am(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&s.set(u,e)})}function r(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let u=s[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&s.set(u,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(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&&(am({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var cm=X(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.getRetryConfig=Sw;async function Sw(t){let e=um(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 n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||vw)(t))return{shouldRetry:!1,config:t.config};let o=Tw(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function vw(t){let e=um(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 n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function um(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Tw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var Uc=X($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.GaxiosInterceptorManager=void 0;var jc=class extends Set{};$i.GaxiosInterceptorManager=jc});var dm=X((qx,lm)=>{var no=1e3,ro=no*60,oo=ro*60,_r=oo*24,Dw=_r*7,Rw=_r*365.25;lm.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return xw(t);if(n==="number"&&isFinite(t))return e.long?Pw(t):Ow(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function xw(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 n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*Rw;case"weeks":case"week":case"w":return n*Dw;case"days":case"day":case"d":return n*_r;case"hours":case"hour":case"hrs":case"hr":case"h":return n*oo;case"minutes":case"minute":case"mins":case"min":case"m":return n*ro;case"seconds":case"second":case"secs":case"sec":case"s":return n*no;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function Ow(t){var e=Math.abs(t);return e>=_r?Math.round(t/_r)+"d":e>=oo?Math.round(t/oo)+"h":e>=ro?Math.round(t/ro)+"m":e>=no?Math.round(t/no)+"s":t+"ms"}function Pw(t){var e=Math.abs(t);return e>=_r?qi(t,e,_r,"day"):e>=oo?qi(t,e,oo,"hour"):e>=ro?qi(t,e,ro,"minute"):e>=no?qi(t,e,no,"second"):t+" ms"}function qi(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var $c=X((zx,fm)=>{function Fw(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=u,n.humanize=dm(),n.destroy=f,Object.keys(t).forEach(d=>{n[d]=t[d]}),n.names=[],n.skips=[],n.formatters={};function e(d){let p=0;for(let m=0;m<d.length;m++)p=(p<<5)-p+d.charCodeAt(m),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(d){let p,m=null,b,w;function y(...g){if(!y.enabled)return;let _=y,A=Number(new Date),C=A-(p||A);_.diff=C,_.prev=p,_.curr=A,p=A,g[0]=n.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let v=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(R,$)=>{if(R==="%%")return"%";v++;let G=n.formatters[$];if(typeof G=="function"){let P=g[v];R=G.call(_,P),g.splice(v,1),v--}return R}),n.formatArgs.call(_,g),(_.log||n.log).apply(_,g)}return y.namespace=d,y.useColors=n.useColors(),y.color=n.selectColor(d),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==n.namespaces&&(b=n.namespaces,w=n.enabled(d)),w),set:g=>{m=g}}),typeof n.init=="function"&&n.init(y),y}function r(d,p){let m=n(this.namespace+(typeof p>"u"?":":p)+d);return m.log=this.log,m}function o(d){n.save(d),n.namespaces=d,n.names=[],n.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of p)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(d,p){let m=0,b=0,w=-1,y=0;for(;m<d.length;)if(b<p.length&&(p[b]===d[m]||p[b]==="*"))p[b]==="*"?(w=b,y=m,b++):(m++,b++);else if(w!==-1)b=w+1,y++,m=y;else return!1;for(;b<p.length&&p[b]==="*";)b++;return b===p.length}function a(){let d=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),d}function u(d){for(let p of n.skips)if(s(d,p))return!1;for(let p of n.names)if(s(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){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 n.enable(n.load()),n}fm.exports=Fw});var hm=X((ut,zi)=>{ut.formatArgs=Nw;ut.save=Bw;ut.load=Mw;ut.useColors=Iw;ut.storage=Lw();ut.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`."))}})();ut.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 Iw(){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 Nw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+zi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}ut.log=console.debug||console.log||(()=>{});function Bw(t){try{t?ut.storage.setItem("debug",t):ut.storage.removeItem("debug")}catch{}}function Mw(){let t;try{t=ut.storage.getItem("debug")||ut.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Lw(){try{return localStorage}catch{}}zi.exports=$c()(ut);var{formatters:jw}=zi.exports;jw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mm=X((Hx,pm)=>{"use strict";pm.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var _m=X((Wx,ym)=>{"use strict";var Uw=require("os"),gm=require("tty"),Dt=mm(),{env:Ve}=process,Gn;Dt("no-color")||Dt("no-colors")||Dt("color=false")||Dt("color=never")?Gn=0:(Dt("color")||Dt("colors")||Dt("color=true")||Dt("color=always"))&&(Gn=1);"FORCE_COLOR"in Ve&&(Ve.FORCE_COLOR==="true"?Gn=1:Ve.FORCE_COLOR==="false"?Gn=0:Gn=Ve.FORCE_COLOR.length===0?1:Math.min(parseInt(Ve.FORCE_COLOR,10),3));function qc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function zc(t,e){if(Gn===0)return 0;if(Dt("color=16m")||Dt("color=full")||Dt("color=truecolor"))return 3;if(Dt("color=256"))return 2;if(t&&!e&&Gn===void 0)return 0;let n=Gn||0;if(Ve.TERM==="dumb")return n;if(process.platform==="win32"){let r=Uw.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Ve)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Ve)||Ve.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Ve)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ve.TEAMCITY_VERSION)?1:0;if(Ve.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ve){let r=parseInt((Ve.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ve.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ve.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ve.TERM)||"COLORTERM"in Ve?1:n}function $w(t){let e=zc(t,t&&t.isTTY);return qc(e)}ym.exports={supportsColor:$w,stdout:qc(zc(!0,gm.isatty(1))),stderr:qc(zc(!0,gm.isatty(2)))}});var Cm=X((Ke,Wi)=>{var qw=require("tty"),Hi=require("util");Ke.init=Kw;Ke.log=Gw;Ke.formatArgs=Hw;Ke.save=Jw;Ke.load=Vw;Ke.useColors=zw;Ke.destroy=Hi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ke.colors=[6,2,3,4,5,1];try{let t=_m();t&&(t.stderr||t).level>=2&&(Ke.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{}Ke.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function zw(){return"colors"in Ke.inspectOpts?!!Ke.inspectOpts.colors:qw.isatty(process.stderr.fd)}function Hw(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
1
+ "use strict";var SC=Object.create;var fi=Object.defineProperty;var TC=Object.getOwnPropertyDescriptor;var vC=Object.getOwnPropertyNames;var DC=Object.getPrototypeOf,RC=Object.prototype.hasOwnProperty;var Le=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),hi=(t,e)=>{for(var n in e)fi(t,n,{get:e[n],enumerable:!0})},zh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vC(e))!RC.call(t,o)&&o!==n&&fi(t,o,{get:()=>e[o],enumerable:!(r=TC(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?SC(DC(t)):{},zh(e||!t||!t.__esModule?fi(n,"default",{value:t,enumerable:!0}):n,t)),Hh=t=>zh(fi({},"__esModule",{value:!0}),t);var Wh=X((NR,pi)=>{pi.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;pi.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]/;pi.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 ic=X((BR,Gh)=>{var sc=Wh();Gh.exports={isSpaceSeparator(t){return typeof t=="string"&&sc.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||sc.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"||sc.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 Qh=X((MR,Yh)=>{var We=ic(),uc,ot,En,gi,Hn,$t,Ge,dc,qo;Yh.exports=function(e,n){uc=String(e),ot="start",En=[],gi=0,Hn=1,$t=0,Ge=void 0,dc=void 0,qo=void 0;do Ge=xC(),FC[ot]();while(Ge.type!=="eof");return typeof n=="function"?cc({"":qo},"",n):qo};function cc(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),a=cc(r,s,n);a===void 0?delete r[s]:Object.defineProperty(r,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=cc(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var _e,ge,$o,wn,Ee;function xC(){for(_e="default",ge="",$o=!1,wn=1;;){Ee=kn();let t=Vh[_e]();if(t)return t}}function kn(){if(uc[gi])return String.fromCodePoint(uc.codePointAt(gi))}function G(){let t=kn();return t===`
2
+ `?(Hn++,$t=0):t?$t+=t.length:$t++,t&&(gi+=t.length),t}var Vh={default(){switch(Ee){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
3
+ `:case"\r":case"\u2028":case"\u2029":G();return;case"/":G(),_e="comment";return;case void 0:return G(),Ne("eof")}if(We.isSpaceSeparator(Ee)){G();return}return Vh[ot]()},comment(){switch(Ee){case"*":G(),_e="multiLineComment";return;case"/":G(),_e="singleLineComment";return}throw Be(G())},multiLineComment(){switch(Ee){case"*":G(),_e="multiLineCommentAsterisk";return;case void 0:throw Be(G())}G()},multiLineCommentAsterisk(){switch(Ee){case"*":G();return;case"/":G(),_e="default";return;case void 0:throw Be(G())}G(),_e="multiLineComment"},singleLineComment(){switch(Ee){case`
4
+ `:case"\r":case"\u2028":case"\u2029":G(),_e="default";return;case void 0:return G(),Ne("eof")}G()},value(){switch(Ee){case"{":case"[":return Ne("punctuator",G());case"n":return G(),dr("ull"),Ne("null",null);case"t":return G(),dr("rue"),Ne("boolean",!0);case"f":return G(),dr("alse"),Ne("boolean",!1);case"-":case"+":G()==="-"&&(wn=-1),_e="sign";return;case".":ge=G(),_e="decimalPointLeading";return;case"0":ge=G(),_e="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ge=G(),_e="decimalInteger";return;case"I":return G(),dr("nfinity"),Ne("numeric",1/0);case"N":return G(),dr("aN"),Ne("numeric",NaN);case'"':case"'":$o=G()==='"',ge="",_e="string";return}throw Be(G())},identifierNameStartEscape(){if(Ee!=="u")throw Be(G());G();let t=lc();switch(t){case"$":case"_":break;default:if(!We.isIdStartChar(t))throw Jh();break}ge+=t,_e="identifierName"},identifierName(){switch(Ee){case"$":case"_":case"\u200C":case"\u200D":ge+=G();return;case"\\":G(),_e="identifierNameEscape";return}if(We.isIdContinueChar(Ee)){ge+=G();return}return Ne("identifier",ge)},identifierNameEscape(){if(Ee!=="u")throw Be(G());G();let t=lc();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!We.isIdContinueChar(t))throw Jh();break}ge+=t,_e="identifierName"},sign(){switch(Ee){case".":ge=G(),_e="decimalPointLeading";return;case"0":ge=G(),_e="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":ge=G(),_e="decimalInteger";return;case"I":return G(),dr("nfinity"),Ne("numeric",wn*(1/0));case"N":return G(),dr("aN"),Ne("numeric",NaN)}throw Be(G())},zero(){switch(Ee){case".":ge+=G(),_e="decimalPoint";return;case"e":case"E":ge+=G(),_e="decimalExponent";return;case"x":case"X":ge+=G(),_e="hexadecimal";return}return Ne("numeric",wn*0)},decimalInteger(){switch(Ee){case".":ge+=G(),_e="decimalPoint";return;case"e":case"E":ge+=G(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=G();return}return Ne("numeric",wn*Number(ge))},decimalPointLeading(){if(We.isDigit(Ee)){ge+=G(),_e="decimalFraction";return}throw Be(G())},decimalPoint(){switch(Ee){case"e":case"E":ge+=G(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=G(),_e="decimalFraction";return}return Ne("numeric",wn*Number(ge))},decimalFraction(){switch(Ee){case"e":case"E":ge+=G(),_e="decimalExponent";return}if(We.isDigit(Ee)){ge+=G();return}return Ne("numeric",wn*Number(ge))},decimalExponent(){switch(Ee){case"+":case"-":ge+=G(),_e="decimalExponentSign";return}if(We.isDigit(Ee)){ge+=G(),_e="decimalExponentInteger";return}throw Be(G())},decimalExponentSign(){if(We.isDigit(Ee)){ge+=G(),_e="decimalExponentInteger";return}throw Be(G())},decimalExponentInteger(){if(We.isDigit(Ee)){ge+=G();return}return Ne("numeric",wn*Number(ge))},hexadecimal(){if(We.isHexDigit(Ee)){ge+=G(),_e="hexadecimalInteger";return}throw Be(G())},hexadecimalInteger(){if(We.isHexDigit(Ee)){ge+=G();return}return Ne("numeric",wn*Number(ge))},string(){switch(Ee){case"\\":G(),ge+=OC();return;case'"':if($o)return G(),Ne("string",ge);ge+=G();return;case"'":if(!$o)return G(),Ne("string",ge);ge+=G();return;case`
5
+ `:case"\r":throw Be(G());case"\u2028":case"\u2029":IC(Ee);break;case void 0:throw Be(G())}ge+=G()},start(){switch(Ee){case"{":case"[":return Ne("punctuator",G())}_e="value"},beforePropertyName(){switch(Ee){case"$":case"_":ge=G(),_e="identifierName";return;case"\\":G(),_e="identifierNameStartEscape";return;case"}":return Ne("punctuator",G());case'"':case"'":$o=G()==='"',_e="string";return}if(We.isIdStartChar(Ee)){ge+=G(),_e="identifierName";return}throw Be(G())},afterPropertyName(){if(Ee===":")return Ne("punctuator",G());throw Be(G())},beforePropertyValue(){_e="value"},afterPropertyValue(){switch(Ee){case",":case"}":return Ne("punctuator",G())}throw Be(G())},beforeArrayValue(){if(Ee==="]")return Ne("punctuator",G());_e="value"},afterArrayValue(){switch(Ee){case",":case"]":return Ne("punctuator",G())}throw Be(G())},end(){throw Be(G())}};function Ne(t,e){return{type:t,value:e,line:Hn,column:$t}}function dr(t){for(let e of t){if(kn()!==e)throw Be(G());G()}}function OC(){switch(kn()){case"b":return G(),"\b";case"f":return G(),"\f";case"n":return G(),`
6
+ `;case"r":return G(),"\r";case"t":return G()," ";case"v":return G(),"\v";case"0":if(G(),We.isDigit(kn()))throw Be(G());return"\0";case"x":return G(),PC();case"u":return G(),lc();case`
7
+ `:case"\u2028":case"\u2029":return G(),"";case"\r":return G(),kn()===`
8
+ `&&G(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Be(G());case void 0:throw Be(G())}return G()}function PC(){let t="",e=kn();if(!We.isHexDigit(e)||(t+=G(),e=kn(),!We.isHexDigit(e)))throw Be(G());return t+=G(),String.fromCodePoint(parseInt(t,16))}function lc(){let t="",e=4;for(;e-- >0;){let n=kn();if(!We.isHexDigit(n))throw Be(G());t+=G()}return String.fromCodePoint(parseInt(t,16))}var FC={start(){if(Ge.type==="eof")throw fr();ac()},beforePropertyName(){switch(Ge.type){case"identifier":case"string":dc=Ge.value,ot="afterPropertyName";return;case"punctuator":mi();return;case"eof":throw fr()}},afterPropertyName(){if(Ge.type==="eof")throw fr();ot="beforePropertyValue"},beforePropertyValue(){if(Ge.type==="eof")throw fr();ac()},beforeArrayValue(){if(Ge.type==="eof")throw fr();if(Ge.type==="punctuator"&&Ge.value==="]"){mi();return}ac()},afterPropertyValue(){if(Ge.type==="eof")throw fr();switch(Ge.value){case",":ot="beforePropertyName";return;case"}":mi()}},afterArrayValue(){if(Ge.type==="eof")throw fr();switch(Ge.value){case",":ot="beforeArrayValue";return;case"]":mi()}},end(){}};function ac(){let t;switch(Ge.type){case"punctuator":switch(Ge.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=Ge.value;break}if(qo===void 0)qo=t;else{let e=En[En.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,dc,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")En.push(t),Array.isArray(t)?ot="beforeArrayValue":ot="beforePropertyName";else{let e=En[En.length-1];e==null?ot="end":Array.isArray(e)?ot="afterArrayValue":ot="afterPropertyValue"}}function mi(){En.pop();let t=En[En.length-1];t==null?ot="end":Array.isArray(t)?ot="afterArrayValue":ot="afterPropertyValue"}function Be(t){return yi(t===void 0?`JSON5: invalid end of input at ${Hn}:${$t}`:`JSON5: invalid character '${Kh(t)}' at ${Hn}:${$t}`)}function fr(){return yi(`JSON5: invalid end of input at ${Hn}:${$t}`)}function Jh(){return $t-=5,yi(`JSON5: invalid identifier character at ${Hn}:${$t}`)}function IC(t){console.warn(`JSON5: '${Kh(t)}' in strings is not valid ECMAScript; consider escaping`)}function Kh(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 n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function yi(t){let e=new SyntaxError(t);return e.lineNumber=Hn,e.columnNumber=$t,e}});var Zh=X((LR,Xh)=>{var fc=ic();Xh.exports=function(e,n,r){let o=[],s="",a,u,l="",f;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,f=n.quote,n=n.replacer),typeof n=="function")u=n;else if(Array.isArray(n)){a=[];for(let y of n){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&a.indexOf(g)<0&&a.push(g)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),d("",{"":e});function d(y,g){let _=g[y];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(y):typeof _.toJSON=="function"&&(_=_.toJSON(y))),u&&(_=u.call(g,y,_)),_ instanceof Number?_=Number(_):_ instanceof String?_=String(_):_ instanceof Boolean&&(_=_.valueOf()),_){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof _=="string")return h(_,!1);if(typeof _=="number")return String(_);if(typeof _=="object")return Array.isArray(_)?w(_):m(_)}function h(y){let g={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},E="";for(let S=0;S<y.length;S++){let v=y[S];switch(v){case"'":case'"':g[v]++,E+=v;continue;case"\0":if(fc.isDigit(y[S+1])){E+="\\x00";continue}}if(_[v]){E+=_[v];continue}if(v<" "){let R=v.charCodeAt(0).toString(16);E+="\\x"+("00"+R).substring(R.length);continue}E+=v}let b=f||Object.keys(g).reduce((S,v)=>g[S]<g[v]?S:v);return E=E.replace(new RegExp(b,"g"),_[b]),b+E+b}function m(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let _=a||Object.keys(y),E=[];for(let S of _){let v=d(S,y);if(v!==void 0){let R=C(S)+":";l!==""&&(R+=" "),R+=v,E.push(R)}}let b;if(E.length===0)b="{}";else{let S;if(l==="")S=E.join(","),b="{"+S+"}";else{let v=`,
9
+ `+s;S=E.join(v),b=`{
10
+ `+s+S+`,
11
+ `+g+"}"}}return o.pop(),s=g,b}function C(y){if(y.length===0)return h(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!fc.isIdStartChar(g))return h(y,!0);for(let _=g.length;_<y.length;_++)if(!fc.isIdContinueChar(String.fromCodePoint(y.codePointAt(_))))return h(y,!0);return y}function w(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let _=[];for(let b=0;b<y.length;b++){let S=d(String(b),y);_.push(S!==void 0?S:"null")}let E;if(_.length===0)E="[]";else if(l==="")E="["+_.join(",")+"]";else{let b=`,
12
+ `+s,S=_.join(b);E=`[
13
+ `+s+S+`,
14
+ `+g+"]"}return o.pop(),s=g,E}}});var hc=X((jR,ep)=>{var NC=Qh(),BC=Zh(),MC={parse:NC,stringify:BC};ep.exports=MC});var mp={};hi(mp,{getFallbackPromotionStore:()=>Jr,resetFallbackPromotionStore:()=>qC});function Jr(t){return pr||(pr=new gc,t&&pr.configure(t)),pr}function qC(){pr&&(pr.clearAll(),pr=null)}var $C,gc,pr,wi=Le(()=>{"use strict";Wn();$C=600*1e3,gc=class{promotions=new Map;enabled=!0;ttlMs=$C;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let u=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(u,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...f]=a.promotedModel.split(","),d=f.join(",");if(!Je().isAvailable(l,d))return this.promotions.delete(s),null;let m=o.find(w=>w.name.toLowerCase()===l.toLowerCase()),C=m?.models?.find(w=>String(w).toLowerCase()===d.toLowerCase());return!m||!C||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${C}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},pr=null});function GC(t){try{if(!(0,An.existsSync)(bc))return;let e=JSON.parse((0,An.readFileSync)(bc,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function yp(t){try{let e=t.getAllStates();if(e.length===0)return;(0,An.existsSync)(_c)||(0,An.mkdirSync)(_c,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));(0,An.writeFileSync)(bc,JSON.stringify(n,null,2),"utf-8")}catch{}}function Ei(){if(gp)return;gp=!0;let t=Je();GC(t),WC=setInterval(()=>yp(t),6e4),process.on("exit",()=>yp(t))}function Je(t){return yc||(yc=new Ho(t)),yc}var An,Cc,_p,zC,HC,Ho,_c,bc,gp,WC,yc,Wn=Le(()=>{"use strict";An=require("fs"),Cc=require("path"),_p=require("@wengine-ai/claude-code-router-shared"),zC=120,HC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Ho=class{states=new Map;config;probeTimer;constructor(e){this.config={...HC,...e}}getKey(e,n){return!e||!n?null:`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n);if(!r)return;let o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(wi(),Hh(mp));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n);if(!o)return;let s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){let r=this.getKey(e,n);if(r)return this.states.get(r)}isAvailable(e,n){if(!this.config.enabled)return!0;if(!this.getKey(e,n))return!1;let o=this.getState(e,n);return o?o.status==="open"&&o.rateLimitUntil?!(Date.now()<o.rateLimitUntil):o.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;if(!this.getKey(e,n))return 2;let o=this.getState(e,n);if(!o)return 0;switch(o.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n);if(!o)return;let s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let u=(r??zC)*1e3;a.rateLimitUntil=Date.now()+u}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n);if(!r)return;let o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);r&&this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){let n=this.getKey(e.provider,e.model);n&&this.states.set(n,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},_c=(0,Cc.join)(_p.HOME_DIR,"runtime"),bc=(0,Cc.join)(_c,"provider-health.json"),gp=!1,WC=null;yc=null});var Nc=X((Mx,nm)=>{"use strict";var Ui=Object.prototype.hasOwnProperty,tm=Object.prototype.toString,Kp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,Qp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):tm.call(e)==="[object Array]"},Xp=function(e){if(!e||tm.call(e)!=="[object Object]")return!1;var n=Ui.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Ui.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Ui.call(e,o)},Zp=function(e,n){Kp&&n.name==="__proto__"?Kp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},em=function(e,n){if(n==="__proto__")if(Ui.call(e,n)){if(Yp)return Yp(e,n).value}else return;return e[n]};nm.exports=function t(){var e,n,r,o,s,a,u=arguments[0],l=1,f=arguments.length,d=!1;for(typeof u=="boolean"&&(d=u,u=arguments[1]||{},l=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});l<f;++l)if(e=arguments[l],e!=null)for(n in e)r=em(u,n),o=em(e,n),u!==o&&(d&&o&&(Xp(o)||(s=Qp(o)))?(s?(s=!1,a=r&&Qp(r)?r:[]):a=r&&Xp(r)?r:{},Zp(u,{name:n,newValue:t(d,a,o)})):typeof o<"u"&&Zp(u,{name:n,newValue:o}));return u}});var rm=X((Lx,Ew)=>{Ew.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 sm=X((jx,om)=>{"use strict";var kw=rm();om.exports={pkg:kw}});var Lc=X(Dt=>{"use strict";var am=Dt&&Dt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.GaxiosError=Dt.GAXIOS_ERROR_SYMBOL=void 0;Dt.defaultErrorRedactor=um;var im=am(Nc()),Aw=am(sm()),Bc=Aw.default.pkg;Dt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Bc.name}-gaxios-error`);var Mc=class t extends Error{config;response;code;status;error;[Dt.GAXIOS_ERROR_SYMBOL]=Bc.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Dt.GAXIOS_ERROR_SYMBOL in e&&e[Dt.GAXIOS_ERROR_SYMBOL]===Bc.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,im.default)(!0,{},n),this.response&&(this.response.config=(0,im.default)(!0,{},this.response.config)),this.response){try{this.response.data=Sw(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=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"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="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 a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
15
+ `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Dt.GaxiosError=Mc;function Sw(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 um(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&s.set(u,e)})}function r(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let u=s[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&s.set(u,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(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&&(um({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var lm=X(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.getRetryConfig=Tw;async function Tw(t){let e=cm(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 n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||vw)(t))return{shouldRetry:!1,config:t.config};let o=Dw(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function vw(t){let e=cm(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 n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function cm(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Dw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var $c=X($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.GaxiosInterceptorManager=void 0;var Uc=class extends Set{};$i.GaxiosInterceptorManager=Uc});var fm=X((zx,dm)=>{var no=1e3,ro=no*60,oo=ro*60,_r=oo*24,Rw=_r*7,xw=_r*365.25;dm.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return Ow(t);if(n==="number"&&isFinite(t))return e.long?Fw(t):Pw(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Ow(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 n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*xw;case"weeks":case"week":case"w":return n*Rw;case"days":case"day":case"d":return n*_r;case"hours":case"hour":case"hrs":case"hr":case"h":return n*oo;case"minutes":case"minute":case"mins":case"min":case"m":return n*ro;case"seconds":case"second":case"secs":case"sec":case"s":return n*no;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function Pw(t){var e=Math.abs(t);return e>=_r?Math.round(t/_r)+"d":e>=oo?Math.round(t/oo)+"h":e>=ro?Math.round(t/ro)+"m":e>=no?Math.round(t/no)+"s":t+"ms"}function Fw(t){var e=Math.abs(t);return e>=_r?qi(t,e,_r,"day"):e>=oo?qi(t,e,oo,"hour"):e>=ro?qi(t,e,ro,"minute"):e>=no?qi(t,e,no,"second"):t+" ms"}function qi(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var qc=X((Hx,hm)=>{function Iw(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=u,n.humanize=fm(),n.destroy=f,Object.keys(t).forEach(d=>{n[d]=t[d]}),n.names=[],n.skips=[],n.formatters={};function e(d){let h=0;for(let m=0;m<d.length;m++)h=(h<<5)-h+d.charCodeAt(m),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=e;function n(d){let h,m=null,C,w;function y(...g){if(!y.enabled)return;let _=y,E=Number(new Date),b=E-(h||E);_.diff=b,_.prev=h,_.curr=E,h=E,g[0]=n.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let S=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(R,$)=>{if(R==="%%")return"%";S++;let H=n.formatters[$];if(typeof H=="function"){let P=g[S];R=H.call(_,P),g.splice(S,1),S--}return R}),n.formatArgs.call(_,g),(_.log||n.log).apply(_,g)}return y.namespace=d,y.useColors=n.useColors(),y.color=n.selectColor(d),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(C!==n.namespaces&&(C=n.namespaces,w=n.enabled(d)),w),set:g=>{m=g}}),typeof n.init=="function"&&n.init(y),y}function r(d,h){let m=n(this.namespace+(typeof h>"u"?":":h)+d);return m.log=this.log,m}function o(d){n.save(d),n.namespaces=d,n.names=[],n.skips=[];let h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of h)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(d,h){let m=0,C=0,w=-1,y=0;for(;m<d.length;)if(C<h.length&&(h[C]===d[m]||h[C]==="*"))h[C]==="*"?(w=C,y=m,C++):(m++,C++);else if(w!==-1)C=w+1,y++,m=y;else return!1;for(;C<h.length&&h[C]==="*";)C++;return C===h.length}function a(){let d=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),d}function u(d){for(let h of n.skips)if(s(d,h))return!1;for(let h of n.names)if(s(d,h))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){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 n.enable(n.load()),n}hm.exports=Iw});var pm=X((ut,zi)=>{ut.formatArgs=Bw;ut.save=Mw;ut.load=Lw;ut.useColors=Nw;ut.storage=jw();ut.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`."))}})();ut.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 Nw(){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 Bw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+zi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}ut.log=console.debug||console.log||(()=>{});function Mw(t){try{t?ut.storage.setItem("debug",t):ut.storage.removeItem("debug")}catch{}}function Lw(){let t;try{t=ut.storage.getItem("debug")||ut.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function jw(){try{return localStorage}catch{}}zi.exports=qc()(ut);var{formatters:Uw}=zi.exports;Uw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var gm=X((Wx,mm)=>{"use strict";mm.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var bm=X((Gx,_m)=>{"use strict";var $w=require("os"),ym=require("tty"),Rt=gm(),{env:Ve}=process,Gn;Rt("no-color")||Rt("no-colors")||Rt("color=false")||Rt("color=never")?Gn=0:(Rt("color")||Rt("colors")||Rt("color=true")||Rt("color=always"))&&(Gn=1);"FORCE_COLOR"in Ve&&(Ve.FORCE_COLOR==="true"?Gn=1:Ve.FORCE_COLOR==="false"?Gn=0:Gn=Ve.FORCE_COLOR.length===0?1:Math.min(parseInt(Ve.FORCE_COLOR,10),3));function zc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Hc(t,e){if(Gn===0)return 0;if(Rt("color=16m")||Rt("color=full")||Rt("color=truecolor"))return 3;if(Rt("color=256"))return 2;if(t&&!e&&Gn===void 0)return 0;let n=Gn||0;if(Ve.TERM==="dumb")return n;if(process.platform==="win32"){let r=$w.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Ve)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Ve)||Ve.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Ve)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ve.TEAMCITY_VERSION)?1:0;if(Ve.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ve){let r=parseInt((Ve.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ve.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ve.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ve.TERM)||"COLORTERM"in Ve?1:n}function qw(t){let e=Hc(t,t&&t.isTTY);return zc(e)}_m.exports={supportsColor:qw,stdout:zc(Hc(!0,ym.isatty(1))),stderr:zc(Hc(!0,ym.isatty(2)))}});var wm=X((Ke,Wi)=>{var zw=require("tty"),Hi=require("util");Ke.init=Yw;Ke.log=Jw;Ke.formatArgs=Ww;Ke.save=Vw;Ke.load=Kw;Ke.useColors=Hw;Ke.destroy=Hi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ke.colors=[6,2,3,4,5,1];try{let t=bm();t&&(t.stderr||t).level>=2&&(Ke.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{}Ke.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function Hw(){return"colors"in Ke.inspectOpts?!!Ke.inspectOpts.colors:zw.isatty(process.stderr.fd)}function Ww(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
16
16
  `).join(`
17
- `+s),t.push(o+"m+"+Wi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Ww()+e+" "+t[0]}function Ww(){return Ke.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Gw(...t){return process.stderr.write(Hi.formatWithOptions(Ke.inspectOpts,...t)+`
18
- `)}function Jw(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Vw(){return process.env.DEBUG}function Kw(t){t.inspectOpts={};let e=Object.keys(Ke.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=Ke.inspectOpts[e[n]]}Wi.exports=$c()(Ke);var{formatters:bm}=Wi.exports;bm.o=function(t){return this.inspectOpts.colors=this.useColors,Hi.inspect(t,this.inspectOpts).split(`
19
- `).map(e=>e.trim()).join(" ")};bm.O=function(t){return this.inspectOpts.colors=this.useColors,Hi.inspect(t,this.inspectOpts)}});var Wc=X((Gx,Hc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Hc.exports=hm():Hc.exports=Cm()});var km=X(ct=>{"use strict";var Yw=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Qw=ct&&ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),wm=ct&&ct.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Yw(e,t,n);return Qw(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0});ct.req=ct.json=ct.toBuffer=void 0;var Xw=wm(require("http")),Zw=wm(require("https"));async function Em(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}ct.toBuffer=Em;async function eE(t){let n=(await Em(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}ct.json=eE;function tE(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?Zw:Xw).request(t,e),o=new Promise((s,a)=>{r.once("response",s).once("error",a).end()});return r.then=o.then.bind(o),r}ct.req=tE});var Tm=X(pt=>{"use strict";var Sm=pt&&pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),nE=pt&&pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vm=pt&&pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Sm(e,t,n);return nE(e,t),e},rE=pt&&pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Sm(e,t,n)};Object.defineProperty(pt,"__esModule",{value:!0});pt.Agent=void 0;var oE=vm(require("net")),Am=vm(require("http")),sE=require("https");rE(km(),pt);var Zt=Symbol("AgentBaseInternalState"),Gc=class extends Am.Agent{constructor(e){super(e),this[Zt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
20
- `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new oE.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?sE.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(u=>{if(this.decrementSockets(s,a),u instanceof Am.Agent)try{return u.addRequest(e,o)}catch(l){return r(l)}this[Zt].currentSocket=u,super.createSocket(e,n,r)},u=>{this.decrementSockets(s,a),r(u)})}createConnection(){let e=this[Zt].currentSocket;if(this[Zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Zt]&&(this[Zt].defaultPort=e)}get protocol(){return this[Zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Zt]&&(this[Zt].protocol=e)}};pt.Agent=Gc});var Dm=X(so=>{"use strict";var iE=so&&so.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(so,"__esModule",{value:!0});so.parseProxyResponse=void 0;var aE=iE(Wc()),Gi=(0,aE.default)("https-proxy-agent:parse-proxy-response");function uE(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",u),t.removeListener("error",l),t.removeListener("readable",s)}function u(){a(),Gi("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),Gi("onerror %o",d),n(d)}function f(d){o.push(d),r+=d.length;let p=Buffer.concat(o,r),m=p.indexOf(`\r
17
+ `+s),t.push(o+"m+"+Wi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Gw()+e+" "+t[0]}function Gw(){return Ke.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Jw(...t){return process.stderr.write(Hi.formatWithOptions(Ke.inspectOpts,...t)+`
18
+ `)}function Vw(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Kw(){return process.env.DEBUG}function Yw(t){t.inspectOpts={};let e=Object.keys(Ke.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=Ke.inspectOpts[e[n]]}Wi.exports=qc()(Ke);var{formatters:Cm}=Wi.exports;Cm.o=function(t){return this.inspectOpts.colors=this.useColors,Hi.inspect(t,this.inspectOpts).split(`
19
+ `).map(e=>e.trim()).join(" ")};Cm.O=function(t){return this.inspectOpts.colors=this.useColors,Hi.inspect(t,this.inspectOpts)}});var Gc=X((Jx,Wc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Wc.exports=pm():Wc.exports=wm()});var Am=X(ct=>{"use strict";var Qw=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Xw=ct&&ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Em=ct&&ct.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Qw(e,t,n);return Xw(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0});ct.req=ct.json=ct.toBuffer=void 0;var Zw=Em(require("http")),eE=Em(require("https"));async function km(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}ct.toBuffer=km;async function tE(t){let n=(await km(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}ct.json=tE;function nE(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?eE:Zw).request(t,e),o=new Promise((s,a)=>{r.once("response",s).once("error",a).end()});return r.then=o.then.bind(o),r}ct.req=nE});var Dm=X(mt=>{"use strict";var Tm=mt&&mt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),rE=mt&&mt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vm=mt&&mt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Tm(e,t,n);return rE(e,t),e},oE=mt&&mt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tm(e,t,n)};Object.defineProperty(mt,"__esModule",{value:!0});mt.Agent=void 0;var sE=vm(require("net")),Sm=vm(require("http")),iE=require("https");oE(Am(),mt);var Zt=Symbol("AgentBaseInternalState"),Jc=class extends Sm.Agent{constructor(e){super(e),this[Zt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
20
+ `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new sE.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?iE.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(u=>{if(this.decrementSockets(s,a),u instanceof Sm.Agent)try{return u.addRequest(e,o)}catch(l){return r(l)}this[Zt].currentSocket=u,super.createSocket(e,n,r)},u=>{this.decrementSockets(s,a),r(u)})}createConnection(){let e=this[Zt].currentSocket;if(this[Zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Zt]&&(this[Zt].defaultPort=e)}get protocol(){return this[Zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Zt]&&(this[Zt].protocol=e)}};mt.Agent=Jc});var Rm=X(so=>{"use strict";var aE=so&&so.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(so,"__esModule",{value:!0});so.parseProxyResponse=void 0;var uE=aE(Gc()),Gi=(0,uE.default)("https-proxy-agent:parse-proxy-response");function cE(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",u),t.removeListener("error",l),t.removeListener("readable",s)}function u(){a(),Gi("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),Gi("onerror %o",d),n(d)}function f(d){o.push(d),r+=d.length;let h=Buffer.concat(o,r),m=h.indexOf(`\r
21
21
  \r
22
- `);if(m===-1){Gi("have not received end of HTTP headers yet..."),s();return}let b=p.slice(0,m).toString("ascii").split(`\r
23
- `),w=b.shift();if(!w)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let y=w.split(" "),g=+y[1],_=y.slice(2).join(" "),A={};for(let C of b){if(!C)continue;let v=C.indexOf(":");if(v===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let T=C.slice(0,v).toLowerCase(),R=C.slice(v+1).trimStart(),$=A[T];typeof $=="string"?A[T]=[$,R]:Array.isArray($)?$.push(R):A[T]=R}Gi("got proxy server response: %o %o",w,A),a(),e({connect:{statusCode:g,statusText:_,headers:A},buffered:p})}t.on("error",l),t.on("end",u),s()})}so.parseProxyResponse=uE});var Im=X(Rt=>{"use strict";var cE=Rt&&Rt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lE=Rt&&Rt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Pm=Rt&&Rt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&cE(e,t,n);return lE(e,t),e},Fm=Rt&&Rt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rt,"__esModule",{value:!0});Rt.HttpsProxyAgent=void 0;var Ji=Pm(require("net")),Rm=Pm(require("tls")),dE=Fm(require("assert")),fE=Fm(Wc()),hE=Tm(),pE=require("url"),mE=Dm(),Vo=(0,fE.default)("https-proxy-agent"),xm=t=>t.servername===void 0&&t.host&&!Ji.isIP(t.host)?{...t,servername:t.host}:t,Vi=class extends hE.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new pE.URL(e):e,this.proxyHeaders=n?.headers??{},Vo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Om(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Vo("Creating `tls.Socket`: %o",this.connectOpts),o=Rm.connect(xm(this.connectOpts))):(Vo("Creating `net.Socket`: %o",this.connectOpts),o=Ji.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=Ji.isIPv6(n.host)?`[${n.host}]`:n.host,u=`CONNECT ${a}:${n.port} HTTP/1.1\r
22
+ `);if(m===-1){Gi("have not received end of HTTP headers yet..."),s();return}let C=h.slice(0,m).toString("ascii").split(`\r
23
+ `),w=C.shift();if(!w)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let y=w.split(" "),g=+y[1],_=y.slice(2).join(" "),E={};for(let b of C){if(!b)continue;let S=b.indexOf(":");if(S===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${b}"`));let v=b.slice(0,S).toLowerCase(),R=b.slice(S+1).trimStart(),$=E[v];typeof $=="string"?E[v]=[$,R]:Array.isArray($)?$.push(R):E[v]=R}Gi("got proxy server response: %o %o",w,E),a(),e({connect:{statusCode:g,statusText:_,headers:E},buffered:h})}t.on("error",l),t.on("end",u),s()})}so.parseProxyResponse=cE});var Nm=X(xt=>{"use strict";var lE=xt&&xt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dE=xt&&xt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Fm=xt&&xt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&lE(e,t,n);return dE(e,t),e},Im=xt&&xt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xt,"__esModule",{value:!0});xt.HttpsProxyAgent=void 0;var Ji=Fm(require("net")),xm=Fm(require("tls")),fE=Im(require("assert")),hE=Im(Gc()),pE=Dm(),mE=require("url"),gE=Rm(),Vo=(0,hE.default)("https-proxy-agent"),Om=t=>t.servername===void 0&&t.host&&!Ji.isIP(t.host)?{...t,servername:t.host}:t,Vi=class extends pE.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new mE.URL(e):e,this.proxyHeaders=n?.headers??{},Vo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Pm(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Vo("Creating `tls.Socket`: %o",this.connectOpts),o=xm.connect(Om(this.connectOpts))):(Vo("Creating `net.Socket`: %o",this.connectOpts),o=Ji.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=Ji.isIPv6(n.host)?`[${n.host}]`:n.host,u=`CONNECT ${a}:${n.port} HTTP/1.1\r
24
24
  `;if(r.username||r.password){let m=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(m).toString("base64")}`}s.Host=`${a}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let m of Object.keys(s))u+=`${m}: ${s[m]}\r
25
- `;let l=(0,mE.parseProxyResponse)(o);o.write(`${u}\r
26
- `);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",gE),n.secureEndpoint?(Vo("Upgrading socket connection to TLS"),Rm.connect({...Om(xm(n),"host","path","port"),socket:o})):o;o.destroy();let p=new Ji.Socket({writable:!1});return p.readable=!0,e.once("socket",m=>{Vo("Replaying proxy buffer for failed request"),(0,dE.default)(m.listenerCount("data")>0),m.push(d),m.push(null)}),p}};Vi.protocols=["http","https"];Rt.HttpsProxyAgent=Vi;function gE(t){t.resume()}function Om(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function yE(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 n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let d=1;d<n.length;d++)n[d]==="base64"?o=!0:n[d]&&(a+=`;${n[d]}`,n[d].indexOf("charset=")===0&&(r=n[d].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let u=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,u);return f.type=s,f.typeFull=a,f.charset=r,f}var Nm,Bm=Le(()=>{Nm=yE});var Lm=X((Ki,Mm)=>{(function(t,e){typeof Ki=="object"&&typeof Mm<"u"?e(Ki):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ki,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=e;function o(i,c){try{Object.defineProperty(i,"name",{value:c,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,u=Promise.reject.bind(s);function l(i){return new s(i)}function f(i){return l(c=>c(i))}function d(i){return u(i)}function p(i,c,h){return a.call(i,c,h)}function m(i,c,h){p(p(i,c,h),void 0,r)}function b(i,c){m(i,c)}function w(i,c){m(i,void 0,c)}function y(i,c,h){return p(i,c,h)}function g(i){p(i,void 0,r)}let _=i=>{if(typeof queueMicrotask=="function")_=queueMicrotask;else{let c=f(void 0);_=h=>p(c,h)}return _(i)};function A(i,c,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,c,h)}function C(i,c,h){try{return f(A(i,c,h))}catch(k){return d(k)}}let v=16384;class T{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(c){let h=this._back,k=h;h._elements.length===v-1&&(k={_elements:[],_next:void 0}),h._elements.push(c),k!==h&&(this._back=k,h._next=k),++this._size}shift(){let c=this._front,h=c,k=this._cursor,x=k+1,j=c._elements,q=j[k];return x===v&&(h=c._next,x=0),--this._size,this._cursor=x,c!==h&&(this._front=h),j[k]=void 0,q}forEach(c){let h=this._cursor,k=this._front,x=k._elements;for(;(h!==x.length||k._next!==void 0)&&!(h===x.length&&(k=k._next,x=k._elements,h=0,x.length===0));)c(x[h]),++h}peek(){let c=this._front,h=this._cursor;return c._elements[h]}}let R=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),G=Symbol("[[CancelSteps]]"),P=Symbol("[[PullSteps]]"),K=Symbol("[[ReleaseSteps]]");function z(i,c){i._ownerReadableStream=c,c._reader=i,c._state==="readable"?oe(i):c._state==="closed"?he(i):se(i,c._storedError)}function Y(i,c){let h=i._ownerReadableStream;return Lt(h,c)}function Q(i){let c=i._ownerReadableStream;c._state==="readable"?J(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Z(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),c._readableStreamController[K](),c._reader=void 0,i._ownerReadableStream=void 0}function ee(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function oe(i){i._closedPromise=l((c,h)=>{i._closedPromise_resolve=c,i._closedPromise_reject=h})}function se(i,c){oe(i),J(i,c)}function he(i){oe(i),ue(i)}function J(i,c){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(c),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function Z(i,c){se(i,c)}function ue(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let je=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},Ce=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function V(i){return typeof i=="object"||typeof i=="function"}function ae(i,c){if(i!==void 0&&!V(i))throw new TypeError(`${c} is not an object.`)}function te(i,c){if(typeof i!="function")throw new TypeError(`${c} is not a function.`)}function ve(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Oe(i,c){if(!ve(i))throw new TypeError(`${c} is not an object.`)}function Ue(i,c,h){if(i===void 0)throw new TypeError(`Parameter ${c} is required in '${h}'.`)}function E(i,c,h){if(i===void 0)throw new TypeError(`${c} is required in '${h}'.`)}function S(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(Ce(i))}function F(i,c){let k=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!je(x))throw new TypeError(`${c} is not a finite number`);if(x=M(x),x<0||x>k)throw new TypeError(`${c} is outside the accepted range of 0 to ${k}, inclusive`);return!je(x)||x===0?0:x}function N(i,c){if(!Un(i))throw new TypeError(`${c} is not a ReadableStream.`)}function U(i){return new H(i)}function O(i,c){i._reader._readRequests.push(c)}function I(i,c,h){let x=i._reader._readRequests.shift();h?x._closeSteps():x._chunkSteps(c)}function L(i){return i._reader._readRequests.length}function B(i){let c=i._reader;return!(c===void 0||!re(c))}class H{constructor(c){if(Ue(c,1,"ReadableStreamDefaultReader"),N(c,"First parameter"),$n(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");z(this,c),this._readRequests=new T}get closed(){return re(this)?this._closedPromise:d(Me("closed"))}cancel(c=void 0){return re(this)?this._ownerReadableStream===void 0?d(ee("cancel")):Y(this,c):d(Me("cancel"))}read(){if(!re(this))return d(Me("read"));if(this._ownerReadableStream===void 0)return d(ee("read from"));let c,h,k=l((j,q)=>{c=j,h=q});return ie(this,{_chunkSteps:j=>c({value:j,done:!1}),_closeSteps:()=>c({value:void 0,done:!0}),_errorSteps:j=>h(j)}),k}releaseLock(){if(!re(this))throw Me("releaseLock");this._ownerReadableStream!==void 0&&Ae(this)}}Object.defineProperties(H.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(H.prototype.cancel,"cancel"),o(H.prototype.read,"read"),o(H.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(H.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function re(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof H}function ie(i,c){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?c._closeSteps():h._state==="errored"?c._errorSteps(h._storedError):h._readableStreamController[P](c)}function Ae(i){Q(i);let c=new TypeError("Reader was released");Ie(i,c)}function Ie(i,c){let h=i._readRequests;i._readRequests=new T,h.forEach(k=>{k._errorSteps(c)})}function Me(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let ke=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(c,h){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=c,this._preventCancel=h}next(){let c=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,c,c):c(),this._ongoingPromise}return(c){let h=()=>this._returnSteps(c);return this._ongoingPromise?y(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let c=this._reader,h,k,x=l((q,ne)=>{h=q,k=ne});return ie(c,{_chunkSteps:q=>{this._ongoingPromise=void 0,_(()=>h({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Q(c),h({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,Q(c),k(q)}}),x}_returnSteps(c){if(this._isFinished)return Promise.resolve({value:c,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let k=Y(h,c);return Q(h),y(k,()=>({value:c,done:!0}))}return Q(h),f({value:c,done:!0})}}let qe={next(){return Fr(this)?this._asyncIteratorImpl.next():d(Ir("next"))},return(i){return Fr(this)?this._asyncIteratorImpl.return(i):d(Ir("return"))}};Object.setPrototypeOf(qe,ke);function Pr(i,c){let h=U(i),k=new Se(h,c),x=Object.create(qe);return x._asyncIteratorImpl=k,x}function Fr(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function Ir(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let ft=Number.isNaN||function(i){return i!==i};var pn,Ze,ze;function Te(i){return i.slice()}function Uf(i,c,h,k,x){new Uint8Array(i).set(new Uint8Array(h,k,x),c)}let mn=i=>(typeof i.transfer=="function"?mn=c=>c.transfer():typeof structuredClone=="function"?mn=c=>structuredClone(c,{transfer:[c]}):mn=c=>c,mn(i)),Bn=i=>(typeof i.detached=="boolean"?Bn=c=>c.detached:Bn=c=>c.byteLength===0,Bn(i));function $f(i,c,h){if(i.slice)return i.slice(c,h);let k=h-c,x=new ArrayBuffer(k);return Uf(x,0,i,c,k),x}function js(i,c){let h=i[c];if(h!=null){if(typeof h!="function")throw new TypeError(`${String(c)} is not a function`);return h}}function z_(i){let c={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*c})(),k=h.next;return{iterator:h,nextMethod:k,done:!1}}let Ou=(ze=(pn=Symbol.asyncIterator)!==null&&pn!==void 0?pn:(Ze=Symbol.for)===null||Ze===void 0?void 0:Ze.call(Symbol,"Symbol.asyncIterator"))!==null&&ze!==void 0?ze:"@@asyncIterator";function qf(i,c="sync",h){if(h===void 0)if(c==="async"){if(h=js(i,Ou),h===void 0){let j=js(i,Symbol.iterator),q=qf(i,"sync",j);return z_(q)}}else h=js(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let k=A(h,i,[]);if(!n(k))throw new TypeError("The iterator method must return an object");let x=k.next;return{iterator:k,nextMethod:x,done:!1}}function H_(i){let c=A(i.nextMethod,i.iterator,[]);if(!n(c))throw new TypeError("The iterator.next() method must return an object");return c}function W_(i){return!!i.done}function G_(i){return i.value}function J_(i){return!(typeof i!="number"||ft(i)||i<0)}function zf(i){let c=$f(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(c)}function Pu(i){let c=i._queue.shift();return i._queueTotalSize-=c.size,i._queueTotalSize<0&&(i._queueTotalSize=0),c.value}function Fu(i,c,h){if(!J_(h)||h===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:c,size:h}),i._queueTotalSize+=h}function V_(i){return i._queue.peek().value}function Mn(i){i._queue=new T,i._queueTotalSize=0}function Hf(i){return i===DataView}function K_(i){return Hf(i.constructor)}function Y_(i){return Hf(i)?1:i.BYTES_PER_ELEMENT}class rr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Iu(this))throw ju("view");return this._view}respond(c){if(!Iu(this))throw ju("respond");if(Ue(c,1,"respond"),c=F(c,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Bn(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");zs(this._associatedReadableByteStreamController,c)}respondWithNewView(c){if(!Iu(this))throw ju("respondWithNewView");if(Ue(c,1,"respondWithNewView"),!ArrayBuffer.isView(c))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(Bn(c.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Hs(this._associatedReadableByteStreamController,c)}}Object.defineProperties(rr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(rr.prototype.respond,"respond"),o(rr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class gn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!or(this))throw Io("byobRequest");return Lu(this)}get desiredSize(){if(!or(this))throw Io("desiredSize");return eh(this)}close(){if(!or(this))throw Io("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be closed`);Fo(this)}enqueue(c){if(!or(this))throw Io("enqueue");if(Ue(c,1,"enqueue"),!ArrayBuffer.isView(c))throw new TypeError("chunk must be an array buffer view");if(c.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(c.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 h=this._controlledReadableByteStream._state;if(h!=="readable")throw new TypeError(`The stream (in ${h} state) is not in the readable state and cannot be enqueued to`);qs(this,c)}error(c=void 0){if(!or(this))throw Io("error");St(this,c)}[G](c){Wf(this),Mn(this);let h=this._cancelAlgorithm(c);return $s(this),h}[P](c){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){Zf(this,c);return}let k=this._autoAllocateChunkSize;if(k!==void 0){let x;try{x=new ArrayBuffer(k)}catch(q){c._errorSteps(q);return}let j={buffer:x,bufferByteLength:k,byteOffset:0,byteLength:k,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(h,c),sr(this)}[K](){if(this._pendingPullIntos.length>0){let c=this._pendingPullIntos.peek();c.readerType="none",this._pendingPullIntos=new T,this._pendingPullIntos.push(c)}}}Object.defineProperties(gn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(gn.prototype.close,"close"),o(gn.prototype.enqueue,"enqueue"),o(gn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function or(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof gn}function Iu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof rr}function sr(i){if(!tb(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,sr(i)),null),k=>(St(i,k),null))}function Wf(i){Bu(i),i._pendingPullIntos=new T}function Nu(i,c){let h=!1;i._state==="closed"&&(h=!0);let k=Gf(c);c.readerType==="default"?I(i,k,h):ab(i,k,h)}function Gf(i){let c=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,c/h)}function Us(i,c,h,k){i._queue.push({buffer:c,byteOffset:h,byteLength:k}),i._queueTotalSize+=k}function Jf(i,c,h,k){let x;try{x=$f(c,h,h+k)}catch(j){throw St(i,j),j}Us(i,x,0,k)}function Vf(i,c){c.bytesFilled>0&&Jf(i,c.buffer,c.byteOffset,c.bytesFilled),Nr(i)}function Kf(i,c){let h=Math.min(i._queueTotalSize,c.byteLength-c.bytesFilled),k=c.bytesFilled+h,x=h,j=!1,q=k%c.elementSize,ne=k-q;ne>=c.minimumFill&&(x=ne-c.bytesFilled,j=!0);let pe=i._queue;for(;x>0;){let le=pe.peek(),me=Math.min(x,le.byteLength),be=c.byteOffset+c.bytesFilled;Uf(c.buffer,be,le.buffer,le.byteOffset,me),le.byteLength===me?pe.shift():(le.byteOffset+=me,le.byteLength-=me),i._queueTotalSize-=me,Yf(i,me,c),x-=me}return j}function Yf(i,c,h){h.bytesFilled+=c}function Qf(i){i._queueTotalSize===0&&i._closeRequested?($s(i),Uo(i._controlledReadableByteStream)):sr(i)}function Bu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function Mu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let c=i._pendingPullIntos.peek();Kf(i,c)&&(Nr(i),Nu(i._controlledReadableByteStream,c))}}function Q_(i){let c=i._controlledReadableByteStream._reader;for(;c._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=c._readRequests.shift();Zf(i,h)}}function X_(i,c,h,k){let x=i._controlledReadableByteStream,j=c.constructor,q=Y_(j),{byteOffset:ne,byteLength:pe}=c,le=h*q,me;try{me=mn(c.buffer)}catch(Re){k._errorSteps(Re);return}let be={buffer:me,bufferByteLength:me.byteLength,byteOffset:ne,byteLength:pe,bytesFilled:0,minimumFill:le,elementSize:q,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(be),rh(x,k);return}if(x._state==="closed"){let Re=new j(be.buffer,be.byteOffset,0);k._closeSteps(Re);return}if(i._queueTotalSize>0){if(Kf(i,be)){let Re=Gf(be);Qf(i),k._chunkSteps(Re);return}if(i._closeRequested){let Re=new TypeError("Insufficient bytes to fill elements in the given buffer");St(i,Re),k._errorSteps(Re);return}}i._pendingPullIntos.push(be),rh(x,k),sr(i)}function Z_(i,c){c.readerType==="none"&&Nr(i);let h=i._controlledReadableByteStream;if(Uu(h))for(;oh(h)>0;){let k=Nr(i);Nu(h,k)}}function eb(i,c,h){if(Yf(i,c,h),h.readerType==="none"){Vf(i,h),Mu(i);return}if(h.bytesFilled<h.minimumFill)return;Nr(i);let k=h.bytesFilled%h.elementSize;if(k>0){let x=h.byteOffset+h.bytesFilled;Jf(i,h.buffer,x-k,k)}h.bytesFilled-=k,Nu(i._controlledReadableByteStream,h),Mu(i)}function Xf(i,c){let h=i._pendingPullIntos.peek();Bu(i),i._controlledReadableByteStream._state==="closed"?Z_(i,h):eb(i,c,h),sr(i)}function Nr(i){return i._pendingPullIntos.shift()}function tb(i){let c=i._controlledReadableByteStream;return c._state!=="readable"||i._closeRequested||!i._started?!1:!!(B(c)&&L(c)>0||Uu(c)&&oh(c)>0||eh(i)>0)}function $s(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function Fo(i){let c=i._controlledReadableByteStream;if(!(i._closeRequested||c._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let h=i._pendingPullIntos.peek();if(h.bytesFilled%h.elementSize!==0){let k=new TypeError("Insufficient bytes to fill elements in the given buffer");throw St(i,k),k}}$s(i),Uo(c)}}function qs(i,c){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:k,byteOffset:x,byteLength:j}=c;if(Bn(k))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=mn(k);if(i._pendingPullIntos.length>0){let ne=i._pendingPullIntos.peek();if(Bn(ne.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Bu(i),ne.buffer=mn(ne.buffer),ne.readerType==="none"&&Vf(i,ne)}if(B(h))if(Q_(i),L(h)===0)Us(i,q,x,j);else{i._pendingPullIntos.length>0&&Nr(i);let ne=new Uint8Array(q,x,j);I(h,ne,!1)}else Uu(h)?(Us(i,q,x,j),Mu(i)):Us(i,q,x,j);sr(i)}function St(i,c){let h=i._controlledReadableByteStream;h._state==="readable"&&(Wf(i),Mn(i),$s(i),Dh(h,c))}function Zf(i,c){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,Qf(i);let k=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);c._chunkSteps(k)}function Lu(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let c=i._pendingPullIntos.peek(),h=new Uint8Array(c.buffer,c.byteOffset+c.bytesFilled,c.byteLength-c.bytesFilled),k=Object.create(rr.prototype);rb(k,i,h),i._byobRequest=k}return i._byobRequest}function eh(i){let c=i._controlledReadableByteStream._state;return c==="errored"?null:c==="closed"?0:i._strategyHWM-i._queueTotalSize}function zs(i,c){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(c!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(c===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(h.bytesFilled+c>h.byteLength)throw new RangeError("bytesWritten out of range")}h.buffer=mn(h.buffer),Xf(i,c)}function Hs(i,c){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(c.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(c.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(h.byteOffset+h.bytesFilled!==c.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(h.bufferByteLength!==c.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(h.bytesFilled+c.byteLength>h.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let x=c.byteLength;h.buffer=mn(c.buffer),Xf(i,x)}function th(i,c,h,k,x,j,q){c._controlledReadableByteStream=i,c._pullAgain=!1,c._pulling=!1,c._byobRequest=null,c._queue=c._queueTotalSize=void 0,Mn(c),c._closeRequested=!1,c._started=!1,c._strategyHWM=j,c._pullAlgorithm=k,c._cancelAlgorithm=x,c._autoAllocateChunkSize=q,c._pendingPullIntos=new T,i._readableStreamController=c;let ne=h();m(f(ne),()=>(c._started=!0,sr(c),null),pe=>(St(c,pe),null))}function nb(i,c,h){let k=Object.create(gn.prototype),x,j,q;c.start!==void 0?x=()=>c.start(k):x=()=>{},c.pull!==void 0?j=()=>c.pull(k):j=()=>f(void 0),c.cancel!==void 0?q=pe=>c.cancel(pe):q=()=>f(void 0);let ne=c.autoAllocateChunkSize;if(ne===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");th(i,k,x,j,q,h,ne)}function rb(i,c,h){i._associatedReadableByteStreamController=c,i._view=h}function ju(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Io(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function ob(i,c){ae(i,c);let h=i?.mode;return{mode:h===void 0?void 0:sb(h,`${c} has member 'mode' that`)}}function sb(i,c){if(i=`${i}`,i!=="byob")throw new TypeError(`${c} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function ib(i,c){var h;ae(i,c);let k=(h=i?.min)!==null&&h!==void 0?h:1;return{min:F(k,`${c} has member 'min' that`)}}function nh(i){return new Ln(i)}function rh(i,c){i._reader._readIntoRequests.push(c)}function ab(i,c,h){let x=i._reader._readIntoRequests.shift();h?x._closeSteps(c):x._chunkSteps(c)}function oh(i){return i._reader._readIntoRequests.length}function Uu(i){let c=i._reader;return!(c===void 0||!ir(c))}class Ln{constructor(c){if(Ue(c,1,"ReadableStreamBYOBReader"),N(c,"First parameter"),$n(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!or(c._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");z(this,c),this._readIntoRequests=new T}get closed(){return ir(this)?this._closedPromise:d(Ws("closed"))}cancel(c=void 0){return ir(this)?this._ownerReadableStream===void 0?d(ee("cancel")):Y(this,c):d(Ws("cancel"))}read(c,h={}){if(!ir(this))return d(Ws("read"));if(!ArrayBuffer.isView(c))return d(new TypeError("view must be an array buffer view"));if(c.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(c.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Bn(c.buffer))return d(new TypeError("view's buffer has been detached"));let k;try{k=ib(h,"options")}catch(le){return d(le)}let x=k.min;if(x===0)return d(new TypeError("options.min must be greater than 0"));if(K_(c)){if(x>c.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>c.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(ee("read from"));let j,q,ne=l((le,me)=>{j=le,q=me});return sh(this,c,x,{_chunkSteps:le=>j({value:le,done:!1}),_closeSteps:le=>j({value:le,done:!0}),_errorSteps:le=>q(le)}),ne}releaseLock(){if(!ir(this))throw Ws("releaseLock");this._ownerReadableStream!==void 0&&ub(this)}}Object.defineProperties(Ln.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ln.prototype.cancel,"cancel"),o(Ln.prototype.read,"read"),o(Ln.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ln.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function ir(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Ln}function sh(i,c,h,k){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?k._errorSteps(x._storedError):X_(x._readableStreamController,c,h,k)}function ub(i){Q(i);let c=new TypeError("Reader was released");ih(i,c)}function ih(i,c){let h=i._readIntoRequests;i._readIntoRequests=new T,h.forEach(k=>{k._errorSteps(c)})}function Ws(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function No(i,c){let{highWaterMark:h}=i;if(h===void 0)return c;if(ft(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function Gs(i){let{size:c}=i;return c||(()=>1)}function Js(i,c){ae(i,c);let h=i?.highWaterMark,k=i?.size;return{highWaterMark:h===void 0?void 0:S(h),size:k===void 0?void 0:cb(k,`${c} has member 'size' that`)}}function cb(i,c){return te(i,c),h=>S(i(h))}function lb(i,c){ae(i,c);let h=i?.abort,k=i?.close,x=i?.start,j=i?.type,q=i?.write;return{abort:h===void 0?void 0:db(h,i,`${c} has member 'abort' that`),close:k===void 0?void 0:fb(k,i,`${c} has member 'close' that`),start:x===void 0?void 0:hb(x,i,`${c} has member 'start' that`),write:q===void 0?void 0:pb(q,i,`${c} has member 'write' that`),type:j}}function db(i,c,h){return te(i,h),k=>C(i,c,[k])}function fb(i,c,h){return te(i,h),()=>C(i,c,[])}function hb(i,c,h){return te(i,h),k=>A(i,c,[k])}function pb(i,c,h){return te(i,h),(k,x)=>C(i,c,[k,x])}function ah(i,c){if(!Br(i))throw new TypeError(`${c} is not a WritableStream.`)}function mb(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let gb=typeof AbortController=="function";function yb(){if(gb)return new AbortController}class jn{constructor(c={},h={}){c===void 0?c=null:Oe(c,"First parameter");let k=Js(h,"Second parameter"),x=lb(c,"First parameter");if(ch(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let q=Gs(k),ne=No(k,1);Ob(this,x,ne,q)}get locked(){if(!Br(this))throw Xs("locked");return Mr(this)}abort(c=void 0){return Br(this)?Mr(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Vs(this,c):d(Xs("abort"))}close(){return Br(this)?Mr(this)?d(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?d(new TypeError("Cannot close an already-closing stream")):lh(this):d(Xs("close"))}getWriter(){if(!Br(this))throw Xs("getWriter");return uh(this)}}Object.defineProperties(jn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(jn.prototype.abort,"abort"),o(jn.prototype.close,"close"),o(jn.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jn.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function uh(i){return new yn(i)}function _b(i,c,h,k,x=1,j=()=>1){let q=Object.create(jn.prototype);ch(q);let ne=Object.create(Lr.prototype);return gh(q,ne,i,c,h,k,x,j),q}function ch(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new T,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Br(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof jn}function Mr(i){return i._writer!==void 0}function Vs(i,c){var h;if(i._state==="closed"||i._state==="errored")return f(void 0);i._writableStreamController._abortReason=c,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(c);let k=i._state;if(k==="closed"||k==="errored")return f(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;k==="erroring"&&(x=!0,c=void 0);let j=l((q,ne)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:ne,_reason:c,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||qu(i,c),j}function lh(i){let c=i._state;if(c==="closed"||c==="errored")return d(new TypeError(`The stream (in ${c} state) is not in the writable state and cannot be closed`));let h=l((x,j)=>{let q={_resolve:x,_reject:j};i._closeRequest=q}),k=i._writer;return k!==void 0&&i._backpressure&&c==="writable"&&Yu(k),Pb(i._writableStreamController),h}function bb(i){return l((h,k)=>{let x={_resolve:h,_reject:k};i._writeRequests.push(x)})}function $u(i,c){if(i._state==="writable"){qu(i,c);return}zu(i)}function qu(i,c){let h=i._writableStreamController;i._state="erroring",i._storedError=c;let k=i._writer;k!==void 0&&fh(k,c),!Ab(i)&&h._started&&zu(i)}function zu(i){i._state="errored",i._writableStreamController[$]();let c=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(c)}),i._writeRequests=new T,i._pendingAbortRequest===void 0){Ks(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(c),Ks(i);return}let k=i._writableStreamController[R](h._reason);m(k,()=>(h._resolve(),Ks(i),null),x=>(h._reject(x),Ks(i),null))}function Cb(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function wb(i,c){i._inFlightWriteRequest._reject(c),i._inFlightWriteRequest=void 0,$u(i,c)}function Eb(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let h=i._writer;h!==void 0&&Ch(h)}function kb(i,c){i._inFlightCloseRequest._reject(c),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(c),i._pendingAbortRequest=void 0),$u(i,c)}function Xt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function Ab(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function Sb(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function vb(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Ks(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let c=i._writer;c!==void 0&&Vu(c,i._storedError)}function Hu(i,c){let h=i._writer;h!==void 0&&c!==i._backpressure&&(c?jb(h):Yu(h)),i._backpressure=c}class yn{constructor(c){if(Ue(c,1,"WritableStreamDefaultWriter"),ah(c,"First parameter"),Mr(c))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=c,c._writer=this;let h=c._state;if(h==="writable")!Xt(c)&&c._backpressure?ei(this):wh(this),Zs(this);else if(h==="erroring")Ku(this,c._storedError),Zs(this);else if(h==="closed")wh(this),Mb(this);else{let k=c._storedError;Ku(this,k),bh(this,k)}}get closed(){return ar(this)?this._closedPromise:d(ur("closed"))}get desiredSize(){if(!ar(this))throw ur("desiredSize");if(this._ownerWritableStream===void 0)throw Mo("desiredSize");return xb(this)}get ready(){return ar(this)?this._readyPromise:d(ur("ready"))}abort(c=void 0){return ar(this)?this._ownerWritableStream===void 0?d(Mo("abort")):Tb(this,c):d(ur("abort"))}close(){if(!ar(this))return d(ur("close"));let c=this._ownerWritableStream;return c===void 0?d(Mo("close")):Xt(c)?d(new TypeError("Cannot close an already-closing stream")):dh(this)}releaseLock(){if(!ar(this))throw ur("releaseLock");this._ownerWritableStream!==void 0&&hh(this)}write(c=void 0){return ar(this)?this._ownerWritableStream===void 0?d(Mo("write to")):ph(this,c):d(ur("write"))}}Object.defineProperties(yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(yn.prototype.abort,"abort"),o(yn.prototype.close,"close"),o(yn.prototype.releaseLock,"releaseLock"),o(yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function ar(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof yn}function Tb(i,c){let h=i._ownerWritableStream;return Vs(h,c)}function dh(i){let c=i._ownerWritableStream;return lh(c)}function Db(i){let c=i._ownerWritableStream,h=c._state;return Xt(c)||h==="closed"?f(void 0):h==="errored"?d(c._storedError):dh(i)}function Rb(i,c){i._closedPromiseState==="pending"?Vu(i,c):Lb(i,c)}function fh(i,c){i._readyPromiseState==="pending"?Eh(i,c):Ub(i,c)}function xb(i){let c=i._ownerWritableStream,h=c._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:yh(c._writableStreamController)}function hh(i){let c=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");fh(i,h),Rb(i,h),c._writer=void 0,i._ownerWritableStream=void 0}function ph(i,c){let h=i._ownerWritableStream,k=h._writableStreamController,x=Fb(k,c);if(h!==i._ownerWritableStream)return d(Mo("write to"));let j=h._state;if(j==="errored")return d(h._storedError);if(Xt(h)||j==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return d(h._storedError);let q=bb(h);return Ib(k,c,x),q}let mh={};class Lr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Wu(this))throw Ju("abortReason");return this._abortReason}get signal(){if(!Wu(this))throw Ju("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(c=void 0){if(!Wu(this))throw Ju("error");this._controlledWritableStream._state==="writable"&&_h(this,c)}[R](c){let h=this._abortAlgorithm(c);return Ys(this),h}[$](){Mn(this)}}Object.defineProperties(Lr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Lr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Wu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Lr}function gh(i,c,h,k,x,j,q,ne){c._controlledWritableStream=i,i._writableStreamController=c,c._queue=void 0,c._queueTotalSize=void 0,Mn(c),c._abortReason=void 0,c._abortController=yb(),c._started=!1,c._strategySizeAlgorithm=ne,c._strategyHWM=q,c._writeAlgorithm=k,c._closeAlgorithm=x,c._abortAlgorithm=j;let pe=Gu(c);Hu(i,pe);let le=h(),me=f(le);m(me,()=>(c._started=!0,Qs(c),null),be=>(c._started=!0,$u(i,be),null))}function Ob(i,c,h,k){let x=Object.create(Lr.prototype),j,q,ne,pe;c.start!==void 0?j=()=>c.start(x):j=()=>{},c.write!==void 0?q=le=>c.write(le,x):q=()=>f(void 0),c.close!==void 0?ne=()=>c.close():ne=()=>f(void 0),c.abort!==void 0?pe=le=>c.abort(le):pe=()=>f(void 0),gh(i,x,j,q,ne,pe,h,k)}function Ys(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function Pb(i){Fu(i,mh,0),Qs(i)}function Fb(i,c){try{return i._strategySizeAlgorithm(c)}catch(h){return Bo(i,h),1}}function yh(i){return i._strategyHWM-i._queueTotalSize}function Ib(i,c,h){try{Fu(i,c,h)}catch(x){Bo(i,x);return}let k=i._controlledWritableStream;if(!Xt(k)&&k._state==="writable"){let x=Gu(i);Hu(k,x)}Qs(i)}function Qs(i){let c=i._controlledWritableStream;if(!i._started||c._inFlightWriteRequest!==void 0)return;if(c._state==="erroring"){zu(c);return}if(i._queue.length===0)return;let k=V_(i);k===mh?Nb(i):Bb(i,k)}function Bo(i,c){i._controlledWritableStream._state==="writable"&&_h(i,c)}function Nb(i){let c=i._controlledWritableStream;Sb(c),Pu(i);let h=i._closeAlgorithm();Ys(i),m(h,()=>(Eb(c),null),k=>(kb(c,k),null))}function Bb(i,c){let h=i._controlledWritableStream;vb(h);let k=i._writeAlgorithm(c);m(k,()=>{Cb(h);let x=h._state;if(Pu(i),!Xt(h)&&x==="writable"){let j=Gu(i);Hu(h,j)}return Qs(i),null},x=>(h._state==="writable"&&Ys(i),wb(h,x),null))}function Gu(i){return yh(i)<=0}function _h(i,c){let h=i._controlledWritableStream;Ys(i),qu(h,c)}function Xs(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function Ju(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function ur(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function Mo(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Zs(i){i._closedPromise=l((c,h)=>{i._closedPromise_resolve=c,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function bh(i,c){Zs(i),Vu(i,c)}function Mb(i){Zs(i),Ch(i)}function Vu(i,c){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(c),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function Lb(i,c){bh(i,c)}function Ch(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function ei(i){i._readyPromise=l((c,h)=>{i._readyPromise_resolve=c,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function Ku(i,c){ei(i),Eh(i,c)}function wh(i){ei(i),Yu(i)}function Eh(i,c){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(c),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function jb(i){ei(i)}function Ub(i,c){Ku(i,c)}function Yu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function $b(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Qu=$b();function qb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function zb(){let i=Qu?.DOMException;return qb(i)?i:void 0}function Hb(){let i=function(h,k){this.message=h||"",this.name=k||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let Wb=zb()||Hb();function kh(i,c,h,k,x,j){let q=U(i),ne=uh(c);i._disturbed=!0;let pe=!1,le=f(void 0);return l((me,be)=>{let Re;if(j!==void 0){if(Re=()=>{let de=j.reason!==void 0?j.reason:new Wb("Aborted","AbortError"),we=[];k||we.push(()=>c._state==="writable"?Vs(c,de):f(void 0)),x||we.push(()=>i._state==="readable"?Lt(i,de):f(void 0)),at(()=>Promise.all(we.map(Pe=>Pe())),!0,de)},j.aborted){Re();return}j.addEventListener("abort",Re)}function jt(){return l((de,we)=>{function Pe(ht){ht?de():p(qr(),Pe,we)}Pe(!1)})}function qr(){return pe?f(!0):p(ne._readyPromise,()=>l((de,we)=>{ie(q,{_chunkSteps:Pe=>{le=p(ph(ne,Pe),void 0,e),de(!1)},_closeSteps:()=>de(!0),_errorSteps:we})}))}if(bn(i,q._closedPromise,de=>(k?vt(!0,de):at(()=>Vs(c,de),!0,de),null)),bn(c,ne._closedPromise,de=>(x?vt(!0,de):at(()=>Lt(i,de),!0,de),null)),rt(i,q._closedPromise,()=>(h?vt():at(()=>Db(ne)),null)),Xt(c)||c._state==="closed"){let de=new TypeError("the destination writable stream closed before all data could be piped to it");x?vt(!0,de):at(()=>Lt(i,de),!0,de)}g(jt());function zn(){let de=le;return p(le,()=>de!==le?zn():void 0)}function bn(de,we,Pe){de._state==="errored"?Pe(de._storedError):w(we,Pe)}function rt(de,we,Pe){de._state==="closed"?Pe():b(we,Pe)}function at(de,we,Pe){if(pe)return;pe=!0,c._state==="writable"&&!Xt(c)?b(zn(),ht):ht();function ht(){return m(de(),()=>Cn(we,Pe),zr=>Cn(!0,zr)),null}}function vt(de,we){pe||(pe=!0,c._state==="writable"&&!Xt(c)?b(zn(),()=>Cn(de,we)):Cn(de,we))}function Cn(de,we){return hh(ne),Q(q),j!==void 0&&j.removeEventListener("abort",Re),de?be(we):me(void 0),null}})}class _n{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ti(this))throw ri("desiredSize");return Xu(this)}close(){if(!ti(this))throw ri("close");if(!Ur(this))throw new TypeError("The stream is not in a state that permits close");cr(this)}enqueue(c=void 0){if(!ti(this))throw ri("enqueue");if(!Ur(this))throw new TypeError("The stream is not in a state that permits enqueue");return jr(this,c)}error(c=void 0){if(!ti(this))throw ri("error");Mt(this,c)}[G](c){Mn(this);let h=this._cancelAlgorithm(c);return ni(this),h}[P](c){let h=this._controlledReadableStream;if(this._queue.length>0){let k=Pu(this);this._closeRequested&&this._queue.length===0?(ni(this),Uo(h)):Lo(this),c._chunkSteps(k)}else O(h,c),Lo(this)}[K](){}}Object.defineProperties(_n.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(_n.prototype.close,"close"),o(_n.prototype.enqueue,"enqueue"),o(_n.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(_n.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function ti(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof _n}function Lo(i){if(!Ah(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Lo(i)),null),k=>(Mt(i,k),null))}function Ah(i){let c=i._controlledReadableStream;return!Ur(i)||!i._started?!1:!!($n(c)&&L(c)>0||Xu(i)>0)}function ni(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function cr(i){if(!Ur(i))return;let c=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(ni(i),Uo(c))}function jr(i,c){if(!Ur(i))return;let h=i._controlledReadableStream;if($n(h)&&L(h)>0)I(h,c,!1);else{let k;try{k=i._strategySizeAlgorithm(c)}catch(x){throw Mt(i,x),x}try{Fu(i,c,k)}catch(x){throw Mt(i,x),x}}Lo(i)}function Mt(i,c){let h=i._controlledReadableStream;h._state==="readable"&&(Mn(i),ni(i),Dh(h,c))}function Xu(i){let c=i._controlledReadableStream._state;return c==="errored"?null:c==="closed"?0:i._strategyHWM-i._queueTotalSize}function Gb(i){return!Ah(i)}function Ur(i){let c=i._controlledReadableStream._state;return!i._closeRequested&&c==="readable"}function Sh(i,c,h,k,x,j,q){c._controlledReadableStream=i,c._queue=void 0,c._queueTotalSize=void 0,Mn(c),c._started=!1,c._closeRequested=!1,c._pullAgain=!1,c._pulling=!1,c._strategySizeAlgorithm=q,c._strategyHWM=j,c._pullAlgorithm=k,c._cancelAlgorithm=x,i._readableStreamController=c;let ne=h();m(f(ne),()=>(c._started=!0,Lo(c),null),pe=>(Mt(c,pe),null))}function Jb(i,c,h,k){let x=Object.create(_n.prototype),j,q,ne;c.start!==void 0?j=()=>c.start(x):j=()=>{},c.pull!==void 0?q=()=>c.pull(x):q=()=>f(void 0),c.cancel!==void 0?ne=pe=>c.cancel(pe):ne=()=>f(void 0),Sh(i,x,j,q,ne,h,k)}function ri(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function Vb(i,c){return or(i._readableStreamController)?Yb(i):Kb(i)}function Kb(i,c){let h=U(i),k=!1,x=!1,j=!1,q=!1,ne,pe,le,me,be,Re=l(rt=>{be=rt});function jt(){return k?(x=!0,f(void 0)):(k=!0,ie(h,{_chunkSteps:at=>{_(()=>{x=!1;let vt=at,Cn=at;j||jr(le._readableStreamController,vt),q||jr(me._readableStreamController,Cn),k=!1,x&&jt()})},_closeSteps:()=>{k=!1,j||cr(le._readableStreamController),q||cr(me._readableStreamController),(!j||!q)&&be(void 0)},_errorSteps:()=>{k=!1}}),f(void 0))}function qr(rt){if(j=!0,ne=rt,q){let at=Te([ne,pe]),vt=Lt(i,at);be(vt)}return Re}function zn(rt){if(q=!0,pe=rt,j){let at=Te([ne,pe]),vt=Lt(i,at);be(vt)}return Re}function bn(){}return le=jo(bn,jt,qr),me=jo(bn,jt,zn),w(h._closedPromise,rt=>(Mt(le._readableStreamController,rt),Mt(me._readableStreamController,rt),(!j||!q)&&be(void 0),null)),[le,me]}function Yb(i){let c=U(i),h=!1,k=!1,x=!1,j=!1,q=!1,ne,pe,le,me,be,Re=l(de=>{be=de});function jt(de){w(de._closedPromise,we=>(de!==c||(St(le._readableStreamController,we),St(me._readableStreamController,we),(!j||!q)&&be(void 0)),null))}function qr(){ir(c)&&(Q(c),c=U(i),jt(c)),ie(c,{_chunkSteps:we=>{_(()=>{k=!1,x=!1;let Pe=we,ht=we;if(!j&&!q)try{ht=zf(we)}catch(zr){St(le._readableStreamController,zr),St(me._readableStreamController,zr),be(Lt(i,zr));return}j||qs(le._readableStreamController,Pe),q||qs(me._readableStreamController,ht),h=!1,k?bn():x&&rt()})},_closeSteps:()=>{h=!1,j||Fo(le._readableStreamController),q||Fo(me._readableStreamController),le._readableStreamController._pendingPullIntos.length>0&&zs(le._readableStreamController,0),me._readableStreamController._pendingPullIntos.length>0&&zs(me._readableStreamController,0),(!j||!q)&&be(void 0)},_errorSteps:()=>{h=!1}})}function zn(de,we){re(c)&&(Q(c),c=nh(i),jt(c));let Pe=we?me:le,ht=we?le:me;sh(c,de,1,{_chunkSteps:Hr=>{_(()=>{k=!1,x=!1;let Wr=we?q:j;if(we?j:q)Wr||Hs(Pe._readableStreamController,Hr);else{let $h;try{$h=zf(Hr)}catch(rc){St(Pe._readableStreamController,rc),St(ht._readableStreamController,rc),be(Lt(i,rc));return}Wr||Hs(Pe._readableStreamController,Hr),qs(ht._readableStreamController,$h)}h=!1,k?bn():x&&rt()})},_closeSteps:Hr=>{h=!1;let Wr=we?q:j,di=we?j:q;Wr||Fo(Pe._readableStreamController),di||Fo(ht._readableStreamController),Hr!==void 0&&(Wr||Hs(Pe._readableStreamController,Hr),!di&&ht._readableStreamController._pendingPullIntos.length>0&&zs(ht._readableStreamController,0)),(!Wr||!di)&&be(void 0)},_errorSteps:()=>{h=!1}})}function bn(){if(h)return k=!0,f(void 0);h=!0;let de=Lu(le._readableStreamController);return de===null?qr():zn(de._view,!1),f(void 0)}function rt(){if(h)return x=!0,f(void 0);h=!0;let de=Lu(me._readableStreamController);return de===null?qr():zn(de._view,!0),f(void 0)}function at(de){if(j=!0,ne=de,q){let we=Te([ne,pe]),Pe=Lt(i,we);be(Pe)}return Re}function vt(de){if(q=!0,pe=de,j){let we=Te([ne,pe]),Pe=Lt(i,we);be(Pe)}return Re}function Cn(){}return le=Th(Cn,bn,at),me=Th(Cn,rt,vt),jt(c),[le,me]}function Qb(i){return n(i)&&typeof i.getReader<"u"}function Xb(i){return Qb(i)?eC(i.getReader()):Zb(i)}function Zb(i){let c,h=qf(i,"async"),k=e;function x(){let q;try{q=H_(h)}catch(pe){return d(pe)}let ne=f(q);return y(ne,pe=>{if(!n(pe))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(W_(pe))cr(c._readableStreamController);else{let me=G_(pe);jr(c._readableStreamController,me)}})}function j(q){let ne=h.iterator,pe;try{pe=js(ne,"return")}catch(be){return d(be)}if(pe===void 0)return f(void 0);let le;try{le=A(pe,ne,[q])}catch(be){return d(be)}let me=f(le);return y(me,be=>{if(!n(be))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return c=jo(k,x,j,0),c}function eC(i){let c,h=e;function k(){let j;try{j=i.read()}catch(q){return d(q)}return y(j,q=>{if(!n(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)cr(c._readableStreamController);else{let ne=q.value;jr(c._readableStreamController,ne)}})}function x(j){try{return f(i.cancel(j))}catch(q){return d(q)}}return c=jo(h,k,x,0),c}function tC(i,c){ae(i,c);let h=i,k=h?.autoAllocateChunkSize,x=h?.cancel,j=h?.pull,q=h?.start,ne=h?.type;return{autoAllocateChunkSize:k===void 0?void 0:F(k,`${c} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:nC(x,h,`${c} has member 'cancel' that`),pull:j===void 0?void 0:rC(j,h,`${c} has member 'pull' that`),start:q===void 0?void 0:oC(q,h,`${c} has member 'start' that`),type:ne===void 0?void 0:sC(ne,`${c} has member 'type' that`)}}function nC(i,c,h){return te(i,h),k=>C(i,c,[k])}function rC(i,c,h){return te(i,h),k=>C(i,c,[k])}function oC(i,c,h){return te(i,h),k=>A(i,c,[k])}function sC(i,c){if(i=`${i}`,i!=="bytes")throw new TypeError(`${c} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function iC(i,c){return ae(i,c),{preventCancel:!!i?.preventCancel}}function vh(i,c){ae(i,c);let h=i?.preventAbort,k=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&aC(j,`${c} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!k,preventClose:!!x,signal:j}}function aC(i,c){if(!mb(i))throw new TypeError(`${c} is not an AbortSignal.`)}function uC(i,c){ae(i,c);let h=i?.readable;E(h,"readable","ReadableWritablePair"),N(h,`${c} has member 'readable' that`);let k=i?.writable;return E(k,"writable","ReadableWritablePair"),ah(k,`${c} has member 'writable' that`),{readable:h,writable:k}}class et{constructor(c={},h={}){c===void 0?c=null:Oe(c,"First parameter");let k=Js(h,"Second parameter"),x=tC(c,"First parameter");if(Zu(this),x.type==="bytes"){if(k.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=No(k,0);nb(this,x,j)}else{let j=Gs(k),q=No(k,1);Jb(this,x,q,j)}}get locked(){if(!Un(this))throw lr("locked");return $n(this)}cancel(c=void 0){return Un(this)?$n(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Lt(this,c):d(lr("cancel"))}getReader(c=void 0){if(!Un(this))throw lr("getReader");return ob(c,"First parameter").mode===void 0?U(this):nh(this)}pipeThrough(c,h={}){if(!Un(this))throw lr("pipeThrough");Ue(c,1,"pipeThrough");let k=uC(c,"First parameter"),x=vh(h,"Second parameter");if($n(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Mr(k.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=kh(this,k.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return g(j),k.readable}pipeTo(c,h={}){if(!Un(this))return d(lr("pipeTo"));if(c===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!Br(c))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let k;try{k=vh(h,"Second parameter")}catch(x){return d(x)}return $n(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Mr(c)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kh(this,c,k.preventClose,k.preventAbort,k.preventCancel,k.signal)}tee(){if(!Un(this))throw lr("tee");let c=Vb(this);return Te(c)}values(c=void 0){if(!Un(this))throw lr("values");let h=iC(c,"First parameter");return Pr(this,h.preventCancel)}[Ou](c){return this.values(c)}static from(c){return Xb(c)}}Object.defineProperties(et,{from:{enumerable:!0}}),Object.defineProperties(et.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(et.from,"from"),o(et.prototype.cancel,"cancel"),o(et.prototype.getReader,"getReader"),o(et.prototype.pipeThrough,"pipeThrough"),o(et.prototype.pipeTo,"pipeTo"),o(et.prototype.tee,"tee"),o(et.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(et.prototype,Ou,{value:et.prototype.values,writable:!0,configurable:!0});function jo(i,c,h,k=1,x=()=>1){let j=Object.create(et.prototype);Zu(j);let q=Object.create(_n.prototype);return Sh(j,q,i,c,h,k,x),j}function Th(i,c,h){let k=Object.create(et.prototype);Zu(k);let x=Object.create(gn.prototype);return th(k,x,i,c,h,0,void 0),k}function Zu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Un(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof et}function $n(i){return i._reader!==void 0}function Lt(i,c){if(i._disturbed=!0,i._state==="closed")return f(void 0);if(i._state==="errored")return d(i._storedError);Uo(i);let h=i._reader;if(h!==void 0&&ir(h)){let x=h._readIntoRequests;h._readIntoRequests=new T,x.forEach(j=>{j._closeSteps(void 0)})}let k=i._readableStreamController[G](c);return y(k,e)}function Uo(i){i._state="closed";let c=i._reader;if(c!==void 0&&(ue(c),re(c))){let h=c._readRequests;c._readRequests=new T,h.forEach(k=>{k._closeSteps()})}}function Dh(i,c){i._state="errored",i._storedError=c;let h=i._reader;h!==void 0&&(J(h,c),re(h)?Ie(h,c):ih(h,c))}function lr(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function Rh(i,c){ae(i,c);let h=i?.highWaterMark;return E(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:S(h)}}let xh=i=>i.byteLength;o(xh,"size");class oi{constructor(c){Ue(c,1,"ByteLengthQueuingStrategy"),c=Rh(c,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Ph(this))throw Oh("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Ph(this))throw Oh("size");return xh}}Object.defineProperties(oi.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(oi.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Oh(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function Ph(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof oi}let Fh=()=>1;o(Fh,"size");class si{constructor(c){Ue(c,1,"CountQueuingStrategy"),c=Rh(c,"First parameter"),this._countQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Nh(this))throw Ih("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Nh(this))throw Ih("size");return Fh}}Object.defineProperties(si.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(si.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Ih(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Nh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof si}function cC(i,c){ae(i,c);let h=i?.cancel,k=i?.flush,x=i?.readableType,j=i?.start,q=i?.transform,ne=i?.writableType;return{cancel:h===void 0?void 0:hC(h,i,`${c} has member 'cancel' that`),flush:k===void 0?void 0:lC(k,i,`${c} has member 'flush' that`),readableType:x,start:j===void 0?void 0:dC(j,i,`${c} has member 'start' that`),transform:q===void 0?void 0:fC(q,i,`${c} has member 'transform' that`),writableType:ne}}function lC(i,c,h){return te(i,h),k=>C(i,c,[k])}function dC(i,c,h){return te(i,h),k=>A(i,c,[k])}function fC(i,c,h){return te(i,h),(k,x)=>C(i,c,[k,x])}function hC(i,c,h){return te(i,h),k=>C(i,c,[k])}class ii{constructor(c={},h={},k={}){c===void 0&&(c=null);let x=Js(h,"Second parameter"),j=Js(k,"Third parameter"),q=cC(c,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let ne=No(j,0),pe=Gs(j),le=No(x,1),me=Gs(x),be,Re=l(jt=>{be=jt});pC(this,Re,le,me,ne,pe),gC(this,q),q.start!==void 0?be(q.start(this._transformStreamController)):be(void 0)}get readable(){if(!Bh(this))throw Uh("readable");return this._readable}get writable(){if(!Bh(this))throw Uh("writable");return this._writable}}Object.defineProperties(ii.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ii.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function pC(i,c,h,k,x,j){function q(){return c}function ne(Re){return bC(i,Re)}function pe(Re){return CC(i,Re)}function le(){return wC(i)}i._writable=_b(q,ne,le,pe,h,k);function me(){return EC(i)}function be(Re){return kC(i,Re)}i._readable=jo(q,me,be,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,ai(i,!0),i._transformStreamController=void 0}function Bh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof ii}function Mh(i,c){Mt(i._readable._readableStreamController,c),ec(i,c)}function ec(i,c){ci(i._transformStreamController),Bo(i._writable._writableStreamController,c),tc(i)}function tc(i){i._backpressure&&ai(i,!1)}function ai(i,c){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=c}class qn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ui(this))throw li("desiredSize");let c=this._controlledTransformStream._readable._readableStreamController;return Xu(c)}enqueue(c=void 0){if(!ui(this))throw li("enqueue");Lh(this,c)}error(c=void 0){if(!ui(this))throw li("error");yC(this,c)}terminate(){if(!ui(this))throw li("terminate");_C(this)}}Object.defineProperties(qn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(qn.prototype.enqueue,"enqueue"),o(qn.prototype.error,"error"),o(qn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(qn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ui(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof qn}function mC(i,c,h,k,x){c._controlledTransformStream=i,i._transformStreamController=c,c._transformAlgorithm=h,c._flushAlgorithm=k,c._cancelAlgorithm=x,c._finishPromise=void 0,c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0}function gC(i,c){let h=Object.create(qn.prototype),k,x,j;c.transform!==void 0?k=q=>c.transform(q,h):k=q=>{try{return Lh(h,q),f(void 0)}catch(ne){return d(ne)}},c.flush!==void 0?x=()=>c.flush(h):x=()=>f(void 0),c.cancel!==void 0?j=q=>c.cancel(q):j=()=>f(void 0),mC(i,h,k,x,j)}function ci(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function Lh(i,c){let h=i._controlledTransformStream,k=h._readable._readableStreamController;if(!Ur(k))throw new TypeError("Readable side is not in a state that permits enqueue");try{jr(k,c)}catch(j){throw ec(h,j),h._readable._storedError}Gb(k)!==h._backpressure&&ai(h,!0)}function yC(i,c){Mh(i._controlledTransformStream,c)}function jh(i,c){let h=i._transformAlgorithm(c);return y(h,void 0,k=>{throw Mh(i._controlledTransformStream,k),k})}function _C(i){let c=i._controlledTransformStream,h=c._readable._readableStreamController;cr(h);let k=new TypeError("TransformStream terminated");ec(c,k)}function bC(i,c){let h=i._transformStreamController;if(i._backpressure){let k=i._backpressureChangePromise;return y(k,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return jh(h,c)})}return jh(h,c)}function CC(i,c){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._readable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(c);return ci(h),m(x,()=>(k._state==="errored"?$r(h,k._storedError):(Mt(k._readableStreamController,c),nc(h)),null),j=>(Mt(k._readableStreamController,j),$r(h,j),null)),h._finishPromise}function wC(i){let c=i._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=i._readable;c._finishPromise=l((x,j)=>{c._finishPromise_resolve=x,c._finishPromise_reject=j});let k=c._flushAlgorithm();return ci(c),m(k,()=>(h._state==="errored"?$r(c,h._storedError):(cr(h._readableStreamController),nc(c)),null),x=>(Mt(h._readableStreamController,x),$r(c,x),null)),c._finishPromise}function EC(i){return ai(i,!1),i._backpressureChangePromise}function kC(i,c){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._writable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(c);return ci(h),m(x,()=>(k._state==="errored"?$r(h,k._storedError):(Bo(k._writableStreamController,c),tc(i),nc(h)),null),j=>(Bo(k._writableStreamController,j),tc(i),$r(h,j),null)),h._finishPromise}function li(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function nc(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function $r(i,c){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(c),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Uh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=oi,t.CountQueuingStrategy=si,t.ReadableByteStreamController=gn,t.ReadableStream=et,t.ReadableStreamBYOBReader=Ln,t.ReadableStreamBYOBRequest=rr,t.ReadableStreamDefaultController=_n,t.ReadableStreamDefaultReader=H,t.TransformStream=ii,t.TransformStreamDefaultController=qn,t.WritableStream=jn,t.WritableStreamDefaultController=Lr,t.WritableStreamDefaultWriter=yn}))});var jm=X(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,Lm())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let u=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=u.byteLength,s.enqueue(new Uint8Array(u)),r===o.size&&s.close()}})})}catch{}});async function*Jc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,Um),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+Um)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var e1,Um,$m,_E,zt,Ko=Le(()=>{e1=xe(jm(),1);Um=65536;$m=class Vc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){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 n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=new TextEncoder;for(let s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof Vc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Jc(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Jc(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Jc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),u=Math.max(a-s,0),l=this.#e,f=[],d=0;for(let m of l){if(d>=u)break;let b=ArrayBuffer.isView(m)?m.byteLength:m.size;if(s&&b<=s)s-=b,a-=b;else{let w;ArrayBuffer.isView(m)?(w=m.subarray(s,Math.min(b,a)),d+=w.byteLength):(w=m.slice(s,Math.min(b,a)),d+=w.size),a-=b,f.push(w),s=0}}let p=new Vc([],{type:String(r).toLowerCase()});return p.#n=u,p.#e=f,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($m.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});_E=$m,zt=_E});var bE,CE,Jn,Kc=Le(()=>{Ko();bE=class extends zt{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof zt&&/^(File)$/.test(e[Symbol.toStringTag])}},CE=bE,Jn=CE});function Hm(t,e=zt){var n=`${qm()}${qm()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
27
- Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?r.push(o+Yc(a)+`"\r
25
+ `;let l=(0,gE.parseProxyResponse)(o);o.write(`${u}\r
26
+ `);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",yE),n.secureEndpoint?(Vo("Upgrading socket connection to TLS"),xm.connect({...Pm(Om(n),"host","path","port"),socket:o})):o;o.destroy();let h=new Ji.Socket({writable:!1});return h.readable=!0,e.once("socket",m=>{Vo("Replaying proxy buffer for failed request"),(0,fE.default)(m.listenerCount("data")>0),m.push(d),m.push(null)}),h}};Vi.protocols=["http","https"];xt.HttpsProxyAgent=Vi;function yE(t){t.resume()}function Pm(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function _E(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 n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let d=1;d<n.length;d++)n[d]==="base64"?o=!0:n[d]&&(a+=`;${n[d]}`,n[d].indexOf("charset=")===0&&(r=n[d].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let u=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,u);return f.type=s,f.typeFull=a,f.charset=r,f}var Bm,Mm=Le(()=>{Bm=_E});var jm=X((Ki,Lm)=>{(function(t,e){typeof Ki=="object"&&typeof Lm<"u"?e(Ki):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ki,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=e;function o(i,c){try{Object.defineProperty(i,"name",{value:c,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,u=Promise.reject.bind(s);function l(i){return new s(i)}function f(i){return l(c=>c(i))}function d(i){return u(i)}function h(i,c,p){return a.call(i,c,p)}function m(i,c,p){h(h(i,c,p),void 0,r)}function C(i,c){m(i,c)}function w(i,c){m(i,void 0,c)}function y(i,c,p){return h(i,c,p)}function g(i){h(i,void 0,r)}let _=i=>{if(typeof queueMicrotask=="function")_=queueMicrotask;else{let c=f(void 0);_=p=>h(c,p)}return _(i)};function E(i,c,p){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,c,p)}function b(i,c,p){try{return f(E(i,c,p))}catch(A){return d(A)}}let S=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(c){let p=this._back,A=p;p._elements.length===S-1&&(A={_elements:[],_next:void 0}),p._elements.push(c),A!==p&&(this._back=A,p._next=A),++this._size}shift(){let c=this._front,p=c,A=this._cursor,x=A+1,j=c._elements,z=j[A];return x===S&&(p=c._next,x=0),--this._size,this._cursor=x,c!==p&&(this._front=p),j[A]=void 0,z}forEach(c){let p=this._cursor,A=this._front,x=A._elements;for(;(p!==x.length||A._next!==void 0)&&!(p===x.length&&(A=A._next,x=A._elements,p=0,x.length===0));)c(x[p]),++p}peek(){let c=this._front,p=this._cursor;return c._elements[p]}}let R=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),H=Symbol("[[CancelSteps]]"),P=Symbol("[[PullSteps]]"),K=Symbol("[[ReleaseSteps]]");function q(i,c){i._ownerReadableStream=c,c._reader=i,c._state==="readable"?oe(i):c._state==="closed"?he(i):se(i,c._storedError)}function Y(i,c){let p=i._ownerReadableStream;return jt(p,c)}function Q(i){let c=i._ownerReadableStream;c._state==="readable"?J(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Z(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),c._readableStreamController[K](),c._reader=void 0,i._ownerReadableStream=void 0}function ee(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function oe(i){i._closedPromise=l((c,p)=>{i._closedPromise_resolve=c,i._closedPromise_reject=p})}function se(i,c){oe(i),J(i,c)}function he(i){oe(i),ue(i)}function J(i,c){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(c),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function Z(i,c){se(i,c)}function ue(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let je=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},Ce=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function V(i){return typeof i=="object"||typeof i=="function"}function ae(i,c){if(i!==void 0&&!V(i))throw new TypeError(`${c} is not an object.`)}function te(i,c){if(typeof i!="function")throw new TypeError(`${c} is not a function.`)}function Te(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Oe(i,c){if(!Te(i))throw new TypeError(`${c} is not an object.`)}function Ue(i,c,p){if(i===void 0)throw new TypeError(`Parameter ${c} is required in '${p}'.`)}function k(i,c,p){if(i===void 0)throw new TypeError(`${c} is required in '${p}'.`)}function T(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(Ce(i))}function F(i,c){let A=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!je(x))throw new TypeError(`${c} is not a finite number`);if(x=M(x),x<0||x>A)throw new TypeError(`${c} is outside the accepted range of 0 to ${A}, inclusive`);return!je(x)||x===0?0:x}function N(i,c){if(!Un(i))throw new TypeError(`${c} is not a ReadableStream.`)}function U(i){return new W(i)}function O(i,c){i._reader._readRequests.push(c)}function I(i,c,p){let x=i._reader._readRequests.shift();p?x._closeSteps():x._chunkSteps(c)}function L(i){return i._reader._readRequests.length}function B(i){let c=i._reader;return!(c===void 0||!re(c))}class W{constructor(c){if(Ue(c,1,"ReadableStreamDefaultReader"),N(c,"First parameter"),$n(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");q(this,c),this._readRequests=new v}get closed(){return re(this)?this._closedPromise:d(Me("closed"))}cancel(c=void 0){return re(this)?this._ownerReadableStream===void 0?d(ee("cancel")):Y(this,c):d(Me("cancel"))}read(){if(!re(this))return d(Me("read"));if(this._ownerReadableStream===void 0)return d(ee("read from"));let c,p,A=l((j,z)=>{c=j,p=z});return ie(this,{_chunkSteps:j=>c({value:j,done:!1}),_closeSteps:()=>c({value:void 0,done:!0}),_errorSteps:j=>p(j)}),A}releaseLock(){if(!re(this))throw Me("releaseLock");this._ownerReadableStream!==void 0&&Ae(this)}}Object.defineProperties(W.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(W.prototype.cancel,"cancel"),o(W.prototype.read,"read"),o(W.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(W.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function re(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof W}function ie(i,c){let p=i._ownerReadableStream;p._disturbed=!0,p._state==="closed"?c._closeSteps():p._state==="errored"?c._errorSteps(p._storedError):p._readableStreamController[P](c)}function Ae(i){Q(i);let c=new TypeError("Reader was released");Ie(i,c)}function Ie(i,c){let p=i._readRequests;i._readRequests=new v,p.forEach(A=>{A._errorSteps(c)})}function Me(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let ke=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(c,p){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=c,this._preventCancel=p}next(){let c=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,c,c):c(),this._ongoingPromise}return(c){let p=()=>this._returnSteps(c);return this._ongoingPromise?y(this._ongoingPromise,p,p):p()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let c=this._reader,p,A,x=l((z,ne)=>{p=z,A=ne});return ie(c,{_chunkSteps:z=>{this._ongoingPromise=void 0,_(()=>p({value:z,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Q(c),p({value:void 0,done:!0})},_errorSteps:z=>{this._ongoingPromise=void 0,this._isFinished=!0,Q(c),A(z)}}),x}_returnSteps(c){if(this._isFinished)return Promise.resolve({value:c,done:!0});this._isFinished=!0;let p=this._reader;if(!this._preventCancel){let A=Y(p,c);return Q(p),y(A,()=>({value:c,done:!0}))}return Q(p),f({value:c,done:!0})}}let qe={next(){return Fr(this)?this._asyncIteratorImpl.next():d(Ir("next"))},return(i){return Fr(this)?this._asyncIteratorImpl.return(i):d(Ir("return"))}};Object.setPrototypeOf(qe,ke);function Pr(i,c){let p=U(i),A=new Se(p,c),x=Object.create(qe);return x._asyncIteratorImpl=A,x}function Fr(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function Ir(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let ft=Number.isNaN||function(i){return i!==i};var pn,Ze,ze;function ve(i){return i.slice()}function $f(i,c,p,A,x){new Uint8Array(i).set(new Uint8Array(p,A,x),c)}let mn=i=>(typeof i.transfer=="function"?mn=c=>c.transfer():typeof structuredClone=="function"?mn=c=>structuredClone(c,{transfer:[c]}):mn=c=>c,mn(i)),Bn=i=>(typeof i.detached=="boolean"?Bn=c=>c.detached:Bn=c=>c.byteLength===0,Bn(i));function qf(i,c,p){if(i.slice)return i.slice(c,p);let A=p-c,x=new ArrayBuffer(A);return $f(x,0,i,c,A),x}function js(i,c){let p=i[c];if(p!=null){if(typeof p!="function")throw new TypeError(`${String(c)} is not a function`);return p}}function H_(i){let c={[Symbol.iterator]:()=>i.iterator},p=(async function*(){return yield*c})(),A=p.next;return{iterator:p,nextMethod:A,done:!1}}let Pu=(ze=(pn=Symbol.asyncIterator)!==null&&pn!==void 0?pn:(Ze=Symbol.for)===null||Ze===void 0?void 0:Ze.call(Symbol,"Symbol.asyncIterator"))!==null&&ze!==void 0?ze:"@@asyncIterator";function zf(i,c="sync",p){if(p===void 0)if(c==="async"){if(p=js(i,Pu),p===void 0){let j=js(i,Symbol.iterator),z=zf(i,"sync",j);return H_(z)}}else p=js(i,Symbol.iterator);if(p===void 0)throw new TypeError("The object is not iterable");let A=E(p,i,[]);if(!n(A))throw new TypeError("The iterator method must return an object");let x=A.next;return{iterator:A,nextMethod:x,done:!1}}function W_(i){let c=E(i.nextMethod,i.iterator,[]);if(!n(c))throw new TypeError("The iterator.next() method must return an object");return c}function G_(i){return!!i.done}function J_(i){return i.value}function V_(i){return!(typeof i!="number"||ft(i)||i<0)}function Hf(i){let c=qf(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(c)}function Fu(i){let c=i._queue.shift();return i._queueTotalSize-=c.size,i._queueTotalSize<0&&(i._queueTotalSize=0),c.value}function Iu(i,c,p){if(!V_(p)||p===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:c,size:p}),i._queueTotalSize+=p}function K_(i){return i._queue.peek().value}function Mn(i){i._queue=new v,i._queueTotalSize=0}function Wf(i){return i===DataView}function Y_(i){return Wf(i.constructor)}function Q_(i){return Wf(i)?1:i.BYTES_PER_ELEMENT}class rr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Nu(this))throw Uu("view");return this._view}respond(c){if(!Nu(this))throw Uu("respond");if(Ue(c,1,"respond"),c=F(c,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Bn(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");zs(this._associatedReadableByteStreamController,c)}respondWithNewView(c){if(!Nu(this))throw Uu("respondWithNewView");if(Ue(c,1,"respondWithNewView"),!ArrayBuffer.isView(c))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(Bn(c.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Hs(this._associatedReadableByteStreamController,c)}}Object.defineProperties(rr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(rr.prototype.respond,"respond"),o(rr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class gn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!or(this))throw Io("byobRequest");return ju(this)}get desiredSize(){if(!or(this))throw Io("desiredSize");return th(this)}close(){if(!or(this))throw Io("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be closed`);Fo(this)}enqueue(c){if(!or(this))throw Io("enqueue");if(Ue(c,1,"enqueue"),!ArrayBuffer.isView(c))throw new TypeError("chunk must be an array buffer view");if(c.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(c.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 p=this._controlledReadableByteStream._state;if(p!=="readable")throw new TypeError(`The stream (in ${p} state) is not in the readable state and cannot be enqueued to`);qs(this,c)}error(c=void 0){if(!or(this))throw Io("error");Tt(this,c)}[H](c){Gf(this),Mn(this);let p=this._cancelAlgorithm(c);return $s(this),p}[P](c){let p=this._controlledReadableByteStream;if(this._queueTotalSize>0){eh(this,c);return}let A=this._autoAllocateChunkSize;if(A!==void 0){let x;try{x=new ArrayBuffer(A)}catch(z){c._errorSteps(z);return}let j={buffer:x,bufferByteLength:A,byteOffset:0,byteLength:A,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(p,c),sr(this)}[K](){if(this._pendingPullIntos.length>0){let c=this._pendingPullIntos.peek();c.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(c)}}}Object.defineProperties(gn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(gn.prototype.close,"close"),o(gn.prototype.enqueue,"enqueue"),o(gn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function or(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof gn}function Nu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof rr}function sr(i){if(!nb(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let p=i._pullAlgorithm();m(p,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,sr(i)),null),A=>(Tt(i,A),null))}function Gf(i){Mu(i),i._pendingPullIntos=new v}function Bu(i,c){let p=!1;i._state==="closed"&&(p=!0);let A=Jf(c);c.readerType==="default"?I(i,A,p):ub(i,A,p)}function Jf(i){let c=i.bytesFilled,p=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,c/p)}function Us(i,c,p,A){i._queue.push({buffer:c,byteOffset:p,byteLength:A}),i._queueTotalSize+=A}function Vf(i,c,p,A){let x;try{x=qf(c,p,p+A)}catch(j){throw Tt(i,j),j}Us(i,x,0,A)}function Kf(i,c){c.bytesFilled>0&&Vf(i,c.buffer,c.byteOffset,c.bytesFilled),Nr(i)}function Yf(i,c){let p=Math.min(i._queueTotalSize,c.byteLength-c.bytesFilled),A=c.bytesFilled+p,x=p,j=!1,z=A%c.elementSize,ne=A-z;ne>=c.minimumFill&&(x=ne-c.bytesFilled,j=!0);let pe=i._queue;for(;x>0;){let le=pe.peek(),me=Math.min(x,le.byteLength),be=c.byteOffset+c.bytesFilled;$f(c.buffer,be,le.buffer,le.byteOffset,me),le.byteLength===me?pe.shift():(le.byteOffset+=me,le.byteLength-=me),i._queueTotalSize-=me,Qf(i,me,c),x-=me}return j}function Qf(i,c,p){p.bytesFilled+=c}function Xf(i){i._queueTotalSize===0&&i._closeRequested?($s(i),Uo(i._controlledReadableByteStream)):sr(i)}function Mu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function Lu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let c=i._pendingPullIntos.peek();Yf(i,c)&&(Nr(i),Bu(i._controlledReadableByteStream,c))}}function X_(i){let c=i._controlledReadableByteStream._reader;for(;c._readRequests.length>0;){if(i._queueTotalSize===0)return;let p=c._readRequests.shift();eh(i,p)}}function Z_(i,c,p,A){let x=i._controlledReadableByteStream,j=c.constructor,z=Q_(j),{byteOffset:ne,byteLength:pe}=c,le=p*z,me;try{me=mn(c.buffer)}catch(Re){A._errorSteps(Re);return}let be={buffer:me,bufferByteLength:me.byteLength,byteOffset:ne,byteLength:pe,bytesFilled:0,minimumFill:le,elementSize:z,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(be),oh(x,A);return}if(x._state==="closed"){let Re=new j(be.buffer,be.byteOffset,0);A._closeSteps(Re);return}if(i._queueTotalSize>0){if(Yf(i,be)){let Re=Jf(be);Xf(i),A._chunkSteps(Re);return}if(i._closeRequested){let Re=new TypeError("Insufficient bytes to fill elements in the given buffer");Tt(i,Re),A._errorSteps(Re);return}}i._pendingPullIntos.push(be),oh(x,A),sr(i)}function eb(i,c){c.readerType==="none"&&Nr(i);let p=i._controlledReadableByteStream;if($u(p))for(;sh(p)>0;){let A=Nr(i);Bu(p,A)}}function tb(i,c,p){if(Qf(i,c,p),p.readerType==="none"){Kf(i,p),Lu(i);return}if(p.bytesFilled<p.minimumFill)return;Nr(i);let A=p.bytesFilled%p.elementSize;if(A>0){let x=p.byteOffset+p.bytesFilled;Vf(i,p.buffer,x-A,A)}p.bytesFilled-=A,Bu(i._controlledReadableByteStream,p),Lu(i)}function Zf(i,c){let p=i._pendingPullIntos.peek();Mu(i),i._controlledReadableByteStream._state==="closed"?eb(i,p):tb(i,c,p),sr(i)}function Nr(i){return i._pendingPullIntos.shift()}function nb(i){let c=i._controlledReadableByteStream;return c._state!=="readable"||i._closeRequested||!i._started?!1:!!(B(c)&&L(c)>0||$u(c)&&sh(c)>0||th(i)>0)}function $s(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function Fo(i){let c=i._controlledReadableByteStream;if(!(i._closeRequested||c._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let p=i._pendingPullIntos.peek();if(p.bytesFilled%p.elementSize!==0){let A=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Tt(i,A),A}}$s(i),Uo(c)}}function qs(i,c){let p=i._controlledReadableByteStream;if(i._closeRequested||p._state!=="readable")return;let{buffer:A,byteOffset:x,byteLength:j}=c;if(Bn(A))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let z=mn(A);if(i._pendingPullIntos.length>0){let ne=i._pendingPullIntos.peek();if(Bn(ne.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Mu(i),ne.buffer=mn(ne.buffer),ne.readerType==="none"&&Kf(i,ne)}if(B(p))if(X_(i),L(p)===0)Us(i,z,x,j);else{i._pendingPullIntos.length>0&&Nr(i);let ne=new Uint8Array(z,x,j);I(p,ne,!1)}else $u(p)?(Us(i,z,x,j),Lu(i)):Us(i,z,x,j);sr(i)}function Tt(i,c){let p=i._controlledReadableByteStream;p._state==="readable"&&(Gf(i),Mn(i),$s(i),Rh(p,c))}function eh(i,c){let p=i._queue.shift();i._queueTotalSize-=p.byteLength,Xf(i);let A=new Uint8Array(p.buffer,p.byteOffset,p.byteLength);c._chunkSteps(A)}function ju(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let c=i._pendingPullIntos.peek(),p=new Uint8Array(c.buffer,c.byteOffset+c.bytesFilled,c.byteLength-c.bytesFilled),A=Object.create(rr.prototype);ob(A,i,p),i._byobRequest=A}return i._byobRequest}function th(i){let c=i._controlledReadableByteStream._state;return c==="errored"?null:c==="closed"?0:i._strategyHWM-i._queueTotalSize}function zs(i,c){let p=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(c!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(c===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(p.bytesFilled+c>p.byteLength)throw new RangeError("bytesWritten out of range")}p.buffer=mn(p.buffer),Zf(i,c)}function Hs(i,c){let p=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(c.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(c.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(p.byteOffset+p.bytesFilled!==c.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(p.bufferByteLength!==c.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(p.bytesFilled+c.byteLength>p.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let x=c.byteLength;p.buffer=mn(c.buffer),Zf(i,x)}function nh(i,c,p,A,x,j,z){c._controlledReadableByteStream=i,c._pullAgain=!1,c._pulling=!1,c._byobRequest=null,c._queue=c._queueTotalSize=void 0,Mn(c),c._closeRequested=!1,c._started=!1,c._strategyHWM=j,c._pullAlgorithm=A,c._cancelAlgorithm=x,c._autoAllocateChunkSize=z,c._pendingPullIntos=new v,i._readableStreamController=c;let ne=p();m(f(ne),()=>(c._started=!0,sr(c),null),pe=>(Tt(c,pe),null))}function rb(i,c,p){let A=Object.create(gn.prototype),x,j,z;c.start!==void 0?x=()=>c.start(A):x=()=>{},c.pull!==void 0?j=()=>c.pull(A):j=()=>f(void 0),c.cancel!==void 0?z=pe=>c.cancel(pe):z=()=>f(void 0);let ne=c.autoAllocateChunkSize;if(ne===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");nh(i,A,x,j,z,p,ne)}function ob(i,c,p){i._associatedReadableByteStreamController=c,i._view=p}function Uu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Io(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function sb(i,c){ae(i,c);let p=i?.mode;return{mode:p===void 0?void 0:ib(p,`${c} has member 'mode' that`)}}function ib(i,c){if(i=`${i}`,i!=="byob")throw new TypeError(`${c} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function ab(i,c){var p;ae(i,c);let A=(p=i?.min)!==null&&p!==void 0?p:1;return{min:F(A,`${c} has member 'min' that`)}}function rh(i){return new Ln(i)}function oh(i,c){i._reader._readIntoRequests.push(c)}function ub(i,c,p){let x=i._reader._readIntoRequests.shift();p?x._closeSteps(c):x._chunkSteps(c)}function sh(i){return i._reader._readIntoRequests.length}function $u(i){let c=i._reader;return!(c===void 0||!ir(c))}class Ln{constructor(c){if(Ue(c,1,"ReadableStreamBYOBReader"),N(c,"First parameter"),$n(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!or(c._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");q(this,c),this._readIntoRequests=new v}get closed(){return ir(this)?this._closedPromise:d(Ws("closed"))}cancel(c=void 0){return ir(this)?this._ownerReadableStream===void 0?d(ee("cancel")):Y(this,c):d(Ws("cancel"))}read(c,p={}){if(!ir(this))return d(Ws("read"));if(!ArrayBuffer.isView(c))return d(new TypeError("view must be an array buffer view"));if(c.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(c.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Bn(c.buffer))return d(new TypeError("view's buffer has been detached"));let A;try{A=ab(p,"options")}catch(le){return d(le)}let x=A.min;if(x===0)return d(new TypeError("options.min must be greater than 0"));if(Y_(c)){if(x>c.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>c.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(ee("read from"));let j,z,ne=l((le,me)=>{j=le,z=me});return ih(this,c,x,{_chunkSteps:le=>j({value:le,done:!1}),_closeSteps:le=>j({value:le,done:!0}),_errorSteps:le=>z(le)}),ne}releaseLock(){if(!ir(this))throw Ws("releaseLock");this._ownerReadableStream!==void 0&&cb(this)}}Object.defineProperties(Ln.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ln.prototype.cancel,"cancel"),o(Ln.prototype.read,"read"),o(Ln.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ln.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function ir(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Ln}function ih(i,c,p,A){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?A._errorSteps(x._storedError):Z_(x._readableStreamController,c,p,A)}function cb(i){Q(i);let c=new TypeError("Reader was released");ah(i,c)}function ah(i,c){let p=i._readIntoRequests;i._readIntoRequests=new v,p.forEach(A=>{A._errorSteps(c)})}function Ws(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function No(i,c){let{highWaterMark:p}=i;if(p===void 0)return c;if(ft(p)||p<0)throw new RangeError("Invalid highWaterMark");return p}function Gs(i){let{size:c}=i;return c||(()=>1)}function Js(i,c){ae(i,c);let p=i?.highWaterMark,A=i?.size;return{highWaterMark:p===void 0?void 0:T(p),size:A===void 0?void 0:lb(A,`${c} has member 'size' that`)}}function lb(i,c){return te(i,c),p=>T(i(p))}function db(i,c){ae(i,c);let p=i?.abort,A=i?.close,x=i?.start,j=i?.type,z=i?.write;return{abort:p===void 0?void 0:fb(p,i,`${c} has member 'abort' that`),close:A===void 0?void 0:hb(A,i,`${c} has member 'close' that`),start:x===void 0?void 0:pb(x,i,`${c} has member 'start' that`),write:z===void 0?void 0:mb(z,i,`${c} has member 'write' that`),type:j}}function fb(i,c,p){return te(i,p),A=>b(i,c,[A])}function hb(i,c,p){return te(i,p),()=>b(i,c,[])}function pb(i,c,p){return te(i,p),A=>E(i,c,[A])}function mb(i,c,p){return te(i,p),(A,x)=>b(i,c,[A,x])}function uh(i,c){if(!Br(i))throw new TypeError(`${c} is not a WritableStream.`)}function gb(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let yb=typeof AbortController=="function";function _b(){if(yb)return new AbortController}class jn{constructor(c={},p={}){c===void 0?c=null:Oe(c,"First parameter");let A=Js(p,"Second parameter"),x=db(c,"First parameter");if(lh(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let z=Gs(A),ne=No(A,1);Pb(this,x,ne,z)}get locked(){if(!Br(this))throw Xs("locked");return Mr(this)}abort(c=void 0){return Br(this)?Mr(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Vs(this,c):d(Xs("abort"))}close(){return Br(this)?Mr(this)?d(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?d(new TypeError("Cannot close an already-closing stream")):dh(this):d(Xs("close"))}getWriter(){if(!Br(this))throw Xs("getWriter");return ch(this)}}Object.defineProperties(jn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(jn.prototype.abort,"abort"),o(jn.prototype.close,"close"),o(jn.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jn.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function ch(i){return new yn(i)}function bb(i,c,p,A,x=1,j=()=>1){let z=Object.create(jn.prototype);lh(z);let ne=Object.create(Lr.prototype);return yh(z,ne,i,c,p,A,x,j),z}function lh(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new v,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Br(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof jn}function Mr(i){return i._writer!==void 0}function Vs(i,c){var p;if(i._state==="closed"||i._state==="errored")return f(void 0);i._writableStreamController._abortReason=c,(p=i._writableStreamController._abortController)===null||p===void 0||p.abort(c);let A=i._state;if(A==="closed"||A==="errored")return f(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;A==="erroring"&&(x=!0,c=void 0);let j=l((z,ne)=>{i._pendingAbortRequest={_promise:void 0,_resolve:z,_reject:ne,_reason:c,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||zu(i,c),j}function dh(i){let c=i._state;if(c==="closed"||c==="errored")return d(new TypeError(`The stream (in ${c} state) is not in the writable state and cannot be closed`));let p=l((x,j)=>{let z={_resolve:x,_reject:j};i._closeRequest=z}),A=i._writer;return A!==void 0&&i._backpressure&&c==="writable"&&Qu(A),Fb(i._writableStreamController),p}function Cb(i){return l((p,A)=>{let x={_resolve:p,_reject:A};i._writeRequests.push(x)})}function qu(i,c){if(i._state==="writable"){zu(i,c);return}Hu(i)}function zu(i,c){let p=i._writableStreamController;i._state="erroring",i._storedError=c;let A=i._writer;A!==void 0&&hh(A,c),!Sb(i)&&p._started&&Hu(i)}function Hu(i){i._state="errored",i._writableStreamController[$]();let c=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(c)}),i._writeRequests=new v,i._pendingAbortRequest===void 0){Ks(i);return}let p=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,p._wasAlreadyErroring){p._reject(c),Ks(i);return}let A=i._writableStreamController[R](p._reason);m(A,()=>(p._resolve(),Ks(i),null),x=>(p._reject(x),Ks(i),null))}function wb(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function Eb(i,c){i._inFlightWriteRequest._reject(c),i._inFlightWriteRequest=void 0,qu(i,c)}function kb(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let p=i._writer;p!==void 0&&wh(p)}function Ab(i,c){i._inFlightCloseRequest._reject(c),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(c),i._pendingAbortRequest=void 0),qu(i,c)}function Xt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function Sb(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function Tb(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function vb(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Ks(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let c=i._writer;c!==void 0&&Ku(c,i._storedError)}function Wu(i,c){let p=i._writer;p!==void 0&&c!==i._backpressure&&(c?Ub(p):Qu(p)),i._backpressure=c}class yn{constructor(c){if(Ue(c,1,"WritableStreamDefaultWriter"),uh(c,"First parameter"),Mr(c))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=c,c._writer=this;let p=c._state;if(p==="writable")!Xt(c)&&c._backpressure?ei(this):Eh(this),Zs(this);else if(p==="erroring")Yu(this,c._storedError),Zs(this);else if(p==="closed")Eh(this),Lb(this);else{let A=c._storedError;Yu(this,A),Ch(this,A)}}get closed(){return ar(this)?this._closedPromise:d(ur("closed"))}get desiredSize(){if(!ar(this))throw ur("desiredSize");if(this._ownerWritableStream===void 0)throw Mo("desiredSize");return Ob(this)}get ready(){return ar(this)?this._readyPromise:d(ur("ready"))}abort(c=void 0){return ar(this)?this._ownerWritableStream===void 0?d(Mo("abort")):Db(this,c):d(ur("abort"))}close(){if(!ar(this))return d(ur("close"));let c=this._ownerWritableStream;return c===void 0?d(Mo("close")):Xt(c)?d(new TypeError("Cannot close an already-closing stream")):fh(this)}releaseLock(){if(!ar(this))throw ur("releaseLock");this._ownerWritableStream!==void 0&&ph(this)}write(c=void 0){return ar(this)?this._ownerWritableStream===void 0?d(Mo("write to")):mh(this,c):d(ur("write"))}}Object.defineProperties(yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(yn.prototype.abort,"abort"),o(yn.prototype.close,"close"),o(yn.prototype.releaseLock,"releaseLock"),o(yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function ar(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof yn}function Db(i,c){let p=i._ownerWritableStream;return Vs(p,c)}function fh(i){let c=i._ownerWritableStream;return dh(c)}function Rb(i){let c=i._ownerWritableStream,p=c._state;return Xt(c)||p==="closed"?f(void 0):p==="errored"?d(c._storedError):fh(i)}function xb(i,c){i._closedPromiseState==="pending"?Ku(i,c):jb(i,c)}function hh(i,c){i._readyPromiseState==="pending"?kh(i,c):$b(i,c)}function Ob(i){let c=i._ownerWritableStream,p=c._state;return p==="errored"||p==="erroring"?null:p==="closed"?0:_h(c._writableStreamController)}function ph(i){let c=i._ownerWritableStream,p=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");hh(i,p),xb(i,p),c._writer=void 0,i._ownerWritableStream=void 0}function mh(i,c){let p=i._ownerWritableStream,A=p._writableStreamController,x=Ib(A,c);if(p!==i._ownerWritableStream)return d(Mo("write to"));let j=p._state;if(j==="errored")return d(p._storedError);if(Xt(p)||j==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return d(p._storedError);let z=Cb(p);return Nb(A,c,x),z}let gh={};class Lr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Gu(this))throw Vu("abortReason");return this._abortReason}get signal(){if(!Gu(this))throw Vu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(c=void 0){if(!Gu(this))throw Vu("error");this._controlledWritableStream._state==="writable"&&bh(this,c)}[R](c){let p=this._abortAlgorithm(c);return Ys(this),p}[$](){Mn(this)}}Object.defineProperties(Lr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Lr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Gu(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Lr}function yh(i,c,p,A,x,j,z,ne){c._controlledWritableStream=i,i._writableStreamController=c,c._queue=void 0,c._queueTotalSize=void 0,Mn(c),c._abortReason=void 0,c._abortController=_b(),c._started=!1,c._strategySizeAlgorithm=ne,c._strategyHWM=z,c._writeAlgorithm=A,c._closeAlgorithm=x,c._abortAlgorithm=j;let pe=Ju(c);Wu(i,pe);let le=p(),me=f(le);m(me,()=>(c._started=!0,Qs(c),null),be=>(c._started=!0,qu(i,be),null))}function Pb(i,c,p,A){let x=Object.create(Lr.prototype),j,z,ne,pe;c.start!==void 0?j=()=>c.start(x):j=()=>{},c.write!==void 0?z=le=>c.write(le,x):z=()=>f(void 0),c.close!==void 0?ne=()=>c.close():ne=()=>f(void 0),c.abort!==void 0?pe=le=>c.abort(le):pe=()=>f(void 0),yh(i,x,j,z,ne,pe,p,A)}function Ys(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function Fb(i){Iu(i,gh,0),Qs(i)}function Ib(i,c){try{return i._strategySizeAlgorithm(c)}catch(p){return Bo(i,p),1}}function _h(i){return i._strategyHWM-i._queueTotalSize}function Nb(i,c,p){try{Iu(i,c,p)}catch(x){Bo(i,x);return}let A=i._controlledWritableStream;if(!Xt(A)&&A._state==="writable"){let x=Ju(i);Wu(A,x)}Qs(i)}function Qs(i){let c=i._controlledWritableStream;if(!i._started||c._inFlightWriteRequest!==void 0)return;if(c._state==="erroring"){Hu(c);return}if(i._queue.length===0)return;let A=K_(i);A===gh?Bb(i):Mb(i,A)}function Bo(i,c){i._controlledWritableStream._state==="writable"&&bh(i,c)}function Bb(i){let c=i._controlledWritableStream;Tb(c),Fu(i);let p=i._closeAlgorithm();Ys(i),m(p,()=>(kb(c),null),A=>(Ab(c,A),null))}function Mb(i,c){let p=i._controlledWritableStream;vb(p);let A=i._writeAlgorithm(c);m(A,()=>{wb(p);let x=p._state;if(Fu(i),!Xt(p)&&x==="writable"){let j=Ju(i);Wu(p,j)}return Qs(i),null},x=>(p._state==="writable"&&Ys(i),Eb(p,x),null))}function Ju(i){return _h(i)<=0}function bh(i,c){let p=i._controlledWritableStream;Ys(i),zu(p,c)}function Xs(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function Vu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function ur(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function Mo(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Zs(i){i._closedPromise=l((c,p)=>{i._closedPromise_resolve=c,i._closedPromise_reject=p,i._closedPromiseState="pending"})}function Ch(i,c){Zs(i),Ku(i,c)}function Lb(i){Zs(i),wh(i)}function Ku(i,c){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(c),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function jb(i,c){Ch(i,c)}function wh(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function ei(i){i._readyPromise=l((c,p)=>{i._readyPromise_resolve=c,i._readyPromise_reject=p}),i._readyPromiseState="pending"}function Yu(i,c){ei(i),kh(i,c)}function Eh(i){ei(i),Qu(i)}function kh(i,c){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(c),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function Ub(i){ei(i)}function $b(i,c){Yu(i,c)}function Qu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function qb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Xu=qb();function zb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function Hb(){let i=Xu?.DOMException;return zb(i)?i:void 0}function Wb(){let i=function(p,A){this.message=p||"",this.name=A||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let Gb=Hb()||Wb();function Ah(i,c,p,A,x,j){let z=U(i),ne=ch(c);i._disturbed=!0;let pe=!1,le=f(void 0);return l((me,be)=>{let Re;if(j!==void 0){if(Re=()=>{let de=j.reason!==void 0?j.reason:new Gb("Aborted","AbortError"),we=[];A||we.push(()=>c._state==="writable"?Vs(c,de):f(void 0)),x||we.push(()=>i._state==="readable"?jt(i,de):f(void 0)),at(()=>Promise.all(we.map(Pe=>Pe())),!0,de)},j.aborted){Re();return}j.addEventListener("abort",Re)}function Ut(){return l((de,we)=>{function Pe(ht){ht?de():h(qr(),Pe,we)}Pe(!1)})}function qr(){return pe?f(!0):h(ne._readyPromise,()=>l((de,we)=>{ie(z,{_chunkSteps:Pe=>{le=h(mh(ne,Pe),void 0,e),de(!1)},_closeSteps:()=>de(!0),_errorSteps:we})}))}if(bn(i,z._closedPromise,de=>(A?vt(!0,de):at(()=>Vs(c,de),!0,de),null)),bn(c,ne._closedPromise,de=>(x?vt(!0,de):at(()=>jt(i,de),!0,de),null)),rt(i,z._closedPromise,()=>(p?vt():at(()=>Rb(ne)),null)),Xt(c)||c._state==="closed"){let de=new TypeError("the destination writable stream closed before all data could be piped to it");x?vt(!0,de):at(()=>jt(i,de),!0,de)}g(Ut());function zn(){let de=le;return h(le,()=>de!==le?zn():void 0)}function bn(de,we,Pe){de._state==="errored"?Pe(de._storedError):w(we,Pe)}function rt(de,we,Pe){de._state==="closed"?Pe():C(we,Pe)}function at(de,we,Pe){if(pe)return;pe=!0,c._state==="writable"&&!Xt(c)?C(zn(),ht):ht();function ht(){return m(de(),()=>Cn(we,Pe),zr=>Cn(!0,zr)),null}}function vt(de,we){pe||(pe=!0,c._state==="writable"&&!Xt(c)?C(zn(),()=>Cn(de,we)):Cn(de,we))}function Cn(de,we){return ph(ne),Q(z),j!==void 0&&j.removeEventListener("abort",Re),de?be(we):me(void 0),null}})}class _n{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ti(this))throw ri("desiredSize");return Zu(this)}close(){if(!ti(this))throw ri("close");if(!Ur(this))throw new TypeError("The stream is not in a state that permits close");cr(this)}enqueue(c=void 0){if(!ti(this))throw ri("enqueue");if(!Ur(this))throw new TypeError("The stream is not in a state that permits enqueue");return jr(this,c)}error(c=void 0){if(!ti(this))throw ri("error");Lt(this,c)}[H](c){Mn(this);let p=this._cancelAlgorithm(c);return ni(this),p}[P](c){let p=this._controlledReadableStream;if(this._queue.length>0){let A=Fu(this);this._closeRequested&&this._queue.length===0?(ni(this),Uo(p)):Lo(this),c._chunkSteps(A)}else O(p,c),Lo(this)}[K](){}}Object.defineProperties(_n.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(_n.prototype.close,"close"),o(_n.prototype.enqueue,"enqueue"),o(_n.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(_n.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function ti(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof _n}function Lo(i){if(!Sh(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let p=i._pullAlgorithm();m(p,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Lo(i)),null),A=>(Lt(i,A),null))}function Sh(i){let c=i._controlledReadableStream;return!Ur(i)||!i._started?!1:!!($n(c)&&L(c)>0||Zu(i)>0)}function ni(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function cr(i){if(!Ur(i))return;let c=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(ni(i),Uo(c))}function jr(i,c){if(!Ur(i))return;let p=i._controlledReadableStream;if($n(p)&&L(p)>0)I(p,c,!1);else{let A;try{A=i._strategySizeAlgorithm(c)}catch(x){throw Lt(i,x),x}try{Iu(i,c,A)}catch(x){throw Lt(i,x),x}}Lo(i)}function Lt(i,c){let p=i._controlledReadableStream;p._state==="readable"&&(Mn(i),ni(i),Rh(p,c))}function Zu(i){let c=i._controlledReadableStream._state;return c==="errored"?null:c==="closed"?0:i._strategyHWM-i._queueTotalSize}function Jb(i){return!Sh(i)}function Ur(i){let c=i._controlledReadableStream._state;return!i._closeRequested&&c==="readable"}function Th(i,c,p,A,x,j,z){c._controlledReadableStream=i,c._queue=void 0,c._queueTotalSize=void 0,Mn(c),c._started=!1,c._closeRequested=!1,c._pullAgain=!1,c._pulling=!1,c._strategySizeAlgorithm=z,c._strategyHWM=j,c._pullAlgorithm=A,c._cancelAlgorithm=x,i._readableStreamController=c;let ne=p();m(f(ne),()=>(c._started=!0,Lo(c),null),pe=>(Lt(c,pe),null))}function Vb(i,c,p,A){let x=Object.create(_n.prototype),j,z,ne;c.start!==void 0?j=()=>c.start(x):j=()=>{},c.pull!==void 0?z=()=>c.pull(x):z=()=>f(void 0),c.cancel!==void 0?ne=pe=>c.cancel(pe):ne=()=>f(void 0),Th(i,x,j,z,ne,p,A)}function ri(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function Kb(i,c){return or(i._readableStreamController)?Qb(i):Yb(i)}function Yb(i,c){let p=U(i),A=!1,x=!1,j=!1,z=!1,ne,pe,le,me,be,Re=l(rt=>{be=rt});function Ut(){return A?(x=!0,f(void 0)):(A=!0,ie(p,{_chunkSteps:at=>{_(()=>{x=!1;let vt=at,Cn=at;j||jr(le._readableStreamController,vt),z||jr(me._readableStreamController,Cn),A=!1,x&&Ut()})},_closeSteps:()=>{A=!1,j||cr(le._readableStreamController),z||cr(me._readableStreamController),(!j||!z)&&be(void 0)},_errorSteps:()=>{A=!1}}),f(void 0))}function qr(rt){if(j=!0,ne=rt,z){let at=ve([ne,pe]),vt=jt(i,at);be(vt)}return Re}function zn(rt){if(z=!0,pe=rt,j){let at=ve([ne,pe]),vt=jt(i,at);be(vt)}return Re}function bn(){}return le=jo(bn,Ut,qr),me=jo(bn,Ut,zn),w(p._closedPromise,rt=>(Lt(le._readableStreamController,rt),Lt(me._readableStreamController,rt),(!j||!z)&&be(void 0),null)),[le,me]}function Qb(i){let c=U(i),p=!1,A=!1,x=!1,j=!1,z=!1,ne,pe,le,me,be,Re=l(de=>{be=de});function Ut(de){w(de._closedPromise,we=>(de!==c||(Tt(le._readableStreamController,we),Tt(me._readableStreamController,we),(!j||!z)&&be(void 0)),null))}function qr(){ir(c)&&(Q(c),c=U(i),Ut(c)),ie(c,{_chunkSteps:we=>{_(()=>{A=!1,x=!1;let Pe=we,ht=we;if(!j&&!z)try{ht=Hf(we)}catch(zr){Tt(le._readableStreamController,zr),Tt(me._readableStreamController,zr),be(jt(i,zr));return}j||qs(le._readableStreamController,Pe),z||qs(me._readableStreamController,ht),p=!1,A?bn():x&&rt()})},_closeSteps:()=>{p=!1,j||Fo(le._readableStreamController),z||Fo(me._readableStreamController),le._readableStreamController._pendingPullIntos.length>0&&zs(le._readableStreamController,0),me._readableStreamController._pendingPullIntos.length>0&&zs(me._readableStreamController,0),(!j||!z)&&be(void 0)},_errorSteps:()=>{p=!1}})}function zn(de,we){re(c)&&(Q(c),c=rh(i),Ut(c));let Pe=we?me:le,ht=we?le:me;ih(c,de,1,{_chunkSteps:Hr=>{_(()=>{A=!1,x=!1;let Wr=we?z:j;if(we?j:z)Wr||Hs(Pe._readableStreamController,Hr);else{let qh;try{qh=Hf(Hr)}catch(oc){Tt(Pe._readableStreamController,oc),Tt(ht._readableStreamController,oc),be(jt(i,oc));return}Wr||Hs(Pe._readableStreamController,Hr),qs(ht._readableStreamController,qh)}p=!1,A?bn():x&&rt()})},_closeSteps:Hr=>{p=!1;let Wr=we?z:j,di=we?j:z;Wr||Fo(Pe._readableStreamController),di||Fo(ht._readableStreamController),Hr!==void 0&&(Wr||Hs(Pe._readableStreamController,Hr),!di&&ht._readableStreamController._pendingPullIntos.length>0&&zs(ht._readableStreamController,0)),(!Wr||!di)&&be(void 0)},_errorSteps:()=>{p=!1}})}function bn(){if(p)return A=!0,f(void 0);p=!0;let de=ju(le._readableStreamController);return de===null?qr():zn(de._view,!1),f(void 0)}function rt(){if(p)return x=!0,f(void 0);p=!0;let de=ju(me._readableStreamController);return de===null?qr():zn(de._view,!0),f(void 0)}function at(de){if(j=!0,ne=de,z){let we=ve([ne,pe]),Pe=jt(i,we);be(Pe)}return Re}function vt(de){if(z=!0,pe=de,j){let we=ve([ne,pe]),Pe=jt(i,we);be(Pe)}return Re}function Cn(){}return le=Dh(Cn,bn,at),me=Dh(Cn,rt,vt),Ut(c),[le,me]}function Xb(i){return n(i)&&typeof i.getReader<"u"}function Zb(i){return Xb(i)?tC(i.getReader()):eC(i)}function eC(i){let c,p=zf(i,"async"),A=e;function x(){let z;try{z=W_(p)}catch(pe){return d(pe)}let ne=f(z);return y(ne,pe=>{if(!n(pe))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(G_(pe))cr(c._readableStreamController);else{let me=J_(pe);jr(c._readableStreamController,me)}})}function j(z){let ne=p.iterator,pe;try{pe=js(ne,"return")}catch(be){return d(be)}if(pe===void 0)return f(void 0);let le;try{le=E(pe,ne,[z])}catch(be){return d(be)}let me=f(le);return y(me,be=>{if(!n(be))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return c=jo(A,x,j,0),c}function tC(i){let c,p=e;function A(){let j;try{j=i.read()}catch(z){return d(z)}return y(j,z=>{if(!n(z))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(z.done)cr(c._readableStreamController);else{let ne=z.value;jr(c._readableStreamController,ne)}})}function x(j){try{return f(i.cancel(j))}catch(z){return d(z)}}return c=jo(p,A,x,0),c}function nC(i,c){ae(i,c);let p=i,A=p?.autoAllocateChunkSize,x=p?.cancel,j=p?.pull,z=p?.start,ne=p?.type;return{autoAllocateChunkSize:A===void 0?void 0:F(A,`${c} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:rC(x,p,`${c} has member 'cancel' that`),pull:j===void 0?void 0:oC(j,p,`${c} has member 'pull' that`),start:z===void 0?void 0:sC(z,p,`${c} has member 'start' that`),type:ne===void 0?void 0:iC(ne,`${c} has member 'type' that`)}}function rC(i,c,p){return te(i,p),A=>b(i,c,[A])}function oC(i,c,p){return te(i,p),A=>b(i,c,[A])}function sC(i,c,p){return te(i,p),A=>E(i,c,[A])}function iC(i,c){if(i=`${i}`,i!=="bytes")throw new TypeError(`${c} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function aC(i,c){return ae(i,c),{preventCancel:!!i?.preventCancel}}function vh(i,c){ae(i,c);let p=i?.preventAbort,A=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&uC(j,`${c} has member 'signal' that`),{preventAbort:!!p,preventCancel:!!A,preventClose:!!x,signal:j}}function uC(i,c){if(!gb(i))throw new TypeError(`${c} is not an AbortSignal.`)}function cC(i,c){ae(i,c);let p=i?.readable;k(p,"readable","ReadableWritablePair"),N(p,`${c} has member 'readable' that`);let A=i?.writable;return k(A,"writable","ReadableWritablePair"),uh(A,`${c} has member 'writable' that`),{readable:p,writable:A}}class et{constructor(c={},p={}){c===void 0?c=null:Oe(c,"First parameter");let A=Js(p,"Second parameter"),x=nC(c,"First parameter");if(ec(this),x.type==="bytes"){if(A.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=No(A,0);rb(this,x,j)}else{let j=Gs(A),z=No(A,1);Vb(this,x,z,j)}}get locked(){if(!Un(this))throw lr("locked");return $n(this)}cancel(c=void 0){return Un(this)?$n(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):jt(this,c):d(lr("cancel"))}getReader(c=void 0){if(!Un(this))throw lr("getReader");return sb(c,"First parameter").mode===void 0?U(this):rh(this)}pipeThrough(c,p={}){if(!Un(this))throw lr("pipeThrough");Ue(c,1,"pipeThrough");let A=cC(c,"First parameter"),x=vh(p,"Second parameter");if($n(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Mr(A.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=Ah(this,A.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return g(j),A.readable}pipeTo(c,p={}){if(!Un(this))return d(lr("pipeTo"));if(c===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!Br(c))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let A;try{A=vh(p,"Second parameter")}catch(x){return d(x)}return $n(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Mr(c)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Ah(this,c,A.preventClose,A.preventAbort,A.preventCancel,A.signal)}tee(){if(!Un(this))throw lr("tee");let c=Kb(this);return ve(c)}values(c=void 0){if(!Un(this))throw lr("values");let p=aC(c,"First parameter");return Pr(this,p.preventCancel)}[Pu](c){return this.values(c)}static from(c){return Zb(c)}}Object.defineProperties(et,{from:{enumerable:!0}}),Object.defineProperties(et.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(et.from,"from"),o(et.prototype.cancel,"cancel"),o(et.prototype.getReader,"getReader"),o(et.prototype.pipeThrough,"pipeThrough"),o(et.prototype.pipeTo,"pipeTo"),o(et.prototype.tee,"tee"),o(et.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(et.prototype,Pu,{value:et.prototype.values,writable:!0,configurable:!0});function jo(i,c,p,A=1,x=()=>1){let j=Object.create(et.prototype);ec(j);let z=Object.create(_n.prototype);return Th(j,z,i,c,p,A,x),j}function Dh(i,c,p){let A=Object.create(et.prototype);ec(A);let x=Object.create(gn.prototype);return nh(A,x,i,c,p,0,void 0),A}function ec(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Un(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof et}function $n(i){return i._reader!==void 0}function jt(i,c){if(i._disturbed=!0,i._state==="closed")return f(void 0);if(i._state==="errored")return d(i._storedError);Uo(i);let p=i._reader;if(p!==void 0&&ir(p)){let x=p._readIntoRequests;p._readIntoRequests=new v,x.forEach(j=>{j._closeSteps(void 0)})}let A=i._readableStreamController[H](c);return y(A,e)}function Uo(i){i._state="closed";let c=i._reader;if(c!==void 0&&(ue(c),re(c))){let p=c._readRequests;c._readRequests=new v,p.forEach(A=>{A._closeSteps()})}}function Rh(i,c){i._state="errored",i._storedError=c;let p=i._reader;p!==void 0&&(J(p,c),re(p)?Ie(p,c):ah(p,c))}function lr(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function xh(i,c){ae(i,c);let p=i?.highWaterMark;return k(p,"highWaterMark","QueuingStrategyInit"),{highWaterMark:T(p)}}let Oh=i=>i.byteLength;o(Oh,"size");class oi{constructor(c){Ue(c,1,"ByteLengthQueuingStrategy"),c=xh(c,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Fh(this))throw Ph("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Fh(this))throw Ph("size");return Oh}}Object.defineProperties(oi.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(oi.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Ph(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function Fh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof oi}let Ih=()=>1;o(Ih,"size");class si{constructor(c){Ue(c,1,"CountQueuingStrategy"),c=xh(c,"First parameter"),this._countQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Bh(this))throw Nh("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Bh(this))throw Nh("size");return Ih}}Object.defineProperties(si.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(si.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Nh(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Bh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof si}function lC(i,c){ae(i,c);let p=i?.cancel,A=i?.flush,x=i?.readableType,j=i?.start,z=i?.transform,ne=i?.writableType;return{cancel:p===void 0?void 0:pC(p,i,`${c} has member 'cancel' that`),flush:A===void 0?void 0:dC(A,i,`${c} has member 'flush' that`),readableType:x,start:j===void 0?void 0:fC(j,i,`${c} has member 'start' that`),transform:z===void 0?void 0:hC(z,i,`${c} has member 'transform' that`),writableType:ne}}function dC(i,c,p){return te(i,p),A=>b(i,c,[A])}function fC(i,c,p){return te(i,p),A=>E(i,c,[A])}function hC(i,c,p){return te(i,p),(A,x)=>b(i,c,[A,x])}function pC(i,c,p){return te(i,p),A=>b(i,c,[A])}class ii{constructor(c={},p={},A={}){c===void 0&&(c=null);let x=Js(p,"Second parameter"),j=Js(A,"Third parameter"),z=lC(c,"First parameter");if(z.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(z.writableType!==void 0)throw new RangeError("Invalid writableType specified");let ne=No(j,0),pe=Gs(j),le=No(x,1),me=Gs(x),be,Re=l(Ut=>{be=Ut});mC(this,Re,le,me,ne,pe),yC(this,z),z.start!==void 0?be(z.start(this._transformStreamController)):be(void 0)}get readable(){if(!Mh(this))throw $h("readable");return this._readable}get writable(){if(!Mh(this))throw $h("writable");return this._writable}}Object.defineProperties(ii.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ii.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function mC(i,c,p,A,x,j){function z(){return c}function ne(Re){return CC(i,Re)}function pe(Re){return wC(i,Re)}function le(){return EC(i)}i._writable=bb(z,ne,le,pe,p,A);function me(){return kC(i)}function be(Re){return AC(i,Re)}i._readable=jo(z,me,be,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,ai(i,!0),i._transformStreamController=void 0}function Mh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof ii}function Lh(i,c){Lt(i._readable._readableStreamController,c),tc(i,c)}function tc(i,c){ci(i._transformStreamController),Bo(i._writable._writableStreamController,c),nc(i)}function nc(i){i._backpressure&&ai(i,!1)}function ai(i,c){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(p=>{i._backpressureChangePromise_resolve=p}),i._backpressure=c}class qn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ui(this))throw li("desiredSize");let c=this._controlledTransformStream._readable._readableStreamController;return Zu(c)}enqueue(c=void 0){if(!ui(this))throw li("enqueue");jh(this,c)}error(c=void 0){if(!ui(this))throw li("error");_C(this,c)}terminate(){if(!ui(this))throw li("terminate");bC(this)}}Object.defineProperties(qn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(qn.prototype.enqueue,"enqueue"),o(qn.prototype.error,"error"),o(qn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(qn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ui(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof qn}function gC(i,c,p,A,x){c._controlledTransformStream=i,i._transformStreamController=c,c._transformAlgorithm=p,c._flushAlgorithm=A,c._cancelAlgorithm=x,c._finishPromise=void 0,c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0}function yC(i,c){let p=Object.create(qn.prototype),A,x,j;c.transform!==void 0?A=z=>c.transform(z,p):A=z=>{try{return jh(p,z),f(void 0)}catch(ne){return d(ne)}},c.flush!==void 0?x=()=>c.flush(p):x=()=>f(void 0),c.cancel!==void 0?j=z=>c.cancel(z):j=()=>f(void 0),gC(i,p,A,x,j)}function ci(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function jh(i,c){let p=i._controlledTransformStream,A=p._readable._readableStreamController;if(!Ur(A))throw new TypeError("Readable side is not in a state that permits enqueue");try{jr(A,c)}catch(j){throw tc(p,j),p._readable._storedError}Jb(A)!==p._backpressure&&ai(p,!0)}function _C(i,c){Lh(i._controlledTransformStream,c)}function Uh(i,c){let p=i._transformAlgorithm(c);return y(p,void 0,A=>{throw Lh(i._controlledTransformStream,A),A})}function bC(i){let c=i._controlledTransformStream,p=c._readable._readableStreamController;cr(p);let A=new TypeError("TransformStream terminated");tc(c,A)}function CC(i,c){let p=i._transformStreamController;if(i._backpressure){let A=i._backpressureChangePromise;return y(A,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return Uh(p,c)})}return Uh(p,c)}function wC(i,c){let p=i._transformStreamController;if(p._finishPromise!==void 0)return p._finishPromise;let A=i._readable;p._finishPromise=l((j,z)=>{p._finishPromise_resolve=j,p._finishPromise_reject=z});let x=p._cancelAlgorithm(c);return ci(p),m(x,()=>(A._state==="errored"?$r(p,A._storedError):(Lt(A._readableStreamController,c),rc(p)),null),j=>(Lt(A._readableStreamController,j),$r(p,j),null)),p._finishPromise}function EC(i){let c=i._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let p=i._readable;c._finishPromise=l((x,j)=>{c._finishPromise_resolve=x,c._finishPromise_reject=j});let A=c._flushAlgorithm();return ci(c),m(A,()=>(p._state==="errored"?$r(c,p._storedError):(cr(p._readableStreamController),rc(c)),null),x=>(Lt(p._readableStreamController,x),$r(c,x),null)),c._finishPromise}function kC(i){return ai(i,!1),i._backpressureChangePromise}function AC(i,c){let p=i._transformStreamController;if(p._finishPromise!==void 0)return p._finishPromise;let A=i._writable;p._finishPromise=l((j,z)=>{p._finishPromise_resolve=j,p._finishPromise_reject=z});let x=p._cancelAlgorithm(c);return ci(p),m(x,()=>(A._state==="errored"?$r(p,A._storedError):(Bo(A._writableStreamController,c),nc(i),rc(p)),null),j=>(Bo(A._writableStreamController,j),nc(i),$r(p,j),null)),p._finishPromise}function li(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function rc(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function $r(i,c){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(c),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function $h(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=oi,t.CountQueuingStrategy=si,t.ReadableByteStreamController=gn,t.ReadableStream=et,t.ReadableStreamBYOBReader=Ln,t.ReadableStreamBYOBRequest=rr,t.ReadableStreamDefaultController=_n,t.ReadableStreamDefaultReader=W,t.TransformStream=ii,t.TransformStreamDefaultController=qn,t.WritableStream=jn,t.WritableStreamDefaultController=Lr,t.WritableStreamDefaultWriter=yn}))});var Um=X(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,jm())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let u=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=u.byteLength,s.enqueue(new Uint8Array(u)),r===o.size&&s.close()}})})}catch{}});async function*Vc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,$m),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+$m)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var t1,$m,qm,bE,zt,Ko=Le(()=>{t1=xe(Um(),1);$m=65536;qm=class Kc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){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 n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=new TextEncoder;for(let s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof Kc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Vc(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Vc(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Vc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),u=Math.max(a-s,0),l=this.#e,f=[],d=0;for(let m of l){if(d>=u)break;let C=ArrayBuffer.isView(m)?m.byteLength:m.size;if(s&&C<=s)s-=C,a-=C;else{let w;ArrayBuffer.isView(m)?(w=m.subarray(s,Math.min(C,a)),d+=w.byteLength):(w=m.slice(s,Math.min(C,a)),d+=w.size),a-=C,f.push(w),s=0}}let h=new Kc([],{type:String(r).toLowerCase()});return h.#n=u,h.#e=f,h}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(qm.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});bE=qm,zt=bE});var CE,wE,Jn,Yc=Le(()=>{Ko();CE=class extends zt{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof zt&&/^(File)$/.test(e[Symbol.toStringTag])}},wE=CE,Jn=wE});function Wm(t,e=zt){var n=`${zm()}${zm()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
27
+ Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?r.push(o+Qc(a)+`"\r
28
28
  \r
29
29
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
30
30
  `)}\r
31
- `):r.push(o+Yc(a)+`"; filename="${Yc(s.name,1)}"\r
31
+ `):r.push(o+Qc(a)+`"; filename="${Qc(s.name,1)}"\r
32
32
  Content-Type: ${s.type||"application/octet-stream"}\r
33
33
  \r
34
34
  `,s,`\r
35
- `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}var Yo,wE,EE,qm,kE,zm,Yc,br,Vn,Yi=Le(()=>{Ko();Kc();({toStringTag:Yo,iterator:wE,hasInstance:EE}=Symbol),qm=Math.random,kE="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),zm=(t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Yo])?[(n=n!==void 0?n+"":e[Yo]=="File"?e.name:"blob",t),e.name!==n||e[Yo]=="blob"?new Jn([e],n,e):e]:[t,e+""]),Yc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),br=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},Vn=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Yo](){return"FormData"}[wE](){return this.entries()}static[EE](e){return e&&typeof e=="object"&&e[Yo]==="FormData"&&!kE.some(n=>typeof e[n]!="function")}append(...e){br("append",arguments,2),this.#e.push(zm(...e))}delete(e){br("delete",arguments,1),e+="",this.#e=this.#e.filter(([n])=>n!==e)}get(e){br("get",arguments,1),e+="";for(var n=this.#e,r=n.length,o=0;o<r;o++)if(n[o][0]===e)return n[o][1];return null}getAll(e,n){return br("getAll",arguments,1),n=[],e+="",this.#e.forEach(r=>r[0]===e&&n.push(r[1])),n}has(e){return br("has",arguments,1),e+="",this.#e.some(n=>n[0]===e)}forEach(e,n){br("forEach",arguments,1);for(var[r,o]of this)e.call(n,o,r,this)}set(...e){br("set",arguments,2);var n=[],r=!0;e=zm(...e),this.#e.forEach(o=>{o[0]===e[0]?r&&(r=!n.push(e)):n.push(o)}),r&&n.push(e),this.#e=n}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Dn,Qi=Le(()=>{Dn=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var st,Qc=Le(()=>{Qi();st=class extends Dn{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}});var Xi,Xc,Qo,Wm,Gm,Jm,Zi=Le(()=>{Xi=Symbol.toStringTag,Xc=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[Xi]==="URLSearchParams",Qo=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[Xi]),Wm=t=>typeof t=="object"&&(t[Xi]==="AbortSignal"||t[Xi]==="EventTarget"),Gm=(t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},Jm=(t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r}});var Km=X((h1,Vm)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Vm.exports=globalThis.DOMException});var Cr,Ym,Qm,Zc,Xm,Zm,eg,tg,ng,rg,ea,el=Le(()=>{Cr=require("node:fs"),Ym=require("node:path"),Qm=xe(Km(),1);Kc();Ko();({stat:Zc}=Cr.promises),Xm=(t,e)=>ng((0,Cr.statSync)(t),t,e),Zm=(t,e)=>Zc(t).then(n=>ng(n,t,e)),eg=(t,e)=>Zc(t).then(n=>rg(n,t,e)),tg=(t,e)=>rg((0,Cr.statSync)(t),t,e),ng=(t,e,n="")=>new zt([new ea({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),rg=(t,e,n="")=>new Jn([new ea({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,Ym.basename)(e),{type:n,lastModified:t.mtimeMs}),ea=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new t({path:this.#e,lastModified:this.lastModified,size:n-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Zc(this.#e);if(e>this.lastModified)throw new Qm.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*(0,Cr.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var sg={};hi(sg,{toFormData:()=>xE});function RE(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function xE(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new tl(n[1]||n[2]),o,s,a,u,l,f,d=[],p=new Vn,m=_=>{a+=g.decode(_,{stream:!0})},b=_=>{d.push(_)},w=()=>{let _=new Jn(d,f,{type:l});p.append(u,_)},y=()=>{p.append(u,a)},g=new TextDecoder("utf-8");g.decode(),r.onPartBegin=function(){r.onPartData=m,r.onPartEnd=y,o="",s="",a="",u="",l="",f=null,d.length=0},r.onHeaderField=function(_){o+=g.decode(_,{stream:!0})},r.onHeaderValue=function(_){s+=g.decode(_,{stream:!0})},r.onHeaderEnd=function(){if(s+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let _=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);_&&(u=_[2]||_[3]||""),f=RE(s),f&&(r.onPartData=b,r.onPartEnd=w)}else o==="content-type"&&(l=s);s="",o=""};for await(let _ of t)r.write(_);return r.end(),p}var en,Fe,og,Kn,ta,na,AE,Xo,SE,vE,TE,DE,wr,tl,ig=Le(()=>{el();Yi();en=0,Fe={START_BOUNDARY:en++,HEADER_FIELD_START:en++,HEADER_FIELD:en++,HEADER_VALUE_START:en++,HEADER_VALUE:en++,HEADER_VALUE_ALMOST_DONE:en++,HEADERS_ALMOST_DONE:en++,PART_DATA_START:en++,PART_DATA:en++,END:en++},og=1,Kn={PART_BOUNDARY:og,LAST_BOUNDARY:og*=2},ta=10,na=13,AE=32,Xo=45,SE=58,vE=97,TE=122,DE=t=>t|32,wr=()=>{},tl=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=wr,this.onHeaderField=wr,this.onHeadersEnd=wr,this.onHeaderValue=wr,this.onPartBegin=wr,this.onPartData=wr,this.onPartEnd=wr,this.boundaryChars={},e=`\r
37
- --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:u,index:l,state:f,flags:d}=this,p=this.boundary.length,m=p-1,b=e.length,w,y,g=v=>{this[v+"Mark"]=n},_=v=>{delete this[v+"Mark"]},A=(v,T,R,$)=>{(T===void 0||T!==R)&&this[v]($&&$.subarray(T,R))},C=(v,T)=>{let R=v+"Mark";R in this&&(T?(A(v,this[R],n,e),delete this[R]):(A(v,this[R],e.length,e),this[R]=0))};for(n=0;n<r;n++)switch(w=e[n],f){case Fe.START_BOUNDARY:if(l===a.length-2){if(w===Xo)d|=Kn.LAST_BOUNDARY;else if(w!==na)return;l++;break}else if(l-1===a.length-2){if(d&Kn.LAST_BOUNDARY&&w===Xo)f=Fe.END,d=0;else if(!(d&Kn.LAST_BOUNDARY)&&w===ta)l=0,A("onPartBegin"),f=Fe.HEADER_FIELD_START;else return;break}w!==a[l+2]&&(l=-2),w===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:f=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(w===na){_("onHeaderField"),f=Fe.HEADERS_ALMOST_DONE;break}if(l++,w===Xo)break;if(w===SE){if(l===1)return;C("onHeaderField",!0),f=Fe.HEADER_VALUE_START;break}if(y=DE(w),y<vE||y>TE)return;break;case Fe.HEADER_VALUE_START:if(w===AE)break;g("onHeaderValue"),f=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:w===na&&(C("onHeaderValue",!0),A("onHeaderEnd"),f=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(w!==ta)return;f=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(w!==ta)return;A("onHeadersEnd"),f=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:f=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(n+=m;n<b&&!(e[n]in u);)n+=p;n-=m,w=e[n]}if(l<a.length)a[l]===w?(l===0&&C("onPartData",!0),l++):l=0;else if(l===a.length)l++,w===na?d|=Kn.PART_BOUNDARY:w===Xo?d|=Kn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&Kn.PART_BOUNDARY){if(l=0,w===ta){d&=~Kn.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),f=Fe.HEADER_FIELD_START;break}}else d&Kn.LAST_BOUNDARY&&w===Xo?(A("onPartEnd"),f=Fe.END,d=0):l=0;if(l>0)s[l-1]=w;else if(o>0){let v=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);A("onPartData",0,o,v),o=0,g("onPartData"),n--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=l,this.state=f,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")}}});async function nl(t){if(t[lt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[lt].disturbed=!0,t[lt].error)throw t[lt].error;let{body:e}=t;if(e===null)return mt.Buffer.alloc(0);if(!(e instanceof xt.default))return mt.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new st(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof Dn?o:new st(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?mt.Buffer.from(n.join("")):mt.Buffer.concat(n,r)}catch(o){throw new st(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new st(`Premature close of server response while trying to fetch ${t.url}`)}var xt,Rn,mt,OE,lt,tn,io,PE,ra,ag,ug,oa=Le(()=>{xt=xe(require("node:stream"),1),Rn=require("node:util"),mt=require("node:buffer");Ko();Yi();Qc();Qi();Zi();OE=(0,Rn.promisify)(xt.default.pipeline),lt=Symbol("Body internals"),tn=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:Xc(e)?e=mt.Buffer.from(e.toString()):Qo(e)||mt.Buffer.isBuffer(e)||(Rn.types.isAnyArrayBuffer(e)?e=mt.Buffer.from(e):ArrayBuffer.isView(e)?e=mt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof xt.default||(e instanceof Vn?(e=Hm(e),r=e.type.split("=")[1]):e=mt.Buffer.from(String(e))));let o=e;mt.Buffer.isBuffer(e)?o=xt.default.Readable.from(e):Qo(e)&&(o=xt.default.Readable.from(e.stream())),this[lt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof xt.default&&e.on("error",s=>{let a=s instanceof Dn?s:new st(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[lt].error=a})}get body(){return this[lt].stream}get bodyUsed(){return this[lt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await nl(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Vn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>(ig(),sg));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[lt].body&&this[lt].body.type||"",n=await this.arrayBuffer();return new zt([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await nl(this);return new TextDecoder().decode(e)}buffer(){return nl(this)}};tn.prototype.buffer=(0,Rn.deprecate)(tn.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(tn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Rn.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});io=(t,e)=>{let n,r,{body:o}=t[lt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof xt.default&&typeof o.getBoundary!="function"&&(n=new xt.PassThrough({highWaterMark:e}),r=new xt.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[lt].stream=n,o=r),o},PE=(0,Rn.deprecate)(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"),ra=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Xc(t)?"application/x-www-form-urlencoded;charset=UTF-8":Qo(t)?t.type||null:mt.Buffer.isBuffer(t)||Rn.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Vn?`multipart/form-data; boundary=${e[lt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${PE(t)}`:t instanceof xt.default?null:"text/plain;charset=UTF-8",ag=t=>{let{body:e}=t[lt];return e===null?0:Qo(e)?e.size:mt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},ug=async(t,{body:e})=>{e===null?t.end():await OE(e,t)}});function cg(t=[]){return new dt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return sa(e),ol(e,String(n)),!0}catch{return!1}}))}var rl,Zo,sa,ol,dt,ia=Le(()=>{rl=require("node:util"),Zo=xe(require("node:http"),1),sa=typeof Zo.default.validateHeaderName=="function"?Zo.default.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}},ol=typeof Zo.default.validateHeaderValue=="function"?Zo.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},dt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!rl.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||rl.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(sa(r),ol(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,u)=>(sa(a),ol(a,String(u)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(u)));case"delete":case"has":case"getAll":return a=>(sa(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,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,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(dt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var FE,es,sl=Le(()=>{FE=new Set([301,302,303,307,308]),es=t=>FE.has(t)});var Ht,gt,lg=Le(()=>{ia();oa();sl();Ht=Symbol("Response internals"),gt=class t extends tn{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new dt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=ra(e,this);s&&o.append("Content-Type",s)}this[Ht]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ht].type}get url(){return this[Ht].url||""}get status(){return this[Ht].status}get ok(){return this[Ht].status>=200&&this[Ht].status<300}get redirected(){return this[Ht].counter>0}get statusText(){return this[Ht].statusText}get headers(){return this[Ht].headers}get highWaterMark(){return this[Ht].highWaterMark}clone(){return new t(io(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,n=302){if(!es(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ht].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new dt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(gt.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 dg,fg=Le(()=>{dg=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});function hg(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 yg(t){if(!mg.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function IE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,pg.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function ao(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:IE(t)}function _g(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=hg(o),a=hg(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let u=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return ao(s)&&!ao(u)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===u.origin?s:ao(s)&&!ao(u)?"no-referrer":a;case"same-origin":return s.origin===u.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===u.origin?s:a;case"no-referrer-when-downgrade":return ao(s)&&!ao(u)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function bg(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&mg.has(r)&&(n=r);return n}var pg,mg,gg,il=Le(()=>{pg=require("node:net");mg=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),gg="strict-origin-when-cross-origin"});var Cg,wg,Ye,ts,NE,Yn,Eg,kg=Le(()=>{Cg=require("node:url"),wg=require("node:util");ia();oa();Zi();fg();il();Ye=Symbol("Request internals"),ts=t=>typeof t=="object"&&typeof t[Ye]=="object",NE=(0,wg.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Yn=class t extends tn{constructor(e,n={}){let r;if(ts(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!ts(n)&&"data"in n&&NE(),(n.body!=null||ts(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:ts(e)&&e.body!==null?io(e):null;super(s,{size:n.size||e.size||0});let a=new dt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=ra(s,this);f&&a.set("Content-Type",f)}let u=ts(e)?e.signal:null;if("signal"in n&&(u=n.signal),u!=null&&!Wm(u))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[Ye]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:u,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ye].method}get url(){return(0,Cg.format)(this[Ye].parsedURL)}get headers(){return this[Ye].headers}get redirect(){return this[Ye].redirect}get signal(){return this[Ye].signal}get referrer(){if(this[Ye].referrer==="no-referrer")return"";if(this[Ye].referrer==="client")return"about:client";if(this[Ye].referrer)return this[Ye].referrer.toString()}get referrerPolicy(){return this[Ye].referrerPolicy}set referrerPolicy(e){this[Ye].referrerPolicy=yg(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Yn.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}});Eg=t=>{let{parsedURL:e}=t[Ye],n=new dt(t[Ye].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let u=ag(t);typeof u=="number"&&!Number.isNaN(u)&&(r=String(u))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=gg),t.referrer&&t.referrer!=="no-referrer"?t[Ye].referrer=_g(t):t[Ye].referrer="no-referrer",t[Ye].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=dg(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var ns,Ag=Le(()=>{Qi();ns=class extends Dn{constructor(e,n="aborted"){super(e,n)}}});var Tg={};hi(Tg,{AbortError:()=>ns,Blob:()=>zt,FetchError:()=>st,File:()=>Jn,FormData:()=>Vn,Headers:()=>dt,Request:()=>Yn,Response:()=>gt,blobFrom:()=>Zm,blobFromSync:()=>Xm,default:()=>al,fileFrom:()=>eg,fileFromSync:()=>tg,isRedirect:()=>es});async function al(t,e){return new Promise((n,r)=>{let o=new Yn(t,e),{parsedURL:s,options:a}=Eg(o);if(!BE.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let w=Nm(o.url),y=new gt(w,{headers:{"Content-Type":w.typeFull}});n(y);return}let u=(s.protocol==="https:"?vg.default:Sg.default).request,{signal:l}=o,f=null,d=()=>{let w=new ns("The operation was aborted.");r(w),o.body&&o.body instanceof yt.default.Readable&&o.body.destroy(w),!(!f||!f.body)&&f.body.emit("error",w)};if(l&&l.aborted){d();return}let p=()=>{d(),b()},m=u(s.toString(),a);l&&l.addEventListener("abort",p);let b=()=>{m.abort(),l&&l.removeEventListener("abort",p)};m.on("error",w=>{r(new st(`request to ${o.url} failed, reason: ${w.message}`,"system",w)),b()}),ME(m,w=>{f&&f.body&&f.body.destroy(w)}),process.version<"v14"&&m.on("socket",w=>{let y;w.prependListener("end",()=>{y=w._eventsCount}),w.prependListener("close",g=>{if(f&&y<w._eventsCount&&!g){let _=new Error("Premature close");_.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",_)}})}),m.on("response",w=>{m.setTimeout(0);let y=cg(w.rawHeaders);if(es(w.statusCode)){let v=y.get("Location"),T=null;try{T=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){r(new st(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),b();return}}switch(o.redirect){case"error":r(new st(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),b();return;case"manual":break;case"follow":{if(T===null)break;if(o.counter>=o.follow){r(new st(`maximum redirect reached at: ${o.url}`,"max-redirect")),b();return}let R={headers:new dt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:io(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Gm(o.url,T)||!Jm(o.url,T))for(let G of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(G);if(w.statusCode!==303&&o.body&&e.body instanceof yt.default.Readable){r(new st("Cannot follow redirect with body being a readable stream","unsupported-redirect")),b();return}(w.statusCode===303||(w.statusCode===301||w.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let $=bg(y);$&&(R.referrerPolicy=$),n(al(new Yn(T,R))),b();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&w.once("end",()=>{l.removeEventListener("abort",p)});let g=(0,yt.pipeline)(w,new yt.PassThrough,v=>{v&&r(v)});process.version<"v12.10"&&w.on("aborted",p);let _={url:o.url,status:w.statusCode,statusText:w.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||w.statusCode===204||w.statusCode===304){f=new gt(g,_),n(f);return}let C={flush:Er.default.Z_SYNC_FLUSH,finishFlush:Er.default.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){g=(0,yt.pipeline)(g,Er.default.createGunzip(C),v=>{v&&r(v)}),f=new gt(g,_),n(f);return}if(A==="deflate"||A==="x-deflate"){let v=(0,yt.pipeline)(w,new yt.PassThrough,T=>{T&&r(T)});v.once("data",T=>{(T[0]&15)===8?g=(0,yt.pipeline)(g,Er.default.createInflate(),R=>{R&&r(R)}):g=(0,yt.pipeline)(g,Er.default.createInflateRaw(),R=>{R&&r(R)}),f=new gt(g,_),n(f)}),v.once("end",()=>{f||(f=new gt(g,_),n(f))});return}if(A==="br"){g=(0,yt.pipeline)(g,Er.default.createBrotliDecompress(),v=>{v&&r(v)}),f=new gt(g,_),n(f);return}f=new gt(g,_),n(f)}),ug(m,o).catch(r)})}function ME(t,e){let n=rs.Buffer.from(`0\r
35
+ `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}var Yo,EE,kE,zm,AE,Hm,Qc,br,Vn,Yi=Le(()=>{Ko();Yc();({toStringTag:Yo,iterator:EE,hasInstance:kE}=Symbol),zm=Math.random,AE="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Hm=(t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Yo])?[(n=n!==void 0?n+"":e[Yo]=="File"?e.name:"blob",t),e.name!==n||e[Yo]=="blob"?new Jn([e],n,e):e]:[t,e+""]),Qc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),br=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},Vn=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Yo](){return"FormData"}[EE](){return this.entries()}static[kE](e){return e&&typeof e=="object"&&e[Yo]==="FormData"&&!AE.some(n=>typeof e[n]!="function")}append(...e){br("append",arguments,2),this.#e.push(Hm(...e))}delete(e){br("delete",arguments,1),e+="",this.#e=this.#e.filter(([n])=>n!==e)}get(e){br("get",arguments,1),e+="";for(var n=this.#e,r=n.length,o=0;o<r;o++)if(n[o][0]===e)return n[o][1];return null}getAll(e,n){return br("getAll",arguments,1),n=[],e+="",this.#e.forEach(r=>r[0]===e&&n.push(r[1])),n}has(e){return br("has",arguments,1),e+="",this.#e.some(n=>n[0]===e)}forEach(e,n){br("forEach",arguments,1);for(var[r,o]of this)e.call(n,o,r,this)}set(...e){br("set",arguments,2);var n=[],r=!0;e=Hm(...e),this.#e.forEach(o=>{o[0]===e[0]?r&&(r=!n.push(e)):n.push(o)}),r&&n.push(e),this.#e=n}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Dn,Qi=Le(()=>{Dn=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var st,Xc=Le(()=>{Qi();st=class extends Dn{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}});var Xi,Zc,Qo,Gm,Jm,Vm,Zi=Le(()=>{Xi=Symbol.toStringTag,Zc=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[Xi]==="URLSearchParams",Qo=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[Xi]),Gm=t=>typeof t=="object"&&(t[Xi]==="AbortSignal"||t[Xi]==="EventTarget"),Jm=(t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},Vm=(t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r}});var Ym=X((p1,Km)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Km.exports=globalThis.DOMException});var Cr,Qm,Xm,el,Zm,eg,tg,ng,rg,og,ea,tl=Le(()=>{Cr=require("node:fs"),Qm=require("node:path"),Xm=xe(Ym(),1);Yc();Ko();({stat:el}=Cr.promises),Zm=(t,e)=>rg((0,Cr.statSync)(t),t,e),eg=(t,e)=>el(t).then(n=>rg(n,t,e)),tg=(t,e)=>el(t).then(n=>og(n,t,e)),ng=(t,e)=>og((0,Cr.statSync)(t),t,e),rg=(t,e,n="")=>new zt([new ea({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),og=(t,e,n="")=>new Jn([new ea({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,Qm.basename)(e),{type:n,lastModified:t.mtimeMs}),ea=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new t({path:this.#e,lastModified:this.lastModified,size:n-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await el(this.#e);if(e>this.lastModified)throw new Xm.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*(0,Cr.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var ig={};hi(ig,{toFormData:()=>OE});function xE(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function OE(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new nl(n[1]||n[2]),o,s,a,u,l,f,d=[],h=new Vn,m=_=>{a+=g.decode(_,{stream:!0})},C=_=>{d.push(_)},w=()=>{let _=new Jn(d,f,{type:l});h.append(u,_)},y=()=>{h.append(u,a)},g=new TextDecoder("utf-8");g.decode(),r.onPartBegin=function(){r.onPartData=m,r.onPartEnd=y,o="",s="",a="",u="",l="",f=null,d.length=0},r.onHeaderField=function(_){o+=g.decode(_,{stream:!0})},r.onHeaderValue=function(_){s+=g.decode(_,{stream:!0})},r.onHeaderEnd=function(){if(s+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let _=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);_&&(u=_[2]||_[3]||""),f=xE(s),f&&(r.onPartData=C,r.onPartEnd=w)}else o==="content-type"&&(l=s);s="",o=""};for await(let _ of t)r.write(_);return r.end(),h}var en,Fe,sg,Kn,ta,na,SE,Xo,TE,vE,DE,RE,wr,nl,ag=Le(()=>{tl();Yi();en=0,Fe={START_BOUNDARY:en++,HEADER_FIELD_START:en++,HEADER_FIELD:en++,HEADER_VALUE_START:en++,HEADER_VALUE:en++,HEADER_VALUE_ALMOST_DONE:en++,HEADERS_ALMOST_DONE:en++,PART_DATA_START:en++,PART_DATA:en++,END:en++},sg=1,Kn={PART_BOUNDARY:sg,LAST_BOUNDARY:sg*=2},ta=10,na=13,SE=32,Xo=45,TE=58,vE=97,DE=122,RE=t=>t|32,wr=()=>{},nl=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=wr,this.onHeaderField=wr,this.onHeadersEnd=wr,this.onHeaderValue=wr,this.onPartBegin=wr,this.onPartData=wr,this.onPartEnd=wr,this.boundaryChars={},e=`\r
37
+ --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:u,index:l,state:f,flags:d}=this,h=this.boundary.length,m=h-1,C=e.length,w,y,g=S=>{this[S+"Mark"]=n},_=S=>{delete this[S+"Mark"]},E=(S,v,R,$)=>{(v===void 0||v!==R)&&this[S]($&&$.subarray(v,R))},b=(S,v)=>{let R=S+"Mark";R in this&&(v?(E(S,this[R],n,e),delete this[R]):(E(S,this[R],e.length,e),this[R]=0))};for(n=0;n<r;n++)switch(w=e[n],f){case Fe.START_BOUNDARY:if(l===a.length-2){if(w===Xo)d|=Kn.LAST_BOUNDARY;else if(w!==na)return;l++;break}else if(l-1===a.length-2){if(d&Kn.LAST_BOUNDARY&&w===Xo)f=Fe.END,d=0;else if(!(d&Kn.LAST_BOUNDARY)&&w===ta)l=0,E("onPartBegin"),f=Fe.HEADER_FIELD_START;else return;break}w!==a[l+2]&&(l=-2),w===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:f=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(w===na){_("onHeaderField"),f=Fe.HEADERS_ALMOST_DONE;break}if(l++,w===Xo)break;if(w===TE){if(l===1)return;b("onHeaderField",!0),f=Fe.HEADER_VALUE_START;break}if(y=RE(w),y<vE||y>DE)return;break;case Fe.HEADER_VALUE_START:if(w===SE)break;g("onHeaderValue"),f=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:w===na&&(b("onHeaderValue",!0),E("onHeaderEnd"),f=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(w!==ta)return;f=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(w!==ta)return;E("onHeadersEnd"),f=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:f=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(n+=m;n<C&&!(e[n]in u);)n+=h;n-=m,w=e[n]}if(l<a.length)a[l]===w?(l===0&&b("onPartData",!0),l++):l=0;else if(l===a.length)l++,w===na?d|=Kn.PART_BOUNDARY:w===Xo?d|=Kn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&Kn.PART_BOUNDARY){if(l=0,w===ta){d&=~Kn.PART_BOUNDARY,E("onPartEnd"),E("onPartBegin"),f=Fe.HEADER_FIELD_START;break}}else d&Kn.LAST_BOUNDARY&&w===Xo?(E("onPartEnd"),f=Fe.END,d=0):l=0;if(l>0)s[l-1]=w;else if(o>0){let S=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);E("onPartData",0,o,S),o=0,g("onPartData"),n--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=f,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")}}});async function rl(t){if(t[lt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[lt].disturbed=!0,t[lt].error)throw t[lt].error;let{body:e}=t;if(e===null)return gt.Buffer.alloc(0);if(!(e instanceof Ot.default))return gt.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new st(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof Dn?o:new st(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?gt.Buffer.from(n.join("")):gt.Buffer.concat(n,r)}catch(o){throw new st(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new st(`Premature close of server response while trying to fetch ${t.url}`)}var Ot,Rn,gt,PE,lt,tn,io,FE,ra,ug,cg,oa=Le(()=>{Ot=xe(require("node:stream"),1),Rn=require("node:util"),gt=require("node:buffer");Ko();Yi();Xc();Qi();Zi();PE=(0,Rn.promisify)(Ot.default.pipeline),lt=Symbol("Body internals"),tn=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:Zc(e)?e=gt.Buffer.from(e.toString()):Qo(e)||gt.Buffer.isBuffer(e)||(Rn.types.isAnyArrayBuffer(e)?e=gt.Buffer.from(e):ArrayBuffer.isView(e)?e=gt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Ot.default||(e instanceof Vn?(e=Wm(e),r=e.type.split("=")[1]):e=gt.Buffer.from(String(e))));let o=e;gt.Buffer.isBuffer(e)?o=Ot.default.Readable.from(e):Qo(e)&&(o=Ot.default.Readable.from(e.stream())),this[lt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Ot.default&&e.on("error",s=>{let a=s instanceof Dn?s:new st(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[lt].error=a})}get body(){return this[lt].stream}get bodyUsed(){return this[lt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await rl(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Vn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>(ag(),ig));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[lt].body&&this[lt].body.type||"",n=await this.arrayBuffer();return new zt([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await rl(this);return new TextDecoder().decode(e)}buffer(){return rl(this)}};tn.prototype.buffer=(0,Rn.deprecate)(tn.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(tn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Rn.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});io=(t,e)=>{let n,r,{body:o}=t[lt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Ot.default&&typeof o.getBoundary!="function"&&(n=new Ot.PassThrough({highWaterMark:e}),r=new Ot.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[lt].stream=n,o=r),o},FE=(0,Rn.deprecate)(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"),ra=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Zc(t)?"application/x-www-form-urlencoded;charset=UTF-8":Qo(t)?t.type||null:gt.Buffer.isBuffer(t)||Rn.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Vn?`multipart/form-data; boundary=${e[lt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${FE(t)}`:t instanceof Ot.default?null:"text/plain;charset=UTF-8",ug=t=>{let{body:e}=t[lt];return e===null?0:Qo(e)?e.size:gt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},cg=async(t,{body:e})=>{e===null?t.end():await PE(e,t)}});function lg(t=[]){return new dt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return sa(e),sl(e,String(n)),!0}catch{return!1}}))}var ol,Zo,sa,sl,dt,ia=Le(()=>{ol=require("node:util"),Zo=xe(require("node:http"),1),sa=typeof Zo.default.validateHeaderName=="function"?Zo.default.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}},sl=typeof Zo.default.validateHeaderValue=="function"?Zo.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},dt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!ol.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||ol.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(sa(r),sl(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,u)=>(sa(a),sl(a,String(u)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(u)));case"delete":case"has":case"getAll":return a=>(sa(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,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,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(dt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var IE,es,il=Le(()=>{IE=new Set([301,302,303,307,308]),es=t=>IE.has(t)});var Ht,yt,dg=Le(()=>{ia();oa();il();Ht=Symbol("Response internals"),yt=class t extends tn{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new dt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=ra(e,this);s&&o.append("Content-Type",s)}this[Ht]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ht].type}get url(){return this[Ht].url||""}get status(){return this[Ht].status}get ok(){return this[Ht].status>=200&&this[Ht].status<300}get redirected(){return this[Ht].counter>0}get statusText(){return this[Ht].statusText}get headers(){return this[Ht].headers}get highWaterMark(){return this[Ht].highWaterMark}clone(){return new t(io(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,n=302){if(!es(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ht].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new dt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(yt.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 fg,hg=Le(()=>{fg=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});function pg(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 _g(t){if(!gg.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function NE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,mg.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function ao(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:NE(t)}function bg(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=pg(o),a=pg(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let u=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return ao(s)&&!ao(u)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===u.origin?s:ao(s)&&!ao(u)?"no-referrer":a;case"same-origin":return s.origin===u.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===u.origin?s:a;case"no-referrer-when-downgrade":return ao(s)&&!ao(u)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function Cg(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&gg.has(r)&&(n=r);return n}var mg,gg,yg,al=Le(()=>{mg=require("node:net");gg=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),yg="strict-origin-when-cross-origin"});var wg,Eg,Ye,ts,BE,Yn,kg,Ag=Le(()=>{wg=require("node:url"),Eg=require("node:util");ia();oa();Zi();hg();al();Ye=Symbol("Request internals"),ts=t=>typeof t=="object"&&typeof t[Ye]=="object",BE=(0,Eg.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Yn=class t extends tn{constructor(e,n={}){let r;if(ts(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!ts(n)&&"data"in n&&BE(),(n.body!=null||ts(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:ts(e)&&e.body!==null?io(e):null;super(s,{size:n.size||e.size||0});let a=new dt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=ra(s,this);f&&a.set("Content-Type",f)}let u=ts(e)?e.signal:null;if("signal"in n&&(u=n.signal),u!=null&&!Gm(u))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[Ye]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:u,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ye].method}get url(){return(0,wg.format)(this[Ye].parsedURL)}get headers(){return this[Ye].headers}get redirect(){return this[Ye].redirect}get signal(){return this[Ye].signal}get referrer(){if(this[Ye].referrer==="no-referrer")return"";if(this[Ye].referrer==="client")return"about:client";if(this[Ye].referrer)return this[Ye].referrer.toString()}get referrerPolicy(){return this[Ye].referrerPolicy}set referrerPolicy(e){this[Ye].referrerPolicy=_g(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Yn.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}});kg=t=>{let{parsedURL:e}=t[Ye],n=new dt(t[Ye].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let u=ug(t);typeof u=="number"&&!Number.isNaN(u)&&(r=String(u))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=yg),t.referrer&&t.referrer!=="no-referrer"?t[Ye].referrer=bg(t):t[Ye].referrer="no-referrer",t[Ye].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=fg(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var ns,Sg=Le(()=>{Qi();ns=class extends Dn{constructor(e,n="aborted"){super(e,n)}}});var Dg={};hi(Dg,{AbortError:()=>ns,Blob:()=>zt,FetchError:()=>st,File:()=>Jn,FormData:()=>Vn,Headers:()=>dt,Request:()=>Yn,Response:()=>yt,blobFrom:()=>eg,blobFromSync:()=>Zm,default:()=>ul,fileFrom:()=>tg,fileFromSync:()=>ng,isRedirect:()=>es});async function ul(t,e){return new Promise((n,r)=>{let o=new Yn(t,e),{parsedURL:s,options:a}=kg(o);if(!ME.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let w=Bm(o.url),y=new yt(w,{headers:{"Content-Type":w.typeFull}});n(y);return}let u=(s.protocol==="https:"?vg.default:Tg.default).request,{signal:l}=o,f=null,d=()=>{let w=new ns("The operation was aborted.");r(w),o.body&&o.body instanceof _t.default.Readable&&o.body.destroy(w),!(!f||!f.body)&&f.body.emit("error",w)};if(l&&l.aborted){d();return}let h=()=>{d(),C()},m=u(s.toString(),a);l&&l.addEventListener("abort",h);let C=()=>{m.abort(),l&&l.removeEventListener("abort",h)};m.on("error",w=>{r(new st(`request to ${o.url} failed, reason: ${w.message}`,"system",w)),C()}),LE(m,w=>{f&&f.body&&f.body.destroy(w)}),process.version<"v14"&&m.on("socket",w=>{let y;w.prependListener("end",()=>{y=w._eventsCount}),w.prependListener("close",g=>{if(f&&y<w._eventsCount&&!g){let _=new Error("Premature close");_.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",_)}})}),m.on("response",w=>{m.setTimeout(0);let y=lg(w.rawHeaders);if(es(w.statusCode)){let S=y.get("Location"),v=null;try{v=S===null?null:new URL(S,o.url)}catch{if(o.redirect!=="manual"){r(new st(`uri requested responds with an invalid redirect URL: ${S}`,"invalid-redirect")),C();return}}switch(o.redirect){case"error":r(new st(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),C();return;case"manual":break;case"follow":{if(v===null)break;if(o.counter>=o.follow){r(new st(`maximum redirect reached at: ${o.url}`,"max-redirect")),C();return}let R={headers:new dt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:io(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Jm(o.url,v)||!Vm(o.url,v))for(let H of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(H);if(w.statusCode!==303&&o.body&&e.body instanceof _t.default.Readable){r(new st("Cannot follow redirect with body being a readable stream","unsupported-redirect")),C();return}(w.statusCode===303||(w.statusCode===301||w.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let $=Cg(y);$&&(R.referrerPolicy=$),n(ul(new Yn(v,R))),C();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&w.once("end",()=>{l.removeEventListener("abort",h)});let g=(0,_t.pipeline)(w,new _t.PassThrough,S=>{S&&r(S)});process.version<"v12.10"&&w.on("aborted",h);let _={url:o.url,status:w.statusCode,statusText:w.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},E=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||E===null||w.statusCode===204||w.statusCode===304){f=new yt(g,_),n(f);return}let b={flush:Er.default.Z_SYNC_FLUSH,finishFlush:Er.default.Z_SYNC_FLUSH};if(E==="gzip"||E==="x-gzip"){g=(0,_t.pipeline)(g,Er.default.createGunzip(b),S=>{S&&r(S)}),f=new yt(g,_),n(f);return}if(E==="deflate"||E==="x-deflate"){let S=(0,_t.pipeline)(w,new _t.PassThrough,v=>{v&&r(v)});S.once("data",v=>{(v[0]&15)===8?g=(0,_t.pipeline)(g,Er.default.createInflate(),R=>{R&&r(R)}):g=(0,_t.pipeline)(g,Er.default.createInflateRaw(),R=>{R&&r(R)}),f=new yt(g,_),n(f)}),S.once("end",()=>{f||(f=new yt(g,_),n(f))});return}if(E==="br"){g=(0,_t.pipeline)(g,Er.default.createBrotliDecompress(),S=>{S&&r(S)}),f=new yt(g,_),n(f);return}f=new yt(g,_),n(f)}),cg(m,o).catch(r)})}function LE(t,e){let n=rs.Buffer.from(`0\r
38
38
  \r
39
- `),r=!1,o=!1,s;t.on("response",a=>{let{headers:u}=a;r=u["transfer-encoding"]==="chunked"&&!u["content-length"]}),t.on("socket",a=>{let u=()=>{if(r&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},l=f=>{o=rs.Buffer.compare(f.slice(-5),n)===0,!o&&s&&(o=rs.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&rs.Buffer.compare(f.slice(-2),n.slice(3))===0),s=f};a.prependListener("close",u),a.on("data",l),t.on("close",()=>{a.removeListener("close",u),a.removeListener("data",l)})})}var Sg,vg,Er,yt,rs,BE,Dg=Le(()=>{Sg=xe(require("node:http"),1),vg=xe(require("node:https"),1),Er=xe(require("node:zlib"),1),yt=xe(require("node:stream"),1),rs=require("node:buffer");Bm();oa();lg();ia();kg();Qc();Ag();sl();Yi();Zi();il();el();BE=new Set(["data:","http:","https:"])});var Og=X(co=>{"use strict";var LE=co&&co.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},uo;Object.defineProperty(co,"__esModule",{value:!0});co.Gaxios=void 0;var jE=LE(Ic()),UE=require("https"),kr=Mc(),$E=cm(),Rg=require("stream"),xg=Uc(),qE=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),aa=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new xg.GaxiosInterceptorManager,response:new xg.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&uo.mergeHeaders(s,n.headers),r&&uo.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await uo.#u(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let r=kr.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new kr.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof kr.GaxiosError?r=n:n instanceof Error?r=new kr.GaxiosError(n.message,e,void 0,n):r=new kr.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,$E.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new kr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":return n.json();case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(r.hostname.endsWith(u))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);uo.mergeHeaders(n,e.headers);let r=(0,jE.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let u=r.url.toString().includes("?")?"&":"?";r.url=r.url+u+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[u,l]of new URLSearchParams(r.params))a.searchParams.append(u,l);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof Rg.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await qE();n.set("content-type",`multipart/related; boundary=${a}`),r.body=Rg.Readable.from(this.getMultipartRequest(r.multipart,a))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let a=await uo.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new a(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new UE.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=kr.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
39
+ `),r=!1,o=!1,s;t.on("response",a=>{let{headers:u}=a;r=u["transfer-encoding"]==="chunked"&&!u["content-length"]}),t.on("socket",a=>{let u=()=>{if(r&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},l=f=>{o=rs.Buffer.compare(f.slice(-5),n)===0,!o&&s&&(o=rs.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&rs.Buffer.compare(f.slice(-2),n.slice(3))===0),s=f};a.prependListener("close",u),a.on("data",l),t.on("close",()=>{a.removeListener("close",u),a.removeListener("data",l)})})}var Tg,vg,Er,_t,rs,ME,Rg=Le(()=>{Tg=xe(require("node:http"),1),vg=xe(require("node:https"),1),Er=xe(require("node:zlib"),1),_t=xe(require("node:stream"),1),rs=require("node:buffer");Mm();oa();dg();ia();Ag();Xc();Sg();il();Yi();Zi();al();tl();ME=new Set(["data:","http:","https:"])});var Pg=X(co=>{"use strict";var jE=co&&co.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},uo;Object.defineProperty(co,"__esModule",{value:!0});co.Gaxios=void 0;var UE=jE(Nc()),$E=require("https"),kr=Lc(),qE=lm(),xg=require("stream"),Og=$c(),zE=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),aa=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Og.GaxiosInterceptorManager,response:new Og.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&uo.mergeHeaders(s,n.headers),r&&uo.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await uo.#u(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let r=kr.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new kr.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof kr.GaxiosError?r=n:n instanceof Error?r=new kr.GaxiosError(n.message,e,void 0,n):r=new kr.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,qE.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new kr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":return n.json();case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(r.hostname.endsWith(u))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);uo.mergeHeaders(n,e.headers);let r=(0,UE.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let u=r.url.toString().includes("?")?"&":"?";r.url=r.url+u+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[u,l]of new URLSearchParams(r.params))a.searchParams.append(u,l);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof xg.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await zE();n.set("content-type",`multipart/related; boundary=${a}`),r.body=xg.Readable.from(this.getMultipartRequest(r.multipart,a))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let a=await uo.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new a(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new $E.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=kr.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
40
40
  Content-Type: ${s}\r
41
41
  \r
42
42
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
43
- `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>xe(Im()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Dg(),Tg))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};co.Gaxios=aa;uo=aa});var Xe=X(it=>{"use strict";var zE=it&&it.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),HE=it&&it.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zE(e,t,n)};Object.defineProperty(it,"__esModule",{value:!0});it.instance=it.Gaxios=it.GaxiosError=void 0;it.request=GE;var Pg=Og();Object.defineProperty(it,"Gaxios",{enumerable:!0,get:function(){return Pg.Gaxios}});var WE=Mc();Object.defineProperty(it,"GaxiosError",{enumerable:!0,get:function(){return WE.GaxiosError}});HE(Uc(),it);it.instance=new Pg.Gaxios;async function GE(t){return it.instance.request(t)}});var ul=X((Fg,ua)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",u=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,m=1e9;function b(T){var R,$,G,P=V.prototype={constructor:V,toString:null,valueOf:null},K=new V(1),z=20,Y=4,Q=-7,ee=21,oe=-1e7,se=1e7,he=!1,J=1,Z=0,ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},je="0123456789abcdefghijklmnopqrstuvwxyz",Ce=!0;function V(E,S){var D,M,F,N,U,O,I,L,B=this;if(!(B instanceof V))return new V(E,S);if(S==null){if(E&&E._isBigNumber===!0){B.s=E.s,!E.c||E.e>se?B.c=B.e=null:E.e<oe?B.c=[B.e=0]:(B.e=E.e,B.c=E.c.slice());return}if((O=typeof E=="number")&&E*0==0){if(B.s=1/E<0?(E=-E,-1):1,E===~~E){for(N=0,U=E;U>=10;U/=10,N++);N>se?B.c=B.e=null:(B.e=N,B.c=[E]);return}L=String(E)}else{if(!n.test(L=String(E)))return G(B,L,O);B.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(N=L.indexOf("."))>-1&&(L=L.replace(".","")),(U=L.search(/e/i))>0?(N<0&&(N=U),N+=+L.slice(U+1),L=L.substring(0,U)):N<0&&(N=L.length)}else{if(_(S,2,je.length,"Base"),S==10&&Ce)return B=new V(E),Oe(B,z+B.e+1,Y);if(L=String(E),O=typeof E=="number"){if(E*0!=0)return G(B,L,O,S);if(B.s=1/E<0?(L=L.slice(1),-1):1,V.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+E)}else B.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=je.slice(0,S),N=U=0,I=L.length;U<I;U++)if(D.indexOf(M=L.charAt(U))<0){if(M=="."){if(U>N){N=I;continue}}else if(!F&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){F=!0,U=-1,N=0;continue}return G(B,String(E),O,S)}O=!1,L=$(L,S,10,B.s),(N=L.indexOf("."))>-1?L=L.replace(".",""):N=L.length}for(U=0;L.charCodeAt(U)===48;U++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice(U,++I)){if(I-=U,O&&V.DEBUG&&I>15&&(E>f||E!==o(E)))throw Error(a+B.s*E);if((N=N-U-1)>se)B.c=B.e=null;else if(N<oe)B.c=[B.e=0];else{if(B.e=N,B.c=[],U=(N+1)%l,N<0&&(U+=l),U<I){for(U&&B.c.push(+L.slice(0,U)),I-=l;U<I;)B.c.push(+L.slice(U,U+=l));U=l-(L=L.slice(U)).length}else U-=I;for(;U--;L+="0");B.c.push(+L)}}else B.c=[B.e=0]}V.clone=b,V.ROUND_UP=0,V.ROUND_DOWN=1,V.ROUND_CEIL=2,V.ROUND_FLOOR=3,V.ROUND_HALF_UP=4,V.ROUND_HALF_DOWN=5,V.ROUND_HALF_EVEN=6,V.ROUND_HALF_CEIL=7,V.ROUND_HALF_FLOOR=8,V.EUCLID=9,V.config=V.set=function(E){var S,D;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(S="DECIMAL_PLACES")&&(D=E[S],_(D,0,m,S),z=D),E.hasOwnProperty(S="ROUNDING_MODE")&&(D=E[S],_(D,0,8,S),Y=D),E.hasOwnProperty(S="EXPONENTIAL_AT")&&(D=E[S],D&&D.pop?(_(D[0],-m,0,S),_(D[1],0,m,S),Q=D[0],ee=D[1]):(_(D,-m,m,S),Q=-(ee=D<0?-D:D))),E.hasOwnProperty(S="RANGE"))if(D=E[S],D&&D.pop)_(D[0],-m,-1,S),_(D[1],1,m,S),oe=D[0],se=D[1];else if(_(D,-m,m,S),D)oe=-(se=D<0?-D:D);else throw Error(s+S+" cannot be zero: "+D);if(E.hasOwnProperty(S="CRYPTO"))if(D=E[S],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))he=D;else throw he=!D,Error(s+"crypto unavailable");else he=D;else throw Error(s+S+" not true or false: "+D);if(E.hasOwnProperty(S="MODULO_MODE")&&(D=E[S],_(D,0,9,S),J=D),E.hasOwnProperty(S="POW_PRECISION")&&(D=E[S],_(D,0,m,S),Z=D),E.hasOwnProperty(S="FORMAT"))if(D=E[S],typeof D=="object")ue=D;else throw Error(s+S+" not an object: "+D);if(E.hasOwnProperty(S="ALPHABET"))if(D=E[S],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))Ce=D.slice(0,10)=="0123456789",je=D;else throw Error(s+S+" invalid: "+D)}else throw Error(s+"Object expected: "+E);return{DECIMAL_PLACES:z,ROUNDING_MODE:Y,EXPONENTIAL_AT:[Q,ee],RANGE:[oe,se],CRYPTO:he,MODULO_MODE:J,POW_PRECISION:Z,FORMAT:ue,ALPHABET:je}},V.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!V.DEBUG)return!0;var S,D,M=E.c,F=E.e,N=E.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&F>=-m&&F<=m&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(S=(F+1)%l,S<1&&(S+=l),String(M[0]).length==S){for(S=0;S<M.length;S++)if(D=M[S],D<0||D>=u||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&F===null&&(N===null||N===1||N===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},V.maximum=V.max=function(){return te(arguments,-1)},V.minimum=V.min=function(){return te(arguments,1)},V.random=(function(){var E=9007199254740992,S=Math.random()*E&2097151?function(){return o(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,F,N,U,O,I=0,L=[],B=new V(K);if(D==null?D=z:_(D,0,m),U=r(D/l),he)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));I<U;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[I]=F[0],M[I+1]=F[1]):(L.push(O%1e14),I+=2);I=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);I<U;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=U/7}else throw he=!1,Error(s+"crypto unavailable");if(!he)for(;I<U;)O=S(),O<9e15&&(L[I++]=O%1e14);for(U=L[--I],D%=l,U&&D&&(O=d[l-D],L[I]=o(U/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[N=0];else{for(N=-1;L[0]===0;L.splice(0,1),N-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(N-=l-I)}return B.e=N,B.c=L,B}})(),V.sum=function(){for(var E=1,S=arguments,D=new V(S[0]);E<S.length;)D=D.plus(S[E++]);return D},$=(function(){var E="0123456789";function S(D,M,F,N){for(var U,O=[0],I,L=0,B=D.length;L<B;){for(I=O.length;I--;O[I]*=M);for(O[0]+=N.indexOf(D.charAt(L++)),U=0;U<O.length;U++)O[U]>F-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/F|0,O[U]%=F)}return O.reverse()}return function(D,M,F,N,U){var O,I,L,B,H,re,ie,Ae,Ie=D.indexOf("."),Me=z,ke=Y;for(Ie>=0&&(B=Z,Z=0,D=D.replace(".",""),Ae=new V(M),re=Ae.pow(D.length-Ie),Z=B,Ae.c=S(v(y(re.c),re.e,"0"),10,F,E),Ae.e=Ae.c.length),ie=S(D,M,F,U?(O=je,E):(O=E,je)),L=B=ie.length;ie[--B]==0;ie.pop());if(!ie[0])return O.charAt(0);if(Ie<0?--L:(re.c=ie,re.e=L,re.s=N,re=R(re,Ae,Me,ke,F),ie=re.c,H=re.r,L=re.e),I=L+Me+1,Ie=ie[I],B=F/2,H=H||I<0||ie[I+1]!=null,H=ke<4?(Ie!=null||H)&&(ke==0||ke==(re.s<0?3:2)):Ie>B||Ie==B&&(ke==4||H||ke==6&&ie[I-1]&1||ke==(re.s<0?8:7)),I<1||!ie[0])D=H?v(O.charAt(1),-Me,O.charAt(0)):O.charAt(0);else{if(ie.length=I,H)for(--F;++ie[--I]>F;)ie[I]=0,I||(++L,ie=[1].concat(ie));for(B=ie.length;!ie[--B];);for(Ie=0,D="";Ie<=B;D+=O.charAt(ie[Ie++]));D=v(D,L,O.charAt(0))}return D}})(),R=(function(){function E(M,F,N){var U,O,I,L,B=0,H=M.length,re=F%p,ie=F/p|0;for(M=M.slice();H--;)I=M[H]%p,L=M[H]/p|0,U=ie*I+L*re,O=re*I+U%p*p+B,B=(O/N|0)+(U/p|0)+ie*L,M[H]=O%N;return B&&(M=[B].concat(M)),M}function S(M,F,N,U){var O,I;if(N!=U)I=N>U?1:-1;else for(O=I=0;O<N;O++)if(M[O]!=F[O]){I=M[O]>F[O]?1:-1;break}return I}function D(M,F,N,U){for(var O=0;N--;)M[N]-=O,O=M[N]<F[N]?1:0,M[N]=O*U+M[N]-F[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,N,U,O){var I,L,B,H,re,ie,Ae,Ie,Me,ke,Se,qe,Pr,Fr,Ir,ft,pn,Ze=M.s==F.s?1:-1,ze=M.c,Te=F.c;if(!ze||!ze[0]||!Te||!Te[0])return new V(!M.s||!F.s||(ze?Te&&ze[0]==Te[0]:!Te)?NaN:ze&&ze[0]==0||!Te?Ze*0:Ze/0);for(Ie=new V(Ze),Me=Ie.c=[],L=M.e-F.e,Ze=N+L+1,O||(O=u,L=w(M.e/l)-w(F.e/l),Ze=Ze/l|0),B=0;Te[B]==(ze[B]||0);B++);if(Te[B]>(ze[B]||0)&&L--,Ze<0)Me.push(1),H=!0;else{for(Fr=ze.length,ft=Te.length,B=0,Ze+=2,re=o(O/(Te[0]+1)),re>1&&(Te=E(Te,re,O),ze=E(ze,re,O),ft=Te.length,Fr=ze.length),Pr=ft,ke=ze.slice(0,ft),Se=ke.length;Se<ft;ke[Se++]=0);pn=Te.slice(),pn=[0].concat(pn),Ir=Te[0],Te[1]>=O/2&&Ir++;do{if(re=0,I=S(Te,ke,ft,Se),I<0){if(qe=ke[0],ft!=Se&&(qe=qe*O+(ke[1]||0)),re=o(qe/Ir),re>1)for(re>=O&&(re=O-1),ie=E(Te,re,O),Ae=ie.length,Se=ke.length;S(ie,ke,Ae,Se)==1;)re--,D(ie,ft<Ae?pn:Te,Ae,O),Ae=ie.length,I=1;else re==0&&(I=re=1),ie=Te.slice(),Ae=ie.length;if(Ae<Se&&(ie=[0].concat(ie)),D(ke,ie,Se,O),Se=ke.length,I==-1)for(;S(Te,ke,ft,Se)<1;)re++,D(ke,ft<Se?pn:Te,Se,O),Se=ke.length}else I===0&&(re++,ke=[0]);Me[B++]=re,ke[0]?ke[Se++]=ze[Pr]||0:(ke=[ze[Pr]],Se=1)}while((Pr++<Fr||ke[0]!=null)&&Ze--);H=ke[0]!=null,Me[0]||Me.splice(0,1)}if(O==u){for(B=1,Ze=Me[0];Ze>=10;Ze/=10,B++);Oe(Ie,N+(Ie.e=B+L*l-1)+1,U,H)}else Ie.e=L,Ie.r=+H;return Ie}})();function ae(E,S,D,M){var F,N,U,O,I;if(D==null?D=Y:_(D,0,8),!E.c)return E.toString();if(F=E.c[0],U=E.e,S==null)I=y(E.c),I=M==1||M==2&&(U<=Q||U>=ee)?C(I,U):v(I,U,"0");else if(E=Oe(new V(E),S,D),N=E.e,I=y(E.c),O=I.length,M==1||M==2&&(S<=N||N<=Q)){for(;O<S;I+="0",O++);I=C(I,N)}else if(S-=U+(M===2&&N>U),I=v(I,N,"0"),N+1>O){if(--S>0)for(I+=".";S--;I+="0");}else if(S+=N-O,S>0)for(N+1==O&&(I+=".");S--;I+="0");return E.s<0&&F?"-"+I:I}function te(E,S){for(var D,M,F=1,N=new V(E[0]);F<E.length;F++)M=new V(E[F]),(!M.s||(D=g(N,M))===S||D===0&&N.s===S)&&(N=M);return N}function ve(E,S,D){for(var M=1,F=S.length;!S[--F];S.pop());for(F=S[0];F>=10;F/=10,M++);return(D=M+D*l-1)>se?E.c=E.e=null:D<oe?E.c=[E.e=0]:(E.e=D,E.c=S),E}G=(function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,U,O,I){var L,B=O?U:U.replace(F,"");if(M.test(B))N.s=isNaN(B)?null:B<0?-1:1;else{if(!O&&(B=B.replace(E,function(H,re,ie){return L=(ie=ie.toLowerCase())=="x"?16:ie=="b"?2:8,!I||I==L?re:H}),I&&(L=I,B=B.replace(S,"$1").replace(D,"0.$1")),U!=B))return new V(B,L);if(V.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+U);N.s=null}N.c=N.e=null}})();function Oe(E,S,D,M){var F,N,U,O,I,L,B,H=E.c,re=d;if(H){e:{for(F=1,O=H[0];O>=10;O/=10,F++);if(N=S-F,N<0)N+=l,U=S,I=H[L=0],B=o(I/re[F-U-1]%10);else if(L=r((N+1)/l),L>=H.length)if(M){for(;H.length<=L;H.push(0));I=B=0,F=1,N%=l,U=N-l+1}else break e;else{for(I=O=H[L],F=1;O>=10;O/=10,F++);N%=l,U=N-l+F,B=U<0?0:o(I/re[F-U-1]%10)}if(M=M||S<0||H[L+1]!=null||(U<0?I:I%re[F-U-1]),M=D<4?(B||M)&&(D==0||D==(E.s<0?3:2)):B>5||B==5&&(D==4||M||D==6&&(N>0?U>0?I/re[F-U]:0:H[L-1])%10&1||D==(E.s<0?8:7)),S<1||!H[0])return H.length=0,M?(S-=E.e+1,H[0]=re[(l-S%l)%l],E.e=-S||0):H[0]=E.e=0,E;if(N==0?(H.length=L,O=1,L--):(H.length=L+1,O=re[l-N],H[L]=U>0?o(I/re[F-U]%re[U])*O:0),M)for(;;)if(L==0){for(N=1,U=H[0];U>=10;U/=10,N++);for(U=H[0]+=O,O=1;U>=10;U/=10,O++);N!=O&&(E.e++,H[0]==u&&(H[0]=1));break}else{if(H[L]+=O,H[L]!=u)break;H[L--]=0,O=1}for(N=H.length;H[--N]===0;H.pop());}E.e>se?E.c=E.e=null:E.e<oe&&(E.c=[E.e=0])}return E}function Ue(E){var S,D=E.e;return D===null?E.toString():(S=y(E.c),S=D<=Q||D>=ee?C(S,D):v(S,D,"0"),E.s<0?"-"+S:S)}return P.absoluteValue=P.abs=function(){var E=new V(this);return E.s<0&&(E.s=1),E},P.comparedTo=function(E,S){return g(this,new V(E,S))},P.decimalPlaces=P.dp=function(E,S){var D,M,F,N=this;if(E!=null)return _(E,0,m),S==null?S=Y:_(S,0,8),Oe(new V(N),E+N.e+1,S);if(!(D=N.c))return null;if(M=((F=D.length-1)-w(this.e/l))*l,F=D[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},P.dividedBy=P.div=function(E,S){return R(this,new V(E,S),z,Y)},P.dividedToIntegerBy=P.idiv=function(E,S){return R(this,new V(E,S),0,1)},P.exponentiatedBy=P.pow=function(E,S){var D,M,F,N,U,O,I,L,B,H=this;if(E=new V(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+Ue(E));if(S!=null&&(S=new V(S)),O=E.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!E.c||!E.c[0])return B=new V(Math.pow(+Ue(H),O?E.s*(2-A(E)):+Ue(E))),S?B.mod(S):B;if(I=E.s<0,S){if(S.c?!S.c[0]:!S.s)return new V(NaN);M=!I&&H.isInteger()&&S.isInteger(),M&&(H=H.mod(S))}else{if(E.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||O&&H.c[1]>=24e7:H.c[0]<8e13||O&&H.c[0]<=9999975e7)))return N=H.s<0&&A(E)?-0:0,H.e>-1&&(N=1/N),new V(I?1/N:N);Z&&(N=r(Z/l+2))}for(O?(D=new V(.5),I&&(E.s=1),L=A(E)):(F=Math.abs(+Ue(E)),L=F%2),B=new V(K);;){if(L){if(B=B.times(H),!B.c)break;N?B.c.length>N&&(B.c.length=N):M&&(B=B.mod(S))}if(F){if(F=o(F/2),F===0)break;L=F%2}else if(E=E.times(D),Oe(E,E.e+1,1),E.e>14)L=A(E);else{if(F=+Ue(E),F===0)break;L=F%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(S))}return M?B:(I&&(B=K.div(B)),S?B.mod(S):N?Oe(B,Z,Y,U):B)},P.integerValue=function(E){var S=new V(this);return E==null?E=Y:_(E,0,8),Oe(S,S.e+1,E)},P.isEqualTo=P.eq=function(E,S){return g(this,new V(E,S))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(E,S){return g(this,new V(E,S))>0},P.isGreaterThanOrEqualTo=P.gte=function(E,S){return(S=g(this,new V(E,S)))===1||S===0},P.isInteger=function(){return!!this.c&&w(this.e/l)>this.c.length-2},P.isLessThan=P.lt=function(E,S){return g(this,new V(E,S))<0},P.isLessThanOrEqualTo=P.lte=function(E,S){return(S=g(this,new V(E,S)))===-1||S===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(E,S){var D,M,F,N,U=this,O=U.s;if(E=new V(E,S),S=E.s,!O||!S)return new V(NaN);if(O!=S)return E.s=-S,U.plus(E);var I=U.e/l,L=E.e/l,B=U.c,H=E.c;if(!I||!L){if(!B||!H)return B?(E.s=-S,E):new V(H?U:NaN);if(!B[0]||!H[0])return H[0]?(E.s=-S,E):new V(B[0]?U:Y==3?-0:0)}if(I=w(I),L=w(L),B=B.slice(),O=I-L){for((N=O<0)?(O=-O,F=B):(L=I,F=H),F.reverse(),S=O;S--;F.push(0));F.reverse()}else for(M=(N=(O=B.length)<(S=H.length))?O:S,O=S=0;S<M;S++)if(B[S]!=H[S]){N=B[S]<H[S];break}if(N&&(F=B,B=H,H=F,E.s=-E.s),S=(M=H.length)-(D=B.length),S>0)for(;S--;B[D++]=0);for(S=u-1;M>O;){if(B[--M]<H[M]){for(D=M;D&&!B[--D];B[D]=S);--B[D],B[M]+=u}B[M]-=H[M]}for(;B[0]==0;B.splice(0,1),--L);return B[0]?ve(E,B,L):(E.s=Y==3?-1:1,E.c=[E.e=0],E)},P.modulo=P.mod=function(E,S){var D,M,F=this;return E=new V(E,S),!F.c||!E.s||E.c&&!E.c[0]?new V(NaN):!E.c||F.c&&!F.c[0]?new V(F):(J==9?(M=E.s,E.s=1,D=R(F,E,0,3),E.s=M,D.s*=M):D=R(F,E,0,J),E=F.minus(D.times(E)),!E.c[0]&&J==1&&(E.s=F.s),E)},P.multipliedBy=P.times=function(E,S){var D,M,F,N,U,O,I,L,B,H,re,ie,Ae,Ie,Me,ke=this,Se=ke.c,qe=(E=new V(E,S)).c;if(!Se||!qe||!Se[0]||!qe[0])return!ke.s||!E.s||Se&&!Se[0]&&!qe||qe&&!qe[0]&&!Se?E.c=E.e=E.s=null:(E.s*=ke.s,!Se||!qe?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(M=w(ke.e/l)+w(E.e/l),E.s*=ke.s,I=Se.length,H=qe.length,I<H&&(Ae=Se,Se=qe,qe=Ae,F=I,I=H,H=F),F=I+H,Ae=[];F--;Ae.push(0));for(Ie=u,Me=p,F=H;--F>=0;){for(D=0,re=qe[F]%Me,ie=qe[F]/Me|0,U=I,N=F+U;N>F;)L=Se[--U]%Me,B=Se[U]/Me|0,O=ie*L+B*re,L=re*L+O%Me*Me+Ae[N]+D,D=(L/Ie|0)+(O/Me|0)+ie*B,Ae[N--]=L%Ie;Ae[N]=D}return D?++M:Ae.splice(0,1),ve(E,Ae,M)},P.negated=function(){var E=new V(this);return E.s=-E.s||null,E},P.plus=function(E,S){var D,M=this,F=M.s;if(E=new V(E,S),S=E.s,!F||!S)return new V(NaN);if(F!=S)return E.s=-S,M.minus(E);var N=M.e/l,U=E.e/l,O=M.c,I=E.c;if(!N||!U){if(!O||!I)return new V(F/0);if(!O[0]||!I[0])return I[0]?E:new V(O[0]?M:F*0)}if(N=w(N),U=w(U),O=O.slice(),F=N-U){for(F>0?(U=N,D=I):(F=-F,D=O),D.reverse();F--;D.push(0));D.reverse()}for(F=O.length,S=I.length,F-S<0&&(D=I,I=O,O=D,S=F),F=0;S;)F=(O[--S]=O[S]+I[S]+F)/u|0,O[S]=u===O[S]?0:O[S]%u;return F&&(O=[F].concat(O),++U),ve(E,O,U)},P.precision=P.sd=function(E,S){var D,M,F,N=this;if(E!=null&&E!==!!E)return _(E,1,m),S==null?S=Y:_(S,0,8),Oe(new V(N),E,S);if(!(D=N.c))return null;if(F=D.length-1,M=F*l+1,F=D[F]){for(;F%10==0;F/=10,M--);for(F=D[0];F>=10;F/=10,M++);}return E&&N.e+1>M&&(M=N.e+1),M},P.shiftedBy=function(E){return _(E,-f,f),this.times("1e"+E)},P.squareRoot=P.sqrt=function(){var E,S,D,M,F,N=this,U=N.c,O=N.s,I=N.e,L=z+4,B=new V("0.5");if(O!==1||!U||!U[0])return new V(!O||O<0&&(!U||U[0])?NaN:U?N:1/0);if(O=Math.sqrt(+Ue(N)),O==0||O==1/0?(S=y(U),(S.length+I)%2==0&&(S+="0"),O=Math.sqrt(+S),I=w((I+1)/2)-(I<0||I%2),O==1/0?S="5e"+I:(S=O.toExponential(),S=S.slice(0,S.indexOf("e")+1)+I),D=new V(S)):D=new V(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(F=D,D=B.times(F.plus(R(N,F,L,1))),y(F.c).slice(0,O)===(S=y(D.c)).slice(0,O))if(D.e<I&&--O,S=S.slice(O-3,O+1),S=="9999"||!M&&S=="4999"){if(!M&&(Oe(F,F.e+z+2,0),F.times(F).eq(N))){D=F;break}L+=4,O+=4,M=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(Oe(D,D.e+z+2,1),E=!D.times(D).eq(N));break}}return Oe(D,D.e+z+1,Y,E)},P.toExponential=function(E,S){return E!=null&&(_(E,0,m),E++),ae(this,E,S,1)},P.toFixed=function(E,S){return E!=null&&(_(E,0,m),E=E+this.e+1),ae(this,E,S)},P.toFormat=function(E,S,D){var M,F=this;if(D==null)E!=null&&S&&typeof S=="object"?(D=S,S=null):E&&typeof E=="object"?(D=E,E=S=null):D=ue;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=F.toFixed(E,S),F.c){var N,U=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",B=U[0],H=U[1],re=F.s<0,ie=re?B.slice(1):B,Ae=ie.length;if(I&&(N=O,O=I,I=N,Ae-=N),O>0&&Ae>0){for(N=Ae%O||O,B=ie.substr(0,N);N<Ae;N+=O)B+=L+ie.substr(N,O);I>0&&(B+=L+ie.slice(N)),re&&(B="-"+B)}M=H?B+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?H.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):H):B}return(D.prefix||"")+M+(D.suffix||"")},P.toFraction=function(E){var S,D,M,F,N,U,O,I,L,B,H,re,ie=this,Ae=ie.c;if(E!=null&&(O=new V(E),!O.isInteger()&&(O.c||O.s!==1)||O.lt(K)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Ue(O));if(!Ae)return new V(ie);for(S=new V(K),L=D=new V(K),M=I=new V(K),re=y(Ae),N=S.e=re.length-ie.e-1,S.c[0]=d[(U=N%l)<0?l+U:U],E=!E||O.comparedTo(S)>0?N>0?S:L:O,U=se,se=1/0,O=new V(re),I.c[0]=0;B=R(O,S,0,1),F=D.plus(B.times(M)),F.comparedTo(E)!=1;)D=M,M=F,L=I.plus(B.times(F=L)),I=F,S=O.minus(B.times(F=S)),O=F;return F=R(E.minus(D),M,0,1),I=I.plus(F.times(L)),D=D.plus(F.times(M)),I.s=L.s=ie.s,N=N*2,H=R(L,M,N,Y).minus(ie).abs().comparedTo(R(I,D,N,Y).minus(ie).abs())<1?[L,M]:[I,D],se=U,H},P.toNumber=function(){return+Ue(this)},P.toPrecision=function(E,S){return E!=null&&_(E,1,m),ae(this,E,S,2)},P.toString=function(E){var S,D=this,M=D.s,F=D.e;return F===null?M?(S="Infinity",M<0&&(S="-"+S)):S="NaN":(E==null?S=F<=Q||F>=ee?C(y(D.c),F):v(y(D.c),F,"0"):E===10&&Ce?(D=Oe(new V(D),z+F+1,Y),S=v(y(D.c),D.e,"0")):(_(E,2,je.length,"Base"),S=$(v(y(D.c),F,"0"),10,E,M,!0)),M<0&&D.c[0]&&(S="-"+S)),S},P.valueOf=P.toJSON=function(){return Ue(this)},P._isBigNumber=!0,T!=null&&V.set(T),V}function w(T){var R=T|0;return T>0||T===R?R:R-1}function y(T){for(var R,$,G=1,P=T.length,K=T[0]+"";G<P;){for(R=T[G++]+"",$=l-R.length;$--;R="0"+R);K+=R}for(P=K.length;K.charCodeAt(--P)===48;);return K.slice(0,P+1||1)}function g(T,R){var $,G,P=T.c,K=R.c,z=T.s,Y=R.s,Q=T.e,ee=R.e;if(!z||!Y)return null;if($=P&&!P[0],G=K&&!K[0],$||G)return $?G?0:-Y:z;if(z!=Y)return z;if($=z<0,G=Q==ee,!P||!K)return G?0:!P^$?1:-1;if(!G)return Q>ee^$?1:-1;for(Y=(Q=P.length)<(ee=K.length)?Q:ee,z=0;z<Y;z++)if(P[z]!=K[z])return P[z]>K[z]^$?1:-1;return Q==ee?0:Q>ee^$?1:-1}function _(T,R,$,G){if(T<R||T>$||T!==o(T))throw Error(s+(G||"Argument")+(typeof T=="number"?T<R||T>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(T))}function A(T){var R=T.c.length-1;return w(T.e/l)==R&&T.c[R]%2!=0}function C(T,R){return(T.length>1?T.charAt(0)+"."+T.slice(1):T)+(R<0?"e":"e+")+R}function v(T,R,$){var G,P;if(R<0){for(P=$+".";++R;P+=$);T=P+T}else if(G=T.length,++R>G){for(P=$,R-=G;--R;P+=$);T+=P}else R<G&&(T=T.slice(0,R)+"."+T.slice(R));return T}e=b(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof ua<"u"&&ua.exports?ua.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Fg)});var Mg=X((tO,Bg)=>{var Ig=ul(),Ng=Bg.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(f){return n.lastIndex=0,n.test(f)?'"'+f.replace(n,function(d){var p=s[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var p,m,b,w,y=r,g,_=d[f],A=_!=null&&(_ instanceof Ig||Ig.isBigNumber(_));switch(_&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(f)),typeof a=="function"&&(_=a.call(d,f,_)),typeof _){case"string":return A?_:u(_);case"number":return isFinite(_)?String(_):"null";case"boolean":case"null":case"bigint":return String(_);case"object":if(!_)return"null";if(r+=o,g=[],Object.prototype.toString.apply(_)==="[object Array]"){for(w=_.length,p=0;p<w;p+=1)g[p]=l(p,_)||"null";return b=g.length===0?"[]":r?`[
43
+ `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>xe(Nm()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Rg(),Dg))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};co.Gaxios=aa;uo=aa});var Xe=X(it=>{"use strict";var HE=it&&it.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WE=it&&it.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HE(e,t,n)};Object.defineProperty(it,"__esModule",{value:!0});it.instance=it.Gaxios=it.GaxiosError=void 0;it.request=JE;var Fg=Pg();Object.defineProperty(it,"Gaxios",{enumerable:!0,get:function(){return Fg.Gaxios}});var GE=Lc();Object.defineProperty(it,"GaxiosError",{enumerable:!0,get:function(){return GE.GaxiosError}});WE($c(),it);it.instance=new Fg.Gaxios;async function JE(t){return it.instance.request(t)}});var cl=X((Ig,ua)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",u=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,m=1e9;function C(v){var R,$,H,P=V.prototype={constructor:V,toString:null,valueOf:null},K=new V(1),q=20,Y=4,Q=-7,ee=21,oe=-1e7,se=1e7,he=!1,J=1,Z=0,ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},je="0123456789abcdefghijklmnopqrstuvwxyz",Ce=!0;function V(k,T){var D,M,F,N,U,O,I,L,B=this;if(!(B instanceof V))return new V(k,T);if(T==null){if(k&&k._isBigNumber===!0){B.s=k.s,!k.c||k.e>se?B.c=B.e=null:k.e<oe?B.c=[B.e=0]:(B.e=k.e,B.c=k.c.slice());return}if((O=typeof k=="number")&&k*0==0){if(B.s=1/k<0?(k=-k,-1):1,k===~~k){for(N=0,U=k;U>=10;U/=10,N++);N>se?B.c=B.e=null:(B.e=N,B.c=[k]);return}L=String(k)}else{if(!n.test(L=String(k)))return H(B,L,O);B.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(N=L.indexOf("."))>-1&&(L=L.replace(".","")),(U=L.search(/e/i))>0?(N<0&&(N=U),N+=+L.slice(U+1),L=L.substring(0,U)):N<0&&(N=L.length)}else{if(_(T,2,je.length,"Base"),T==10&&Ce)return B=new V(k),Oe(B,q+B.e+1,Y);if(L=String(k),O=typeof k=="number"){if(k*0!=0)return H(B,L,O,T);if(B.s=1/k<0?(L=L.slice(1),-1):1,V.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+k)}else B.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=je.slice(0,T),N=U=0,I=L.length;U<I;U++)if(D.indexOf(M=L.charAt(U))<0){if(M=="."){if(U>N){N=I;continue}}else if(!F&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){F=!0,U=-1,N=0;continue}return H(B,String(k),O,T)}O=!1,L=$(L,T,10,B.s),(N=L.indexOf("."))>-1?L=L.replace(".",""):N=L.length}for(U=0;L.charCodeAt(U)===48;U++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice(U,++I)){if(I-=U,O&&V.DEBUG&&I>15&&(k>f||k!==o(k)))throw Error(a+B.s*k);if((N=N-U-1)>se)B.c=B.e=null;else if(N<oe)B.c=[B.e=0];else{if(B.e=N,B.c=[],U=(N+1)%l,N<0&&(U+=l),U<I){for(U&&B.c.push(+L.slice(0,U)),I-=l;U<I;)B.c.push(+L.slice(U,U+=l));U=l-(L=L.slice(U)).length}else U-=I;for(;U--;L+="0");B.c.push(+L)}}else B.c=[B.e=0]}V.clone=C,V.ROUND_UP=0,V.ROUND_DOWN=1,V.ROUND_CEIL=2,V.ROUND_FLOOR=3,V.ROUND_HALF_UP=4,V.ROUND_HALF_DOWN=5,V.ROUND_HALF_EVEN=6,V.ROUND_HALF_CEIL=7,V.ROUND_HALF_FLOOR=8,V.EUCLID=9,V.config=V.set=function(k){var T,D;if(k!=null)if(typeof k=="object"){if(k.hasOwnProperty(T="DECIMAL_PLACES")&&(D=k[T],_(D,0,m,T),q=D),k.hasOwnProperty(T="ROUNDING_MODE")&&(D=k[T],_(D,0,8,T),Y=D),k.hasOwnProperty(T="EXPONENTIAL_AT")&&(D=k[T],D&&D.pop?(_(D[0],-m,0,T),_(D[1],0,m,T),Q=D[0],ee=D[1]):(_(D,-m,m,T),Q=-(ee=D<0?-D:D))),k.hasOwnProperty(T="RANGE"))if(D=k[T],D&&D.pop)_(D[0],-m,-1,T),_(D[1],1,m,T),oe=D[0],se=D[1];else if(_(D,-m,m,T),D)oe=-(se=D<0?-D:D);else throw Error(s+T+" cannot be zero: "+D);if(k.hasOwnProperty(T="CRYPTO"))if(D=k[T],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))he=D;else throw he=!D,Error(s+"crypto unavailable");else he=D;else throw Error(s+T+" not true or false: "+D);if(k.hasOwnProperty(T="MODULO_MODE")&&(D=k[T],_(D,0,9,T),J=D),k.hasOwnProperty(T="POW_PRECISION")&&(D=k[T],_(D,0,m,T),Z=D),k.hasOwnProperty(T="FORMAT"))if(D=k[T],typeof D=="object")ue=D;else throw Error(s+T+" not an object: "+D);if(k.hasOwnProperty(T="ALPHABET"))if(D=k[T],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))Ce=D.slice(0,10)=="0123456789",je=D;else throw Error(s+T+" invalid: "+D)}else throw Error(s+"Object expected: "+k);return{DECIMAL_PLACES:q,ROUNDING_MODE:Y,EXPONENTIAL_AT:[Q,ee],RANGE:[oe,se],CRYPTO:he,MODULO_MODE:J,POW_PRECISION:Z,FORMAT:ue,ALPHABET:je}},V.isBigNumber=function(k){if(!k||k._isBigNumber!==!0)return!1;if(!V.DEBUG)return!0;var T,D,M=k.c,F=k.e,N=k.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&F>=-m&&F<=m&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(T=(F+1)%l,T<1&&(T+=l),String(M[0]).length==T){for(T=0;T<M.length;T++)if(D=M[T],D<0||D>=u||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&F===null&&(N===null||N===1||N===-1))return!0;throw Error(s+"Invalid BigNumber: "+k)},V.maximum=V.max=function(){return te(arguments,-1)},V.minimum=V.min=function(){return te(arguments,1)},V.random=(function(){var k=9007199254740992,T=Math.random()*k&2097151?function(){return o(Math.random()*k)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,F,N,U,O,I=0,L=[],B=new V(K);if(D==null?D=q:_(D,0,m),U=r(D/l),he)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));I<U;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[I]=F[0],M[I+1]=F[1]):(L.push(O%1e14),I+=2);I=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);I<U;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=U/7}else throw he=!1,Error(s+"crypto unavailable");if(!he)for(;I<U;)O=T(),O<9e15&&(L[I++]=O%1e14);for(U=L[--I],D%=l,U&&D&&(O=d[l-D],L[I]=o(U/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[N=0];else{for(N=-1;L[0]===0;L.splice(0,1),N-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(N-=l-I)}return B.e=N,B.c=L,B}})(),V.sum=function(){for(var k=1,T=arguments,D=new V(T[0]);k<T.length;)D=D.plus(T[k++]);return D},$=(function(){var k="0123456789";function T(D,M,F,N){for(var U,O=[0],I,L=0,B=D.length;L<B;){for(I=O.length;I--;O[I]*=M);for(O[0]+=N.indexOf(D.charAt(L++)),U=0;U<O.length;U++)O[U]>F-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/F|0,O[U]%=F)}return O.reverse()}return function(D,M,F,N,U){var O,I,L,B,W,re,ie,Ae,Ie=D.indexOf("."),Me=q,ke=Y;for(Ie>=0&&(B=Z,Z=0,D=D.replace(".",""),Ae=new V(M),re=Ae.pow(D.length-Ie),Z=B,Ae.c=T(S(y(re.c),re.e,"0"),10,F,k),Ae.e=Ae.c.length),ie=T(D,M,F,U?(O=je,k):(O=k,je)),L=B=ie.length;ie[--B]==0;ie.pop());if(!ie[0])return O.charAt(0);if(Ie<0?--L:(re.c=ie,re.e=L,re.s=N,re=R(re,Ae,Me,ke,F),ie=re.c,W=re.r,L=re.e),I=L+Me+1,Ie=ie[I],B=F/2,W=W||I<0||ie[I+1]!=null,W=ke<4?(Ie!=null||W)&&(ke==0||ke==(re.s<0?3:2)):Ie>B||Ie==B&&(ke==4||W||ke==6&&ie[I-1]&1||ke==(re.s<0?8:7)),I<1||!ie[0])D=W?S(O.charAt(1),-Me,O.charAt(0)):O.charAt(0);else{if(ie.length=I,W)for(--F;++ie[--I]>F;)ie[I]=0,I||(++L,ie=[1].concat(ie));for(B=ie.length;!ie[--B];);for(Ie=0,D="";Ie<=B;D+=O.charAt(ie[Ie++]));D=S(D,L,O.charAt(0))}return D}})(),R=(function(){function k(M,F,N){var U,O,I,L,B=0,W=M.length,re=F%h,ie=F/h|0;for(M=M.slice();W--;)I=M[W]%h,L=M[W]/h|0,U=ie*I+L*re,O=re*I+U%h*h+B,B=(O/N|0)+(U/h|0)+ie*L,M[W]=O%N;return B&&(M=[B].concat(M)),M}function T(M,F,N,U){var O,I;if(N!=U)I=N>U?1:-1;else for(O=I=0;O<N;O++)if(M[O]!=F[O]){I=M[O]>F[O]?1:-1;break}return I}function D(M,F,N,U){for(var O=0;N--;)M[N]-=O,O=M[N]<F[N]?1:0,M[N]=O*U+M[N]-F[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,N,U,O){var I,L,B,W,re,ie,Ae,Ie,Me,ke,Se,qe,Pr,Fr,Ir,ft,pn,Ze=M.s==F.s?1:-1,ze=M.c,ve=F.c;if(!ze||!ze[0]||!ve||!ve[0])return new V(!M.s||!F.s||(ze?ve&&ze[0]==ve[0]:!ve)?NaN:ze&&ze[0]==0||!ve?Ze*0:Ze/0);for(Ie=new V(Ze),Me=Ie.c=[],L=M.e-F.e,Ze=N+L+1,O||(O=u,L=w(M.e/l)-w(F.e/l),Ze=Ze/l|0),B=0;ve[B]==(ze[B]||0);B++);if(ve[B]>(ze[B]||0)&&L--,Ze<0)Me.push(1),W=!0;else{for(Fr=ze.length,ft=ve.length,B=0,Ze+=2,re=o(O/(ve[0]+1)),re>1&&(ve=k(ve,re,O),ze=k(ze,re,O),ft=ve.length,Fr=ze.length),Pr=ft,ke=ze.slice(0,ft),Se=ke.length;Se<ft;ke[Se++]=0);pn=ve.slice(),pn=[0].concat(pn),Ir=ve[0],ve[1]>=O/2&&Ir++;do{if(re=0,I=T(ve,ke,ft,Se),I<0){if(qe=ke[0],ft!=Se&&(qe=qe*O+(ke[1]||0)),re=o(qe/Ir),re>1)for(re>=O&&(re=O-1),ie=k(ve,re,O),Ae=ie.length,Se=ke.length;T(ie,ke,Ae,Se)==1;)re--,D(ie,ft<Ae?pn:ve,Ae,O),Ae=ie.length,I=1;else re==0&&(I=re=1),ie=ve.slice(),Ae=ie.length;if(Ae<Se&&(ie=[0].concat(ie)),D(ke,ie,Se,O),Se=ke.length,I==-1)for(;T(ve,ke,ft,Se)<1;)re++,D(ke,ft<Se?pn:ve,Se,O),Se=ke.length}else I===0&&(re++,ke=[0]);Me[B++]=re,ke[0]?ke[Se++]=ze[Pr]||0:(ke=[ze[Pr]],Se=1)}while((Pr++<Fr||ke[0]!=null)&&Ze--);W=ke[0]!=null,Me[0]||Me.splice(0,1)}if(O==u){for(B=1,Ze=Me[0];Ze>=10;Ze/=10,B++);Oe(Ie,N+(Ie.e=B+L*l-1)+1,U,W)}else Ie.e=L,Ie.r=+W;return Ie}})();function ae(k,T,D,M){var F,N,U,O,I;if(D==null?D=Y:_(D,0,8),!k.c)return k.toString();if(F=k.c[0],U=k.e,T==null)I=y(k.c),I=M==1||M==2&&(U<=Q||U>=ee)?b(I,U):S(I,U,"0");else if(k=Oe(new V(k),T,D),N=k.e,I=y(k.c),O=I.length,M==1||M==2&&(T<=N||N<=Q)){for(;O<T;I+="0",O++);I=b(I,N)}else if(T-=U+(M===2&&N>U),I=S(I,N,"0"),N+1>O){if(--T>0)for(I+=".";T--;I+="0");}else if(T+=N-O,T>0)for(N+1==O&&(I+=".");T--;I+="0");return k.s<0&&F?"-"+I:I}function te(k,T){for(var D,M,F=1,N=new V(k[0]);F<k.length;F++)M=new V(k[F]),(!M.s||(D=g(N,M))===T||D===0&&N.s===T)&&(N=M);return N}function Te(k,T,D){for(var M=1,F=T.length;!T[--F];T.pop());for(F=T[0];F>=10;F/=10,M++);return(D=M+D*l-1)>se?k.c=k.e=null:D<oe?k.c=[k.e=0]:(k.e=D,k.c=T),k}H=(function(){var k=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,U,O,I){var L,B=O?U:U.replace(F,"");if(M.test(B))N.s=isNaN(B)?null:B<0?-1:1;else{if(!O&&(B=B.replace(k,function(W,re,ie){return L=(ie=ie.toLowerCase())=="x"?16:ie=="b"?2:8,!I||I==L?re:W}),I&&(L=I,B=B.replace(T,"$1").replace(D,"0.$1")),U!=B))return new V(B,L);if(V.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+U);N.s=null}N.c=N.e=null}})();function Oe(k,T,D,M){var F,N,U,O,I,L,B,W=k.c,re=d;if(W){e:{for(F=1,O=W[0];O>=10;O/=10,F++);if(N=T-F,N<0)N+=l,U=T,I=W[L=0],B=o(I/re[F-U-1]%10);else if(L=r((N+1)/l),L>=W.length)if(M){for(;W.length<=L;W.push(0));I=B=0,F=1,N%=l,U=N-l+1}else break e;else{for(I=O=W[L],F=1;O>=10;O/=10,F++);N%=l,U=N-l+F,B=U<0?0:o(I/re[F-U-1]%10)}if(M=M||T<0||W[L+1]!=null||(U<0?I:I%re[F-U-1]),M=D<4?(B||M)&&(D==0||D==(k.s<0?3:2)):B>5||B==5&&(D==4||M||D==6&&(N>0?U>0?I/re[F-U]:0:W[L-1])%10&1||D==(k.s<0?8:7)),T<1||!W[0])return W.length=0,M?(T-=k.e+1,W[0]=re[(l-T%l)%l],k.e=-T||0):W[0]=k.e=0,k;if(N==0?(W.length=L,O=1,L--):(W.length=L+1,O=re[l-N],W[L]=U>0?o(I/re[F-U]%re[U])*O:0),M)for(;;)if(L==0){for(N=1,U=W[0];U>=10;U/=10,N++);for(U=W[0]+=O,O=1;U>=10;U/=10,O++);N!=O&&(k.e++,W[0]==u&&(W[0]=1));break}else{if(W[L]+=O,W[L]!=u)break;W[L--]=0,O=1}for(N=W.length;W[--N]===0;W.pop());}k.e>se?k.c=k.e=null:k.e<oe&&(k.c=[k.e=0])}return k}function Ue(k){var T,D=k.e;return D===null?k.toString():(T=y(k.c),T=D<=Q||D>=ee?b(T,D):S(T,D,"0"),k.s<0?"-"+T:T)}return P.absoluteValue=P.abs=function(){var k=new V(this);return k.s<0&&(k.s=1),k},P.comparedTo=function(k,T){return g(this,new V(k,T))},P.decimalPlaces=P.dp=function(k,T){var D,M,F,N=this;if(k!=null)return _(k,0,m),T==null?T=Y:_(T,0,8),Oe(new V(N),k+N.e+1,T);if(!(D=N.c))return null;if(M=((F=D.length-1)-w(this.e/l))*l,F=D[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},P.dividedBy=P.div=function(k,T){return R(this,new V(k,T),q,Y)},P.dividedToIntegerBy=P.idiv=function(k,T){return R(this,new V(k,T),0,1)},P.exponentiatedBy=P.pow=function(k,T){var D,M,F,N,U,O,I,L,B,W=this;if(k=new V(k),k.c&&!k.isInteger())throw Error(s+"Exponent not an integer: "+Ue(k));if(T!=null&&(T=new V(T)),O=k.e>14,!W.c||!W.c[0]||W.c[0]==1&&!W.e&&W.c.length==1||!k.c||!k.c[0])return B=new V(Math.pow(+Ue(W),O?k.s*(2-E(k)):+Ue(k))),T?B.mod(T):B;if(I=k.s<0,T){if(T.c?!T.c[0]:!T.s)return new V(NaN);M=!I&&W.isInteger()&&T.isInteger(),M&&(W=W.mod(T))}else{if(k.e>9&&(W.e>0||W.e<-1||(W.e==0?W.c[0]>1||O&&W.c[1]>=24e7:W.c[0]<8e13||O&&W.c[0]<=9999975e7)))return N=W.s<0&&E(k)?-0:0,W.e>-1&&(N=1/N),new V(I?1/N:N);Z&&(N=r(Z/l+2))}for(O?(D=new V(.5),I&&(k.s=1),L=E(k)):(F=Math.abs(+Ue(k)),L=F%2),B=new V(K);;){if(L){if(B=B.times(W),!B.c)break;N?B.c.length>N&&(B.c.length=N):M&&(B=B.mod(T))}if(F){if(F=o(F/2),F===0)break;L=F%2}else if(k=k.times(D),Oe(k,k.e+1,1),k.e>14)L=E(k);else{if(F=+Ue(k),F===0)break;L=F%2}W=W.times(W),N?W.c&&W.c.length>N&&(W.c.length=N):M&&(W=W.mod(T))}return M?B:(I&&(B=K.div(B)),T?B.mod(T):N?Oe(B,Z,Y,U):B)},P.integerValue=function(k){var T=new V(this);return k==null?k=Y:_(k,0,8),Oe(T,T.e+1,k)},P.isEqualTo=P.eq=function(k,T){return g(this,new V(k,T))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(k,T){return g(this,new V(k,T))>0},P.isGreaterThanOrEqualTo=P.gte=function(k,T){return(T=g(this,new V(k,T)))===1||T===0},P.isInteger=function(){return!!this.c&&w(this.e/l)>this.c.length-2},P.isLessThan=P.lt=function(k,T){return g(this,new V(k,T))<0},P.isLessThanOrEqualTo=P.lte=function(k,T){return(T=g(this,new V(k,T)))===-1||T===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(k,T){var D,M,F,N,U=this,O=U.s;if(k=new V(k,T),T=k.s,!O||!T)return new V(NaN);if(O!=T)return k.s=-T,U.plus(k);var I=U.e/l,L=k.e/l,B=U.c,W=k.c;if(!I||!L){if(!B||!W)return B?(k.s=-T,k):new V(W?U:NaN);if(!B[0]||!W[0])return W[0]?(k.s=-T,k):new V(B[0]?U:Y==3?-0:0)}if(I=w(I),L=w(L),B=B.slice(),O=I-L){for((N=O<0)?(O=-O,F=B):(L=I,F=W),F.reverse(),T=O;T--;F.push(0));F.reverse()}else for(M=(N=(O=B.length)<(T=W.length))?O:T,O=T=0;T<M;T++)if(B[T]!=W[T]){N=B[T]<W[T];break}if(N&&(F=B,B=W,W=F,k.s=-k.s),T=(M=W.length)-(D=B.length),T>0)for(;T--;B[D++]=0);for(T=u-1;M>O;){if(B[--M]<W[M]){for(D=M;D&&!B[--D];B[D]=T);--B[D],B[M]+=u}B[M]-=W[M]}for(;B[0]==0;B.splice(0,1),--L);return B[0]?Te(k,B,L):(k.s=Y==3?-1:1,k.c=[k.e=0],k)},P.modulo=P.mod=function(k,T){var D,M,F=this;return k=new V(k,T),!F.c||!k.s||k.c&&!k.c[0]?new V(NaN):!k.c||F.c&&!F.c[0]?new V(F):(J==9?(M=k.s,k.s=1,D=R(F,k,0,3),k.s=M,D.s*=M):D=R(F,k,0,J),k=F.minus(D.times(k)),!k.c[0]&&J==1&&(k.s=F.s),k)},P.multipliedBy=P.times=function(k,T){var D,M,F,N,U,O,I,L,B,W,re,ie,Ae,Ie,Me,ke=this,Se=ke.c,qe=(k=new V(k,T)).c;if(!Se||!qe||!Se[0]||!qe[0])return!ke.s||!k.s||Se&&!Se[0]&&!qe||qe&&!qe[0]&&!Se?k.c=k.e=k.s=null:(k.s*=ke.s,!Se||!qe?k.c=k.e=null:(k.c=[0],k.e=0)),k;for(M=w(ke.e/l)+w(k.e/l),k.s*=ke.s,I=Se.length,W=qe.length,I<W&&(Ae=Se,Se=qe,qe=Ae,F=I,I=W,W=F),F=I+W,Ae=[];F--;Ae.push(0));for(Ie=u,Me=h,F=W;--F>=0;){for(D=0,re=qe[F]%Me,ie=qe[F]/Me|0,U=I,N=F+U;N>F;)L=Se[--U]%Me,B=Se[U]/Me|0,O=ie*L+B*re,L=re*L+O%Me*Me+Ae[N]+D,D=(L/Ie|0)+(O/Me|0)+ie*B,Ae[N--]=L%Ie;Ae[N]=D}return D?++M:Ae.splice(0,1),Te(k,Ae,M)},P.negated=function(){var k=new V(this);return k.s=-k.s||null,k},P.plus=function(k,T){var D,M=this,F=M.s;if(k=new V(k,T),T=k.s,!F||!T)return new V(NaN);if(F!=T)return k.s=-T,M.minus(k);var N=M.e/l,U=k.e/l,O=M.c,I=k.c;if(!N||!U){if(!O||!I)return new V(F/0);if(!O[0]||!I[0])return I[0]?k:new V(O[0]?M:F*0)}if(N=w(N),U=w(U),O=O.slice(),F=N-U){for(F>0?(U=N,D=I):(F=-F,D=O),D.reverse();F--;D.push(0));D.reverse()}for(F=O.length,T=I.length,F-T<0&&(D=I,I=O,O=D,T=F),F=0;T;)F=(O[--T]=O[T]+I[T]+F)/u|0,O[T]=u===O[T]?0:O[T]%u;return F&&(O=[F].concat(O),++U),Te(k,O,U)},P.precision=P.sd=function(k,T){var D,M,F,N=this;if(k!=null&&k!==!!k)return _(k,1,m),T==null?T=Y:_(T,0,8),Oe(new V(N),k,T);if(!(D=N.c))return null;if(F=D.length-1,M=F*l+1,F=D[F]){for(;F%10==0;F/=10,M--);for(F=D[0];F>=10;F/=10,M++);}return k&&N.e+1>M&&(M=N.e+1),M},P.shiftedBy=function(k){return _(k,-f,f),this.times("1e"+k)},P.squareRoot=P.sqrt=function(){var k,T,D,M,F,N=this,U=N.c,O=N.s,I=N.e,L=q+4,B=new V("0.5");if(O!==1||!U||!U[0])return new V(!O||O<0&&(!U||U[0])?NaN:U?N:1/0);if(O=Math.sqrt(+Ue(N)),O==0||O==1/0?(T=y(U),(T.length+I)%2==0&&(T+="0"),O=Math.sqrt(+T),I=w((I+1)/2)-(I<0||I%2),O==1/0?T="5e"+I:(T=O.toExponential(),T=T.slice(0,T.indexOf("e")+1)+I),D=new V(T)):D=new V(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(F=D,D=B.times(F.plus(R(N,F,L,1))),y(F.c).slice(0,O)===(T=y(D.c)).slice(0,O))if(D.e<I&&--O,T=T.slice(O-3,O+1),T=="9999"||!M&&T=="4999"){if(!M&&(Oe(F,F.e+q+2,0),F.times(F).eq(N))){D=F;break}L+=4,O+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(Oe(D,D.e+q+2,1),k=!D.times(D).eq(N));break}}return Oe(D,D.e+q+1,Y,k)},P.toExponential=function(k,T){return k!=null&&(_(k,0,m),k++),ae(this,k,T,1)},P.toFixed=function(k,T){return k!=null&&(_(k,0,m),k=k+this.e+1),ae(this,k,T)},P.toFormat=function(k,T,D){var M,F=this;if(D==null)k!=null&&T&&typeof T=="object"?(D=T,T=null):k&&typeof k=="object"?(D=k,k=T=null):D=ue;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=F.toFixed(k,T),F.c){var N,U=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",B=U[0],W=U[1],re=F.s<0,ie=re?B.slice(1):B,Ae=ie.length;if(I&&(N=O,O=I,I=N,Ae-=N),O>0&&Ae>0){for(N=Ae%O||O,B=ie.substr(0,N);N<Ae;N+=O)B+=L+ie.substr(N,O);I>0&&(B+=L+ie.slice(N)),re&&(B="-"+B)}M=W?B+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?W.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):W):B}return(D.prefix||"")+M+(D.suffix||"")},P.toFraction=function(k){var T,D,M,F,N,U,O,I,L,B,W,re,ie=this,Ae=ie.c;if(k!=null&&(O=new V(k),!O.isInteger()&&(O.c||O.s!==1)||O.lt(K)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Ue(O));if(!Ae)return new V(ie);for(T=new V(K),L=D=new V(K),M=I=new V(K),re=y(Ae),N=T.e=re.length-ie.e-1,T.c[0]=d[(U=N%l)<0?l+U:U],k=!k||O.comparedTo(T)>0?N>0?T:L:O,U=se,se=1/0,O=new V(re),I.c[0]=0;B=R(O,T,0,1),F=D.plus(B.times(M)),F.comparedTo(k)!=1;)D=M,M=F,L=I.plus(B.times(F=L)),I=F,T=O.minus(B.times(F=T)),O=F;return F=R(k.minus(D),M,0,1),I=I.plus(F.times(L)),D=D.plus(F.times(M)),I.s=L.s=ie.s,N=N*2,W=R(L,M,N,Y).minus(ie).abs().comparedTo(R(I,D,N,Y).minus(ie).abs())<1?[L,M]:[I,D],se=U,W},P.toNumber=function(){return+Ue(this)},P.toPrecision=function(k,T){return k!=null&&_(k,1,m),ae(this,k,T,2)},P.toString=function(k){var T,D=this,M=D.s,F=D.e;return F===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(k==null?T=F<=Q||F>=ee?b(y(D.c),F):S(y(D.c),F,"0"):k===10&&Ce?(D=Oe(new V(D),q+F+1,Y),T=S(y(D.c),D.e,"0")):(_(k,2,je.length,"Base"),T=$(S(y(D.c),F,"0"),10,k,M,!0)),M<0&&D.c[0]&&(T="-"+T)),T},P.valueOf=P.toJSON=function(){return Ue(this)},P._isBigNumber=!0,v!=null&&V.set(v),V}function w(v){var R=v|0;return v>0||v===R?R:R-1}function y(v){for(var R,$,H=1,P=v.length,K=v[0]+"";H<P;){for(R=v[H++]+"",$=l-R.length;$--;R="0"+R);K+=R}for(P=K.length;K.charCodeAt(--P)===48;);return K.slice(0,P+1||1)}function g(v,R){var $,H,P=v.c,K=R.c,q=v.s,Y=R.s,Q=v.e,ee=R.e;if(!q||!Y)return null;if($=P&&!P[0],H=K&&!K[0],$||H)return $?H?0:-Y:q;if(q!=Y)return q;if($=q<0,H=Q==ee,!P||!K)return H?0:!P^$?1:-1;if(!H)return Q>ee^$?1:-1;for(Y=(Q=P.length)<(ee=K.length)?Q:ee,q=0;q<Y;q++)if(P[q]!=K[q])return P[q]>K[q]^$?1:-1;return Q==ee?0:Q>ee^$?1:-1}function _(v,R,$,H){if(v<R||v>$||v!==o(v))throw Error(s+(H||"Argument")+(typeof v=="number"?v<R||v>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(v))}function E(v){var R=v.c.length-1;return w(v.e/l)==R&&v.c[R]%2!=0}function b(v,R){return(v.length>1?v.charAt(0)+"."+v.slice(1):v)+(R<0?"e":"e+")+R}function S(v,R,$){var H,P;if(R<0){for(P=$+".";++R;P+=$);v=P+v}else if(H=v.length,++R>H){for(P=$,R-=H;--R;P+=$);v+=P}else R<H&&(v=v.slice(0,R)+"."+v.slice(R));return v}e=C(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof ua<"u"&&ua.exports?ua.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Ig)});var Lg=X((nO,Mg)=>{var Ng=cl(),Bg=Mg.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(f){return n.lastIndex=0,n.test(f)?'"'+f.replace(n,function(d){var h=s[d];return typeof h=="string"?h:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var h,m,C,w,y=r,g,_=d[f],E=_!=null&&(_ instanceof Ng||Ng.isBigNumber(_));switch(_&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(f)),typeof a=="function"&&(_=a.call(d,f,_)),typeof _){case"string":return E?_:u(_);case"number":return isFinite(_)?String(_):"null";case"boolean":case"null":case"bigint":return String(_);case"object":if(!_)return"null";if(r+=o,g=[],Object.prototype.toString.apply(_)==="[object Array]"){for(w=_.length,h=0;h<w;h+=1)g[h]=l(h,_)||"null";return C=g.length===0?"[]":r?`[
44
44
  `+r+g.join(`,
45
45
  `+r)+`
46
- `+y+"]":"["+g.join(",")+"]",r=y,b}if(a&&typeof a=="object")for(w=a.length,p=0;p<w;p+=1)typeof a[p]=="string"&&(m=a[p],b=l(m,_),b&&g.push(u(m)+(r?": ":":")+b));else Object.keys(_).forEach(function(C){var v=l(C,_);v&&g.push(u(C)+(r?": ":":")+v)});return b=g.length===0?"{}":r?`{
46
+ `+y+"]":"["+g.join(",")+"]",r=y,C}if(a&&typeof a=="object")for(w=a.length,h=0;h<w;h+=1)typeof a[h]=="string"&&(m=a[h],C=l(m,_),C&&g.push(u(m)+(r?": ":":")+C));else Object.keys(_).forEach(function(b){var S=l(b,_);S&&g.push(u(b)+(r?": ":":")+S)});return C=g.length===0?"{}":r?`{
47
47
  `+r+g.join(`,
48
48
  `+r)+`
49
- `+y+"}":"{"+g.join(",")+"}",r=y,b}}typeof Ng.stringify!="function"&&(Ng.stringify=function(f,d,p){var m;if(r="",o="",typeof p=="number")for(m=0;m<p;m+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":f})})})()});var jg=X((nO,Lg)=>{var ca=null,JE=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,VE=/(?: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)/,KE=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 n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
- `,r:"\r",t:" "},s,a=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},u=function(y){return y&&y!==r&&a("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var y,g="";for(r==="-"&&(g="-",u("-"));r>="0"&&r<="9";)g+=r,u();if(r===".")for(g+=".";u()&&r>="0"&&r<="9";)g+=r;if(r==="e"||r==="E")for(g+=r,u(),(r==="-"||r==="+")&&(g+=r,u());r>="0"&&r<="9";)g+=r,u();if(y=+g,!isFinite(y))a("Bad number");else return ca==null&&(ca=ul()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new ca(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new ca(y):y},f=function(){var y,g,_="",A;if(r==='"')for(var C=n;u();){if(r==='"')return n-1>C&&(_+=s.substring(C,n-1)),u(),_;if(r==="\\"){if(n-1>C&&(_+=s.substring(C,n-1)),u(),r==="u"){for(A=0,g=0;g<4&&(y=parseInt(u(),16),!!isFinite(y));g+=1)A=A*16+y;_+=String.fromCharCode(A)}else if(typeof o[r]=="string")_+=o[r];else break;C=n}}a("Bad string")},d=function(){for(;r&&r<=" ";)u()},p=function(){switch(r){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+r+"'")},m,b=function(){var y=[];if(r==="["){if(u("["),d(),r==="]")return u("]"),y;for(;r;){if(y.push(m()),d(),r==="]")return u("]"),y;u(","),d()}}a("Bad array")},w=function(){var y,g=Object.create(null);if(r==="{"){if(u("{"),d(),r==="}")return u("}"),g;for(;r;){if(y=f(),d(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&a('Duplicate key "'+y+'"'),JE.test(y)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():g[y]=m():VE.test(y)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():g[y]=m():g[y]=m(),d(),r==="}")return u("}"),g;u(","),d()}}a("Bad object")};return m=function(){switch(d(),r){case"{":return w();case"[":return b();case'"':return f();case"-":return l();default:return r>="0"&&r<="9"?l():p()}},function(y,g){var _;return s=y+"",n=0,r=" ",_=m(),d(),r&&a("Syntax error"),typeof g=="function"?(function A(C,v){var T,R,$=C[v];return $&&typeof $=="object"&&Object.keys($).forEach(function(G){R=A($,G),R!==void 0?$[G]=R:delete $[G]}),g.call(C,v,$)})({"":_},""):_}};Lg.exports=KE});var qg=X((rO,la)=>{var Ug=Mg().stringify,$g=jg();la.exports=function(t){return{parse:$g(t),stringify:Ug}};la.exports.parse=$g();la.exports.stringify=Ug});var cl=X(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.GCE_LINUX_BIOS_PATHS=void 0;Wt.isGoogleCloudServerless=Wg;Wt.isGoogleComputeEngineLinux=Gg;Wt.isGoogleComputeEngineMACAddress=Jg;Wt.isGoogleComputeEngine=Vg;Wt.detectGCPResidency=QE;var zg=require("fs"),Hg=require("os");Wt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var YE=/^42:01/;function Wg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Gg(){if((0,Hg.platform)()!=="linux")return!1;try{(0,zg.statSync)(Wt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,zg.readFileSync)(Wt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Jg(){let t=(0,Hg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(YE.test(n))return!0}return!1}function Vg(){return Gg()||Jg()}function QE(){return Wg()||Vg()}});var Kg=X(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.Colours=void 0;var nt=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="")}};da.Colours=nt;nt.enabled=!1;nt.reset="";nt.bright="";nt.dim="";nt.red="";nt.green="";nt.yellow="";nt.blue="";nt.magenta="";nt.cyan="";nt.white="";nt.grey="";nt.refresh()});var Zg=X(De=>{"use strict";var XE=De&&De.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ZE=De&&De.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Yg=De&&De.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&XE(n,e,r[o]);return ZE(n,e),n}})();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=dl;De.getDebugBackend=tk;De.getStructuredBackend=nk;De.setBackend=rk;De.log=Xg;var ek=require("events"),os=Yg(require("process")),Qg=Yg(require("util")),_t=Kg(),Gt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Gt||(De.LogSeverity=Gt={}));var ss=class extends ek.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Gt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Gt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Gt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Gt.ERROR,...r),this.func.sublog=r=>Xg(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};De.AdhocDebugLogger=ss;De.placeholder=new ss("",()=>{}).func;var lo=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=os.env[De.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};De.DebugLogBackendBase=lo;var ll=class extends lo{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${_t.Colours.green}${e}${_t.Colours.reset}`,a=`${_t.Colours.yellow}${os.pid}${_t.Colours.reset}`,u;switch(n.severity){case Gt.ERROR:u=`${_t.Colours.red}${n.severity}${_t.Colours.reset}`;break;case Gt.INFO:u=`${_t.Colours.magenta}${n.severity}${_t.Colours.reset}`;break;case Gt.WARNING:u=`${_t.Colours.yellow}${n.severity}${_t.Colours.reset}`;break;default:u=(o=n.severity)!==null&&o!==void 0?o:Gt.DEFAULT;break}let l=Qg.formatWithOptions({colors:_t.Colours.enabled},...r),f=Object.assign({},n);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",p=d?`${_t.Colours.grey}${d}${_t.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,u,l,d?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function dl(){return new ll}var fl=class extends lo{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=os.env.NODE_DEBUG)!==null&&e!==void 0?e:"";os.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function tk(t){return new fl(t)}var hl=class extends lo{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let u=(a=o.severity)!==null&&a!==void 0?a:Gt.INFO,l=Object.assign({severity:u,message:Qg.format(...s)},o),f=JSON.stringify(l);r?r(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function nk(t){return new hl(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var pl=new Map,bt;function rk(t){bt=t,pl.clear()}function Xg(t,e){if(!bt&&!os.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=pl.get(t);if(n)return n.func;if(bt===null)return De.placeholder;bt===void 0&&(bt=dl());let r=(()=>{let o;return new ss(t,(a,...u)=>{if(o!==bt){if(bt===null)return;bt===void 0&&(bt=dl()),o=bt}bt?.log(t,a,...u)})})();return pl.set(t,r),r.func}});var ml=X(Ar=>{"use strict";var ok=Ar&&Ar.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sk=Ar&&Ar.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ok(e,t,n)};Object.defineProperty(Ar,"__esModule",{value:!0});sk(Zg(),Ar)});var as=X(fe=>{"use strict";var ty=fe&&fe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ik=fe&&fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ak=fe&&fe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&ty(n,e,r[o]);return ik(n,e),n}})(),uk=fe&&fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ty(e,t,n)};Object.defineProperty(fe,"__esModule",{value:!0});fe.gcpResidencyCache=fe.METADATA_SERVER_DETECTION=fe.HEADERS=fe.HEADER_VALUE=fe.HEADER_NAME=fe.SECONDARY_HOST_ADDRESS=fe.HOST_ADDRESS=fe.BASE_PATH=void 0;fe.instance=pk;fe.project=mk;fe.universe=gk;fe.bulk=yk;fe.isAvailable=bk;fe.resetIsAvailableCache=Ck;fe.getGCPResidency=_l;fe.setGCPResidency=ny;fe.requestTimeout=ry;var gl=Xe(),ck=qg(),lk=cl(),dk=ak(ml());fe.BASE_PATH="/computeMetadata/v1";fe.HOST_ADDRESS="http://169.254.169.254";fe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";fe.HEADER_NAME="Metadata-Flavor";fe.HEADER_VALUE="Google";fe.HEADERS=Object.freeze({[fe.HEADER_NAME]:fe.HEADER_VALUE});var ey=dk.log("gcp-metadata");fe.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 yl(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||fe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(fe.BASE_PATH,t).href}function fk(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function is(t,e={},n=3,r=!1){let o=new Headers(fe.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((m,b)=>o.set(b,m)),s=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(fk(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,m)=>o.set(m,p)),a=e.params||a);let u=r?hk:gl.request,l={url:`${yl()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:ry()};ey.info("instance request %j",l);let f=await u(l);ey.info("instance metadata is %s",f.data);let d=f.headers.get(fe.HEADER_NAME);if(d!==fe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${fe.HEADER_NAME} header. Expected '${fe.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return ck.parse(f.data)}catch{}return f.data}async function hk(t){let e={...t,url:t.url?.toString().replace(yl(),yl(fe.SECONDARY_HOST_ADDRESS))},n=(0,gl.request)(t),r=(0,gl.request)(e);return Promise.any([n,r])}function pk(t){return is("instance",t)}function mk(t){return is("project",t)}function gk(t){return is("universe",t)}async function yk(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await is(n),o=n.metadataKey;e[o]=r})())),e}function _k(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var fa;async function bk(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in fe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(fe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return _l();case"ping-only":}}try{return fa===void 0&&(fa=is("instance",void 0,_k(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await fa,!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 n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Ck(){fa=void 0}fe.gcpResidencyCache=null;function _l(){return fe.gcpResidencyCache===null&&ny(),fe.gcpResidencyCache}function ny(t=null){fe.gcpResidencyCache=t!==null?t:(0,lk.detectGCPResidency)()}function ry(){return _l()?0:3e3}uk(cl(),fe)});var iy=X(ha=>{"use strict";ha.byteLength=Ek;ha.toByteArray=Ak;ha.fromByteArray=Tk;var nn=[],Ot=[],wk=typeof Uint8Array<"u"?Uint8Array:Array,bl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Sr=0,oy=bl.length;Sr<oy;++Sr)nn[Sr]=bl[Sr],Ot[bl.charCodeAt(Sr)]=Sr;var Sr,oy;Ot[45]=62;Ot[95]=63;function sy(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Ek(t){var e=sy(t),n=e[0],r=e[1];return(n+r)*3/4-r}function kk(t,e,n){return(e+n)*3/4-n}function Ak(t){var e,n=sy(t),r=n[0],o=n[1],s=new wk(kk(t,r,o)),a=0,u=o>0?r-4:r,l;for(l=0;l<u;l+=4)e=Ot[t.charCodeAt(l)]<<18|Ot[t.charCodeAt(l+1)]<<12|Ot[t.charCodeAt(l+2)]<<6|Ot[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Ot[t.charCodeAt(l)]<<2|Ot[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Ot[t.charCodeAt(l)]<<10|Ot[t.charCodeAt(l+1)]<<4|Ot[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function Sk(t){return nn[t>>18&63]+nn[t>>12&63]+nn[t>>6&63]+nn[t&63]}function vk(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(Sk(r));return o.join("")}function Tk(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,u=n-r;a<u;a+=s)o.push(vk(t,a,a+s>u?u:a+s));return r===1?(e=t[n-1],o.push(nn[e>>2]+nn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(nn[e>>10]+nn[e>>4&63]+nn[e<<2&63]+"=")),o.join("")}});var wl=X(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.fromArrayBufferToHex=Dk;function Dk(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var ay=X(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.BrowserCrypto=void 0;var fo=iy(),Rk=wl(),El=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 n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return fo.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),fo.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=fo.toByteArray(t.padBase64(r)),u=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,u,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return fo.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=fo.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return fo.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,Rk.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};pa.BrowserCrypto=El});var uy=X(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.NodeCrypto=void 0;var ho=require("crypto"),kl=class{async sha256DigestBase64(e){return ho.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ho.randomBytes(e).toString("base64")}async verify(e,n,r){let o=ho.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=ho.createSign("RSA-SHA256");return r.update(n),r.end(),r.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 ho.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:Ok(e);return xk(ho.createHmac("sha256",r).update(n).digest())}};ma.NodeCrypto=kl;function xk(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Ok(t){return Buffer.from(t)}});var us=X(xn=>{"use strict";var Pk=xn&&xn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Fk=xn&&xn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pk(e,t,n)};Object.defineProperty(xn,"__esModule",{value:!0});xn.createCrypto=Bk;xn.hasBrowserCrypto=cy;var Ik=ay(),Nk=uy();Fk(wl(),xn);function Bk(){return cy()?new Ik.BrowserCrypto:new Nk.NodeCrypto}function cy(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var po=X((Al,dy)=>{var ga=require("buffer"),rn=ga.Buffer;function ly(t,e){for(var n in t)e[n]=t[n]}rn.from&&rn.alloc&&rn.allocUnsafe&&rn.allocUnsafeSlow?dy.exports=ga:(ly(ga,Al),Al.Buffer=vr);function vr(t,e,n){return rn(t,e,n)}vr.prototype=Object.create(rn.prototype);ly(rn,vr);vr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return rn(t,e,n)};vr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=rn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};vr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rn(t)};vr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ga.SlowBuffer(t)}});var hy=X((pO,fy)=>{"use strict";function Sl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Mk={ES256:Sl(256),ES384:Sl(384),ES512:Sl(521)};function Lk(t){var e=Mk[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}fy.exports=Lk});var vl=X((mO,by)=>{"use strict";var ya=po().Buffer,my=hy(),_a=128,gy=0,jk=32,Uk=16,$k=2,yy=Uk|jk|gy<<6,ba=$k|gy<<6;function qk(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function _y(t){if(ya.isBuffer(t))return t;if(typeof t=="string")return ya.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function zk(t,e){t=_y(t);var n=my(e),r=n+1,o=t.length,s=0;if(t[s++]!==yy)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(_a|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==ba)throw new Error('Could not find expected "int" for "r"');var u=t[s++];if(o-s-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(o-s-2)+'" available');if(r<u)throw new Error('"r" specified length of "'+u+'", max of "'+r+'" is acceptable');var l=s;if(s+=u,t[s++]!==ba)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(r<f)throw new Error('"s" specified length of "'+f+'", max of "'+r+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-u,m=n-f,b=ya.allocUnsafe(p+u+m+f);for(s=0;s<p;++s)b[s]=0;t.copy(b,s,l+Math.max(-p,0),l+u),s=n;for(var w=s;s<w+m;++s)b[s]=0;return t.copy(b,s,d+Math.max(-m,0),d+f),b=b.toString("base64"),b=qk(b),b}function py(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=_a;return o&&--r,r}function Hk(t,e){t=_y(t);var n=my(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=py(t,0,n),s=py(t,n,t.length),a=n-o,u=n-s,l=2+a+1+1+u,f=l<_a,d=ya.allocUnsafe((f?2:3)+l),p=0;return d[p++]=yy,f?d[p++]=l:(d[p++]=_a|1,d[p++]=l&255),d[p++]=ba,d[p++]=a,o<0?(d[p++]=0,p+=t.copy(d,p,0,n)):p+=t.copy(d,p,o,n),d[p++]=ba,d[p++]=u,s<0?(d[p++]=0,t.copy(d,p,n)):t.copy(d,p,n+s),d}by.exports={derToJose:zk,joseToDer:Hk}});var Jt=X(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.LRUCache=void 0;On.snakeToCamel=wy;On.originalOrCamelOptions=Vk;On.removeUndefinedValuesInObject=Kk;On.isValidFile=Yk;On.getWellKnownCertificateConfigFileLocation=Qk;var Wk=require("fs"),Gk=require("os"),Tl=require("path"),Jk="certificate_config.json",Cy="gcloud";function wy(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Vk(t){function e(n){let r=t||{};return r[n]??r[wy(n)]}return{get:e}}var Dl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};On.LRUCache=Dl;function Kk(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Yk(t){try{return(await Wk.promises.lstat(t)).isFile()}catch{return!1}}function Qk(){let t=process.env.CLOUDSDK_CONFIG||(Xk()?Tl.join(process.env.APPDATA||"",Cy):Tl.join(process.env.HOME||"",".config",Cy));return Tl.join(t,Jk)}function Xk(){return Gk.platform().startsWith("win")}});var Ey=X((yO,Zk)=>{Zk.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 Rl=X(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.USER_AGENT=Qn.PRODUCT_NAME=Qn.pkg=void 0;var ky=Ey();Qn.pkg=ky;var Ay="google-api-nodejs-client";Qn.PRODUCT_NAME=Ay;var eA=`${Ay}/${ky.version}`;Qn.USER_AGENT=eA});var Ct=X(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.AuthClient=Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Vt.DEFAULT_UNIVERSE=void 0;var tA=require("events"),xl=Xe(),nA=Jt(),rA=ml(),Ol=Rl();Vt.DEFAULT_UNIVERSE="googleapis.com";Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Pl=class t extends tA.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Vt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,nA.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Vt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new xl.Gaxios(e.transporterOptions),n.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 n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&xl.Gaxios.mergeHeaders(s,n.headers),r&&xl.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}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,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,rA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${Ol.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Ol.USER_AGENT}`):e.headers.set("User-Agent",Ol.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Vt.AuthClient=Pl});var Il=X(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.LoginTicket=void 0;var Fl=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}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()}}};Ca.LoginTicket=Fl});var Tr=X(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.OAuth2Client=on.ClientAuthentication=on.CertificateFormat=on.CodeChallengeMethod=void 0;var Sy=Xe(),oA=require("querystring"),sA=require("stream"),iA=vl(),vy=Jt(),Nl=us(),mo=Ct(),aA=Il(),Ty;(function(t){t.Plain="plain",t.S256="S256"})(Ty||(on.CodeChallengeMethod=Ty={}));var Pn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Pn||(on.CertificateFormat=Pn={}));var cs;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(cs||(on.ClientAuthentication=cs={}));var Bl=class t extends mo.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Pn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||cs.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()+"?"+oA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Nl.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={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===cs.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===cs.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,vy.removeUndefinedValuesInObject)(o)),headers:r};mo.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,vy.removeUndefinedValuesInObject)(r))};mo.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof Sy.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);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 r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(u){let l=u;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(mo.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),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,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=Sy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof sA.Readable,f=s===401||s===403;if(!n&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&f&&!l&&u){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=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()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Nl.hasBrowserCrypto)()?Pn.JWK:Pn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Pn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Pn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let f={...t.RETRY_CONFIG,url:o};mo.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),r=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=r?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let u={};switch(n){case Pn.PEM:u=r.data;break;case Pn.JWK:for(let f of r.data.keys)u[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};mo.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,Nl.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=u[0]+"."+u[1],f=u[2],d,p;try{d=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token envelope: ${u[0]}': ${C.message}`),C}if(!d)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token payload '${u[0]}`),C}if(!p)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let m=n[d.kid];if(d.alg==="ES256"&&(f=iA.joseToDer(f,"ES256").toString("base64")),!await a.verify(m,l,f))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 w=Number(p.iat);if(isNaN(w))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let _=w-t.CLOCK_SKEW_SECS_,A=y+t.CLOCK_SKEW_SECS_;if(g<_)throw new Error("Token used too early, "+g+" < "+_+": "+JSON.stringify(p));if(g>A)throw new Error("Token used too late, "+g+" > "+A+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let C=p.aud,v=!1;if(r.constructor===Array?v=r.indexOf(C)>-1:v=C===r,!v)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new aA.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}};on.OAuth2Client=Bl});var Ll=X(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.Compute=void 0;var uA=Xe(),Dy=as(),cA=Tr(),Ml=class extends cA.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`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await Dy.instance(o)}catch(o){throw o instanceof uA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await Dy.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.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:n.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))}};wa.Compute=Ml});var Ul=X(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.IdTokenClient=void 0;var lA=Tr(),jl=class extends lA.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 n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ea.IdTokenClient=jl});var $l=X(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.GCPEnv=void 0;go.clear=dA;go.getEnv=fA;var Ry=as(),sn;(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"})(sn||(go.GCPEnv=sn={}));var ls;function dA(){ls=void 0}async function fA(){return ls||(ls=hA(),ls)}async function hA(){let t=sn.NONE;return pA()?t=sn.APP_ENGINE:mA()?t=sn.CLOUD_FUNCTIONS:await bA()?await _A()?t=sn.KUBERNETES_ENGINE:gA()?t=sn.CLOUD_RUN:yA()?t=sn.CLOUD_RUN_JOBS:t=sn.COMPUTE_ENGINE:t=sn.NONE,t}function pA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function mA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function gA(){return!!process.env.K_CONFIGURATION}function yA(){return!!process.env.CLOUD_RUN_JOB}async function _A(){try{return await Ry.instance("attributes/cluster-name"),!0}catch{return!1}}async function bA(){return Ry.isAvailable()}});var ql=X((SO,xy)=>{var ka=po().Buffer,CA=require("stream"),wA=require("util");function Aa(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ka.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ka.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+")")}wA.inherits(Aa,CA);Aa.prototype.write=function(e){this.buffer=ka.concat([this.buffer,ka.from(e)]),this.emit("data",e)};Aa.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};xy.exports=Aa});var Py=X((vO,Oy)=>{"use strict";var ds=require("buffer").Buffer,zl=require("buffer").SlowBuffer;Oy.exports=Sa;function Sa(t,e){if(!ds.isBuffer(t)||!ds.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Sa.install=function(){ds.prototype.equal=zl.prototype.equal=function(e){return Sa(this,e)}};var EA=ds.prototype.equal,kA=zl.prototype.equal;Sa.restore=function(){ds.prototype.equal=EA,zl.prototype.equal=kA}});var Jl=X((TO,$y)=>{var _o=po().Buffer,Pt=require("crypto"),Iy=vl(),Fy=require("util"),AA=`"%s" is not a valid algorithm.
49
+ `+y+"}":"{"+g.join(",")+"}",r=y,C}}typeof Bg.stringify!="function"&&(Bg.stringify=function(f,d,h){var m;if(r="",o="",typeof h=="number")for(m=0;m<h;m+=1)o+=" ";else typeof h=="string"&&(o=h);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":f})})})()});var Ug=X((rO,jg)=>{var ca=null,VE=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,KE=/(?: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)/,YE=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 n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
+ `,r:"\r",t:" "},s,a=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},u=function(y){return y&&y!==r&&a("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var y,g="";for(r==="-"&&(g="-",u("-"));r>="0"&&r<="9";)g+=r,u();if(r===".")for(g+=".";u()&&r>="0"&&r<="9";)g+=r;if(r==="e"||r==="E")for(g+=r,u(),(r==="-"||r==="+")&&(g+=r,u());r>="0"&&r<="9";)g+=r,u();if(y=+g,!isFinite(y))a("Bad number");else return ca==null&&(ca=cl()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new ca(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new ca(y):y},f=function(){var y,g,_="",E;if(r==='"')for(var b=n;u();){if(r==='"')return n-1>b&&(_+=s.substring(b,n-1)),u(),_;if(r==="\\"){if(n-1>b&&(_+=s.substring(b,n-1)),u(),r==="u"){for(E=0,g=0;g<4&&(y=parseInt(u(),16),!!isFinite(y));g+=1)E=E*16+y;_+=String.fromCharCode(E)}else if(typeof o[r]=="string")_+=o[r];else break;b=n}}a("Bad string")},d=function(){for(;r&&r<=" ";)u()},h=function(){switch(r){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+r+"'")},m,C=function(){var y=[];if(r==="["){if(u("["),d(),r==="]")return u("]"),y;for(;r;){if(y.push(m()),d(),r==="]")return u("]"),y;u(","),d()}}a("Bad array")},w=function(){var y,g=Object.create(null);if(r==="{"){if(u("{"),d(),r==="}")return u("}"),g;for(;r;){if(y=f(),d(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&a('Duplicate key "'+y+'"'),VE.test(y)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():g[y]=m():KE.test(y)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():g[y]=m():g[y]=m(),d(),r==="}")return u("}"),g;u(","),d()}}a("Bad object")};return m=function(){switch(d(),r){case"{":return w();case"[":return C();case'"':return f();case"-":return l();default:return r>="0"&&r<="9"?l():h()}},function(y,g){var _;return s=y+"",n=0,r=" ",_=m(),d(),r&&a("Syntax error"),typeof g=="function"?(function E(b,S){var v,R,$=b[S];return $&&typeof $=="object"&&Object.keys($).forEach(function(H){R=E($,H),R!==void 0?$[H]=R:delete $[H]}),g.call(b,S,$)})({"":_},""):_}};jg.exports=YE});var zg=X((oO,la)=>{var $g=Lg().stringify,qg=Ug();la.exports=function(t){return{parse:qg(t),stringify:$g}};la.exports.parse=qg();la.exports.stringify=$g});var ll=X(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.GCE_LINUX_BIOS_PATHS=void 0;Wt.isGoogleCloudServerless=Gg;Wt.isGoogleComputeEngineLinux=Jg;Wt.isGoogleComputeEngineMACAddress=Vg;Wt.isGoogleComputeEngine=Kg;Wt.detectGCPResidency=XE;var Hg=require("fs"),Wg=require("os");Wt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var QE=/^42:01/;function Gg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Jg(){if((0,Wg.platform)()!=="linux")return!1;try{(0,Hg.statSync)(Wt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Hg.readFileSync)(Wt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Vg(){let t=(0,Wg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(QE.test(n))return!0}return!1}function Kg(){return Jg()||Vg()}function XE(){return Gg()||Kg()}});var Yg=X(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.Colours=void 0;var nt=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="")}};da.Colours=nt;nt.enabled=!1;nt.reset="";nt.bright="";nt.dim="";nt.red="";nt.green="";nt.yellow="";nt.blue="";nt.magenta="";nt.cyan="";nt.white="";nt.grey="";nt.refresh()});var ey=X(De=>{"use strict";var ZE=De&&De.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ek=De&&De.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Qg=De&&De.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&ZE(n,e,r[o]);return ek(n,e),n}})();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=fl;De.getDebugBackend=nk;De.getStructuredBackend=rk;De.setBackend=ok;De.log=Zg;var tk=require("events"),os=Qg(require("process")),Xg=Qg(require("util")),bt=Yg(),Gt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Gt||(De.LogSeverity=Gt={}));var ss=class extends tk.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Gt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Gt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Gt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Gt.ERROR,...r),this.func.sublog=r=>Zg(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};De.AdhocDebugLogger=ss;De.placeholder=new ss("",()=>{}).func;var lo=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=os.env[De.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};De.DebugLogBackendBase=lo;var dl=class extends lo{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${bt.Colours.green}${e}${bt.Colours.reset}`,a=`${bt.Colours.yellow}${os.pid}${bt.Colours.reset}`,u;switch(n.severity){case Gt.ERROR:u=`${bt.Colours.red}${n.severity}${bt.Colours.reset}`;break;case Gt.INFO:u=`${bt.Colours.magenta}${n.severity}${bt.Colours.reset}`;break;case Gt.WARNING:u=`${bt.Colours.yellow}${n.severity}${bt.Colours.reset}`;break;default:u=(o=n.severity)!==null&&o!==void 0?o:Gt.DEFAULT;break}let l=Xg.formatWithOptions({colors:bt.Colours.enabled},...r),f=Object.assign({},n);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",h=d?`${bt.Colours.grey}${d}${bt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,u,l,d?` ${h}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function fl(){return new dl}var hl=class extends lo{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=os.env.NODE_DEBUG)!==null&&e!==void 0?e:"";os.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function nk(t){return new hl(t)}var pl=class extends lo{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let u=(a=o.severity)!==null&&a!==void 0?a:Gt.INFO,l=Object.assign({severity:u,message:Xg.format(...s)},o),f=JSON.stringify(l);r?r(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function rk(t){return new pl(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var ml=new Map,Ct;function ok(t){Ct=t,ml.clear()}function Zg(t,e){if(!Ct&&!os.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=ml.get(t);if(n)return n.func;if(Ct===null)return De.placeholder;Ct===void 0&&(Ct=fl());let r=(()=>{let o;return new ss(t,(a,...u)=>{if(o!==Ct){if(Ct===null)return;Ct===void 0&&(Ct=fl()),o=Ct}Ct?.log(t,a,...u)})})();return ml.set(t,r),r.func}});var gl=X(Ar=>{"use strict";var sk=Ar&&Ar.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ik=Ar&&Ar.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&sk(e,t,n)};Object.defineProperty(Ar,"__esModule",{value:!0});ik(ey(),Ar)});var as=X(fe=>{"use strict";var ny=fe&&fe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ak=fe&&fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uk=fe&&fe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&ny(n,e,r[o]);return ak(n,e),n}})(),ck=fe&&fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ny(e,t,n)};Object.defineProperty(fe,"__esModule",{value:!0});fe.gcpResidencyCache=fe.METADATA_SERVER_DETECTION=fe.HEADERS=fe.HEADER_VALUE=fe.HEADER_NAME=fe.SECONDARY_HOST_ADDRESS=fe.HOST_ADDRESS=fe.BASE_PATH=void 0;fe.instance=mk;fe.project=gk;fe.universe=yk;fe.bulk=_k;fe.isAvailable=Ck;fe.resetIsAvailableCache=wk;fe.getGCPResidency=bl;fe.setGCPResidency=ry;fe.requestTimeout=oy;var yl=Xe(),lk=zg(),dk=ll(),fk=uk(gl());fe.BASE_PATH="/computeMetadata/v1";fe.HOST_ADDRESS="http://169.254.169.254";fe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";fe.HEADER_NAME="Metadata-Flavor";fe.HEADER_VALUE="Google";fe.HEADERS=Object.freeze({[fe.HEADER_NAME]:fe.HEADER_VALUE});var ty=fk.log("gcp-metadata");fe.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 _l(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||fe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(fe.BASE_PATH,t).href}function hk(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function is(t,e={},n=3,r=!1){let o=new Headers(fe.HEADERS),s="",a={};if(typeof t=="object"){let h=t;new Headers(h.headers).forEach((m,C)=>o.set(C,m)),s=h.metadataKey,a=h.params||a,n=h.noResponseRetries||n,r=h.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(hk(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((h,m)=>o.set(m,h)),a=e.params||a);let u=r?pk:yl.request,l={url:`${_l()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:oy()};ty.info("instance request %j",l);let f=await u(l);ty.info("instance metadata is %s",f.data);let d=f.headers.get(fe.HEADER_NAME);if(d!==fe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${fe.HEADER_NAME} header. Expected '${fe.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return lk.parse(f.data)}catch{}return f.data}async function pk(t){let e={...t,url:t.url?.toString().replace(_l(),_l(fe.SECONDARY_HOST_ADDRESS))},n=(0,yl.request)(t),r=(0,yl.request)(e);return Promise.any([n,r])}function mk(t){return is("instance",t)}function gk(t){return is("project",t)}function yk(t){return is("universe",t)}async function _k(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await is(n),o=n.metadataKey;e[o]=r})())),e}function bk(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var fa;async function Ck(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in fe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(fe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return bl();case"ping-only":}}try{return fa===void 0&&(fa=is("instance",void 0,bk(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await fa,!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 n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function wk(){fa=void 0}fe.gcpResidencyCache=null;function bl(){return fe.gcpResidencyCache===null&&ry(),fe.gcpResidencyCache}function ry(t=null){fe.gcpResidencyCache=t!==null?t:(0,dk.detectGCPResidency)()}function oy(){return bl()?0:3e3}ck(ll(),fe)});var ay=X(ha=>{"use strict";ha.byteLength=kk;ha.toByteArray=Sk;ha.fromByteArray=Dk;var nn=[],Pt=[],Ek=typeof Uint8Array<"u"?Uint8Array:Array,Cl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Sr=0,sy=Cl.length;Sr<sy;++Sr)nn[Sr]=Cl[Sr],Pt[Cl.charCodeAt(Sr)]=Sr;var Sr,sy;Pt[45]=62;Pt[95]=63;function iy(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function kk(t){var e=iy(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Ak(t,e,n){return(e+n)*3/4-n}function Sk(t){var e,n=iy(t),r=n[0],o=n[1],s=new Ek(Ak(t,r,o)),a=0,u=o>0?r-4:r,l;for(l=0;l<u;l+=4)e=Pt[t.charCodeAt(l)]<<18|Pt[t.charCodeAt(l+1)]<<12|Pt[t.charCodeAt(l+2)]<<6|Pt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Pt[t.charCodeAt(l)]<<2|Pt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Pt[t.charCodeAt(l)]<<10|Pt[t.charCodeAt(l+1)]<<4|Pt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function Tk(t){return nn[t>>18&63]+nn[t>>12&63]+nn[t>>6&63]+nn[t&63]}function vk(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(Tk(r));return o.join("")}function Dk(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,u=n-r;a<u;a+=s)o.push(vk(t,a,a+s>u?u:a+s));return r===1?(e=t[n-1],o.push(nn[e>>2]+nn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(nn[e>>10]+nn[e>>4&63]+nn[e<<2&63]+"=")),o.join("")}});var El=X(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.fromArrayBufferToHex=Rk;function Rk(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var uy=X(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.BrowserCrypto=void 0;var fo=ay(),xk=El(),kl=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 n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return fo.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),fo.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=fo.toByteArray(t.padBase64(r)),u=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,u,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return fo.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=fo.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return fo.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,xk.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};pa.BrowserCrypto=kl});var cy=X(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.NodeCrypto=void 0;var ho=require("crypto"),Al=class{async sha256DigestBase64(e){return ho.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ho.randomBytes(e).toString("base64")}async verify(e,n,r){let o=ho.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=ho.createSign("RSA-SHA256");return r.update(n),r.end(),r.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 ho.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:Pk(e);return Ok(ho.createHmac("sha256",r).update(n).digest())}};ma.NodeCrypto=Al;function Ok(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Pk(t){return Buffer.from(t)}});var us=X(xn=>{"use strict";var Fk=xn&&xn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ik=xn&&xn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Fk(e,t,n)};Object.defineProperty(xn,"__esModule",{value:!0});xn.createCrypto=Mk;xn.hasBrowserCrypto=ly;var Nk=uy(),Bk=cy();Ik(El(),xn);function Mk(){return ly()?new Nk.BrowserCrypto:new Bk.NodeCrypto}function ly(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var po=X((Sl,fy)=>{var ga=require("buffer"),rn=ga.Buffer;function dy(t,e){for(var n in t)e[n]=t[n]}rn.from&&rn.alloc&&rn.allocUnsafe&&rn.allocUnsafeSlow?fy.exports=ga:(dy(ga,Sl),Sl.Buffer=Tr);function Tr(t,e,n){return rn(t,e,n)}Tr.prototype=Object.create(rn.prototype);dy(rn,Tr);Tr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return rn(t,e,n)};Tr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=rn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Tr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rn(t)};Tr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ga.SlowBuffer(t)}});var py=X((mO,hy)=>{"use strict";function Tl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Lk={ES256:Tl(256),ES384:Tl(384),ES512:Tl(521)};function jk(t){var e=Lk[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}hy.exports=jk});var vl=X((gO,Cy)=>{"use strict";var ya=po().Buffer,gy=py(),_a=128,yy=0,Uk=32,$k=16,qk=2,_y=$k|Uk|yy<<6,ba=qk|yy<<6;function zk(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function by(t){if(ya.isBuffer(t))return t;if(typeof t=="string")return ya.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Hk(t,e){t=by(t);var n=gy(e),r=n+1,o=t.length,s=0;if(t[s++]!==_y)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(_a|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==ba)throw new Error('Could not find expected "int" for "r"');var u=t[s++];if(o-s-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(o-s-2)+'" available');if(r<u)throw new Error('"r" specified length of "'+u+'", max of "'+r+'" is acceptable');var l=s;if(s+=u,t[s++]!==ba)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(r<f)throw new Error('"s" specified length of "'+f+'", max of "'+r+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var h=n-u,m=n-f,C=ya.allocUnsafe(h+u+m+f);for(s=0;s<h;++s)C[s]=0;t.copy(C,s,l+Math.max(-h,0),l+u),s=n;for(var w=s;s<w+m;++s)C[s]=0;return t.copy(C,s,d+Math.max(-m,0),d+f),C=C.toString("base64"),C=zk(C),C}function my(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=_a;return o&&--r,r}function Wk(t,e){t=by(t);var n=gy(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=my(t,0,n),s=my(t,n,t.length),a=n-o,u=n-s,l=2+a+1+1+u,f=l<_a,d=ya.allocUnsafe((f?2:3)+l),h=0;return d[h++]=_y,f?d[h++]=l:(d[h++]=_a|1,d[h++]=l&255),d[h++]=ba,d[h++]=a,o<0?(d[h++]=0,h+=t.copy(d,h,0,n)):h+=t.copy(d,h,o,n),d[h++]=ba,d[h++]=u,s<0?(d[h++]=0,t.copy(d,h,n)):t.copy(d,h,n+s),d}Cy.exports={derToJose:Hk,joseToDer:Wk}});var Jt=X(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.LRUCache=void 0;On.snakeToCamel=Ey;On.originalOrCamelOptions=Kk;On.removeUndefinedValuesInObject=Yk;On.isValidFile=Qk;On.getWellKnownCertificateConfigFileLocation=Xk;var Gk=require("fs"),Jk=require("os"),Dl=require("path"),Vk="certificate_config.json",wy="gcloud";function Ey(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Kk(t){function e(n){let r=t||{};return r[n]??r[Ey(n)]}return{get:e}}var Rl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};On.LRUCache=Rl;function Yk(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Qk(t){try{return(await Gk.promises.lstat(t)).isFile()}catch{return!1}}function Xk(){let t=process.env.CLOUDSDK_CONFIG||(Zk()?Dl.join(process.env.APPDATA||"",wy):Dl.join(process.env.HOME||"",".config",wy));return Dl.join(t,Vk)}function Zk(){return Jk.platform().startsWith("win")}});var ky=X((_O,eA)=>{eA.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 xl=X(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.USER_AGENT=Qn.PRODUCT_NAME=Qn.pkg=void 0;var Ay=ky();Qn.pkg=Ay;var Sy="google-api-nodejs-client";Qn.PRODUCT_NAME=Sy;var tA=`${Sy}/${Ay.version}`;Qn.USER_AGENT=tA});var wt=X(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.AuthClient=Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Vt.DEFAULT_UNIVERSE=void 0;var nA=require("events"),Ol=Xe(),rA=Jt(),oA=gl(),Pl=xl();Vt.DEFAULT_UNIVERSE="googleapis.com";Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Fl=class t extends nA.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Vt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Vt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,rA.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Vt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Ol.Gaxios(e.transporterOptions),n.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 n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Ol.Gaxios.mergeHeaders(s,n.headers),r&&Ol.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}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,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,oA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${Pl.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Pl.USER_AGENT}`):e.headers.set("User-Agent",Pl.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Vt.AuthClient=Fl});var Nl=X(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.LoginTicket=void 0;var Il=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}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()}}};Ca.LoginTicket=Il});var vr=X(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.OAuth2Client=on.ClientAuthentication=on.CertificateFormat=on.CodeChallengeMethod=void 0;var Ty=Xe(),sA=require("querystring"),iA=require("stream"),aA=vl(),vy=Jt(),Bl=us(),mo=wt(),uA=Nl(),Dy;(function(t){t.Plain="plain",t.S256="S256"})(Dy||(on.CodeChallengeMethod=Dy={}));var Pn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Pn||(on.CertificateFormat=Pn={}));var cs;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(cs||(on.ClientAuthentication=cs={}));var Ml=class t extends mo.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Pn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||cs.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()+"?"+sA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Bl.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={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===cs.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===cs.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,vy.removeUndefinedValuesInObject)(o)),headers:r};mo.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,vy.removeUndefinedValuesInObject)(r))};mo.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof Ty.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);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 r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(u){let l=u;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(mo.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),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,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=Ty.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof iA.Readable,f=s===401||s===403;if(!n&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&f&&!l&&u){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=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()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Bl.hasBrowserCrypto)()?Pn.JWK:Pn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Pn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Pn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let f={...t.RETRY_CONFIG,url:o};mo.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),r=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=r?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let u={};switch(n){case Pn.PEM:u=r.data;break;case Pn.JWK:for(let f of r.data.keys)u[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};mo.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,Bl.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=u[0]+"."+u[1],f=u[2],d,h;try{d=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${u[0]}': ${b.message}`),b}if(!d)throw new Error("Can't parse token envelope: "+u[0]);try{h=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${u[0]}`),b}if(!h)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let m=n[d.kid];if(d.alg==="ES256"&&(f=aA.joseToDer(f,"ES256").toString("base64")),!await a.verify(m,l,f))throw new Error("Invalid token signature: "+e);if(!h.iat)throw new Error("No issue time in token: "+JSON.stringify(h));if(!h.exp)throw new Error("No expiration time in token: "+JSON.stringify(h));let w=Number(h.iat);if(isNaN(w))throw new Error("iat field using invalid format");let y=Number(h.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(h));let _=w-t.CLOCK_SKEW_SECS_,E=y+t.CLOCK_SKEW_SECS_;if(g<_)throw new Error("Token used too early, "+g+" < "+_+": "+JSON.stringify(h));if(g>E)throw new Error("Token used too late, "+g+" > "+E+": "+JSON.stringify(h));if(o&&o.indexOf(h.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+h.iss);if(typeof r<"u"&&r!==null){let b=h.aud,S=!1;if(r.constructor===Array?S=r.indexOf(b)>-1:S=b===r,!S)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new uA.LoginTicket(d,h)}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}};on.OAuth2Client=Ml});var jl=X(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.Compute=void 0;var cA=Xe(),Ry=as(),lA=vr(),Ll=class extends lA.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`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await Ry.instance(o)}catch(o){throw o instanceof cA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await Ry.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.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:n.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))}};wa.Compute=Ll});var $l=X(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.IdTokenClient=void 0;var dA=vr(),Ul=class extends dA.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 n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ea.IdTokenClient=Ul});var ql=X(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.GCPEnv=void 0;go.clear=fA;go.getEnv=hA;var xy=as(),sn;(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"})(sn||(go.GCPEnv=sn={}));var ls;function fA(){ls=void 0}async function hA(){return ls||(ls=pA(),ls)}async function pA(){let t=sn.NONE;return mA()?t=sn.APP_ENGINE:gA()?t=sn.CLOUD_FUNCTIONS:await CA()?await bA()?t=sn.KUBERNETES_ENGINE:yA()?t=sn.CLOUD_RUN:_A()?t=sn.CLOUD_RUN_JOBS:t=sn.COMPUTE_ENGINE:t=sn.NONE,t}function mA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function gA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function yA(){return!!process.env.K_CONFIGURATION}function _A(){return!!process.env.CLOUD_RUN_JOB}async function bA(){try{return await xy.instance("attributes/cluster-name"),!0}catch{return!1}}async function CA(){return xy.isAvailable()}});var zl=X((TO,Oy)=>{var ka=po().Buffer,wA=require("stream"),EA=require("util");function Aa(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ka.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ka.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+")")}EA.inherits(Aa,wA);Aa.prototype.write=function(e){this.buffer=ka.concat([this.buffer,ka.from(e)]),this.emit("data",e)};Aa.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Oy.exports=Aa});var Fy=X((vO,Py)=>{"use strict";var ds=require("buffer").Buffer,Hl=require("buffer").SlowBuffer;Py.exports=Sa;function Sa(t,e){if(!ds.isBuffer(t)||!ds.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Sa.install=function(){ds.prototype.equal=Hl.prototype.equal=function(e){return Sa(this,e)}};var kA=ds.prototype.equal,AA=Hl.prototype.equal;Sa.restore=function(){ds.prototype.equal=kA,Hl.prototype.equal=AA}});var Vl=X((DO,qy)=>{var _o=po().Buffer,Ft=require("crypto"),Ny=vl(),Iy=require("util"),SA=`"%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".`,fs="secret must be a string or buffer",yo="key must be a string or a buffer",SA="key must be a string, a buffer or an object",Wl=typeof Pt.createPublicKey=="function";Wl&&(yo+=" or a KeyObject",fs+="or a KeyObject");function Ny(t){if(!_o.isBuffer(t)&&typeof t!="string"&&(!Wl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Kt(yo)}function By(t){if(!_o.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Kt(SA)}function vA(t){if(!_o.isBuffer(t)){if(typeof t=="string")return t;if(!Wl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Kt(fs)}}function Gl(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function My(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Kt(t){var e=[].slice.call(arguments,1),n=Fy.format.bind(Fy,t).apply(null,e);return new TypeError(n)}function TA(t){return _o.isBuffer(t)||typeof t=="string"}function hs(t){return TA(t)||(t=JSON.stringify(t)),t}function Ly(t){return function(n,r){vA(r),n=hs(n);var o=Pt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Gl(s)}}var Hl,DA="timingSafeEqual"in Pt?function(e,n){return e.byteLength!==n.byteLength?!1:Pt.timingSafeEqual(e,n)}:function(e,n){return Hl||(Hl=Py()),Hl(e,n)};function RA(t){return function(n,r,o){var s=Ly(t)(n,o);return DA(_o.from(r),_o.from(s))}}function jy(t){return function(n,r){By(r),n=hs(n);var o=Pt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Gl(s)}}function Uy(t){return function(n,r,o){Ny(o),n=hs(n),r=My(r);var s=Pt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function xA(t){return function(n,r){By(r),n=hs(n);var o=Pt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Pt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Pt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Gl(s)}}function OA(t){return function(n,r,o){Ny(o),n=hs(n),r=My(r);var s=Pt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Pt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Pt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function PA(t){var e=jy(t);return function(){var r=e.apply(null,arguments);return r=Iy.derToJose(r,"ES"+t),r}}function FA(t){var e=Uy(t);return function(r,o,s){o=Iy.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function IA(){return function(){return""}}function NA(){return function(e,n){return n===""}}$y.exports=function(e){var n={hs:Ly,rs:jy,ps:xA,es:PA,none:IA},r={hs:RA,rs:Uy,ps:OA,es:FA,none:NA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Kt(AA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Vl=X((DO,qy)=>{var BA=require("buffer").Buffer;qy.exports=function(e){return typeof e=="string"?e:typeof e=="number"||BA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Vy=X((RO,Jy)=>{var MA=po().Buffer,zy=ql(),LA=Jl(),jA=require("stream"),Hy=Vl(),Kl=require("util");function Wy(t,e){return MA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function UA(t,e,n){n=n||"utf8";var r=Wy(Hy(t),"binary"),o=Wy(Hy(e),n);return Kl.format("%s.%s",r,o)}function Gy(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=LA(e.alg),a=UA(e,n,o),u=s.sign(a,r);return Kl.format("%s.%s",a,u)}function va(t){var e=t.secret||t.privateKey||t.key,n=new zy(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new zy(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))}Kl.inherits(va,jA);va.prototype.sign=function(){try{var e=Gy({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(n){this.readable=!1,this.emit("error",n),this.emit("close")}};va.sign=Gy;Jy.exports=va});var o0=X((xO,r0)=>{var Yy=po().Buffer,Ky=ql(),$A=Jl(),qA=require("stream"),Qy=Vl(),zA=require("util"),HA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function WA(t){return Object.prototype.toString.call(t)==="[object Object]"}function GA(t){if(WA(t))return t;try{return JSON.parse(t)}catch{return}}function Xy(t){var e=t.split(".",1)[0];return GA(Yy.from(e,"base64").toString("binary"))}function JA(t){return t.split(".",2).join(".")}function Zy(t){return t.split(".")[2]}function VA(t,e){e=e||"utf8";var n=t.split(".")[1];return Yy.from(n,"base64").toString(e)}function e0(t){return HA.test(t)&&!!Xy(t)}function t0(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Qy(t);var o=Zy(t),s=JA(t),a=$A(e);return a.verify(s,o,n)}function n0(t,e){if(e=e||{},t=Qy(t),!e0(t))return null;var n=Xy(t);if(!n)return null;var r=VA(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Zy(t)}}function bo(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new Ky(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Ky(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))}zA.inherits(bo,qA);bo.prototype.verify=function(){try{var e=t0(this.signature.buffer,this.algorithm,this.key.buffer),n=n0(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};bo.decode=n0;bo.isValid=e0;bo.verify=t0;r0.exports=bo});var Yl=X(Xn=>{var s0=Vy(),Ta=o0(),KA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Xn.ALGORITHMS=KA;Xn.sign=s0.sign;Xn.verify=Ta.verify;Xn.decode=Ta.decode;Xn.isValid=Ta.isValid;Xn.createSign=function(e){return new s0(e)};Xn.createVerify=function(e){return new Ta(e)}});var C0=X(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.GoogleToken=void 0;var i0=Da(require("fs")),YA=Xe(),QA=Da(Yl()),XA=Da(require("path")),ZA=require("util");function Da(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(Da=function(s,a){if(!a&&s&&s.__esModule)return s;var u,l,f={__proto__:null,default:s};if(s===null||Fn(s)!="object"&&typeof s!="function")return f;if(u=a?r:n){if(u.has(s))return u.get(s);u.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(u=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?u(f,d,l):f[d]=s[d]);return f})(t,e)}function Fn(t){"@babel/helpers - typeof";return Fn=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},Fn(t)}function eS(t,e){m0(t,e),e.add(t)}function tS(t,e,n){m0(t,e),e.set(t,n)}function m0(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function a0(t,e,n){return t.set(Yt(t,e),n),n}function u0(t,e){return t.get(Yt(t,e))}function Yt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function c0(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,_0(r.key),r)}}function g0(t,e,n){return e&&c0(t.prototype,e),n&&c0(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function y0(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function nS(t,e,n){return e=ys(e),rS(t,nd()?Reflect.construct(e,n||[],ys(t).constructor):e.apply(t,n))}function rS(t,e){if(e&&(Fn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oS(t)}function oS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function sS(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&&gs(t,e)}function Ql(t){var e=typeof Map=="function"?new Map:void 0;return Ql=function(r){if(r===null||!aS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return iS(r,arguments,ys(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),gs(o,r)},Ql(t)}function iS(t,e,n){if(nd())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&gs(o,n.prototype),o}function nd(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(nd=function(){return!!t})()}function aS(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function gs(t,e){return gs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},gs(t,e)}function ys(t){return ys=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ys(t)}function wt(t,e,n){return(e=_0(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _0(t){var e=uS(t,"string");return Fn(e)=="symbol"?e:e+""}function uS(t,e){if(Fn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Fn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function kt(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(b,w,y,g){var _=w&&w.prototype instanceof u?w:u,A=Object.create(_.prototype);return Et(A,"_invoke",(function(C,v,T){var R,$,G,P=0,K=T||[],z=!1,Y={p:0,n:0,v:t,a:Q,f:Q.bind(t,4),d:function(oe,se){return R=oe,$=0,G=t,Y.n=se,a}};function Q(ee,oe){for($=ee,G=oe,e=0;!z&&P&&!se&&e<K.length;e++){var se,he=K[e],J=Y.p,Z=he[2];ee>3?(se=Z===oe)&&(G=he[($=he[4])?5:($=3,3)],he[4]=he[5]=t):he[0]<=J&&((se=ee<2&&J<he[1])?($=0,Y.v=oe,Y.n=he[1]):J<Z&&(se=ee<3||he[0]>oe||oe>Z)&&(he[4]=ee,he[5]=oe,Y.n=Z,$=0))}if(se||ee>1)return a;throw z=!0,oe}return function(ee,oe,se){if(P>1)throw TypeError("Generator is already running");for(z&&oe===1&&Q(oe,se),$=oe,G=se;(e=$<2?t:G)||!z;){R||($?$<3?($>1&&(Y.n=-1),Q($,G)):Y.n=G:Y.v=G);try{if(P=2,R){if($||(ee="next"),e=R[ee]){if(!(e=e.call(R,G)))throw TypeError("iterator result is not an object");if(!e.done)return e;G=e.value,$<2&&($=0)}else $===1&&(e=R.return)&&e.call(R),$<2&&(G=TypeError("The iterator does not provide a '"+ee+"' method"),$=1);R=t}else if((e=(z=Y.n<0)?G:C.call(v,Y))!==a)break}catch(he){R=t,$=1,G=he}finally{P=1}}return{value:e,done:z}}})(b,y,g),!0),A}var a={};function u(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][r]?e(e([][r]())):(Et(e={},r,function(){return this}),e),p=f.prototype=u.prototype=Object.create(d);function m(b){return Object.setPrototypeOf?Object.setPrototypeOf(b,f):(b.__proto__=f,Et(b,o,"GeneratorFunction")),b.prototype=Object.create(p),b}return l.prototype=f,Et(p,"constructor",f),Et(f,"constructor",l),l.displayName="GeneratorFunction",Et(f,o,"GeneratorFunction"),Et(p),Et(p,o,"Generator"),Et(p,r,function(){return this}),Et(p,"toString",function(){return"[object Generator]"}),(kt=function(){return{w:s,m}})()}function Et(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}Et=function(a,u,l,f){if(u)o?o(a,u,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[u]=l;else{var d=function(m,b){Et(a,m,function(w){return this._invoke(m,b,w)})};d("next",0),d("throw",1),d("return",2)}},Et(t,e,n,r)}function l0(t,e,n,r,o,s,a){try{var u=t[s](a),l=u.value}catch(f){return void n(f)}u.done?e(l):Promise.resolve(l).then(r,o)}function Co(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){l0(s,r,o,a,u,"next",l)}function u(l){l0(s,r,o,a,u,"throw",l)}a(void 0)})}}var d0=i0.readFile?(0,ZA.promisify)(i0.readFile):Co(kt().m(function t(){return kt().w(function(e){for(;;)switch(e.n){case 0:throw new ms("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),f0="https://oauth2.googleapis.com/token",cS="https://oauth2.googleapis.com/revoke?token=",ms=(function(t){function e(n,r){var o;return y0(this,e),o=nS(this,e,[n]),wt(o,"code",void 0),o.code=r,o}return sS(e,t),g0(e)})(Ql(Error)),ps=new WeakMap,an=new WeakSet,PO=Ra.GoogleToken=(function(){function t(e){y0(this,t),eS(this,an),wt(this,"expiresAt",void 0),wt(this,"key",void 0),wt(this,"keyFile",void 0),wt(this,"iss",void 0),wt(this,"sub",void 0),wt(this,"scope",void 0),wt(this,"rawToken",void 0),wt(this,"tokenExpires",void 0),wt(this,"email",void 0),wt(this,"additionalClaims",void 0),wt(this,"eagerRefreshThresholdMillis",void 0),wt(this,"transporter",{request:function(r){return(0,YA.request)(r)}}),tS(this,ps,void 0),Yt(an,this,b0).call(this,e)}return g0(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 n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Fn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Yt(an,this,h0).call(this,r).then(function(s){return o(null,s)},n);return}return Yt(an,this,h0).call(this,r)}},{key:"getCredentials",value:(function(){var e=Co(kt().m(function r(o){var s,a,u,l,f,d,p;return kt().w(function(m){for(;;)switch(m.n){case 0:s=XA.extname(o),p=s,m.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return m.n=2,d0(o,"utf8");case 2:if(a=m.v,u=JSON.parse(a),l=u.private_key,f=u.client_email,!(!l||!f)){m.n=3;break}throw new ms("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:f});case 4:return m.n=5,d0(o,"utf8");case 5:return d=m.v,m.a(2,{privateKey:d});case 6:throw new ms("*.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 ms("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Yt(an,this,p0).call(this).then(function(){return n()},n);return}return Yt(an,this,p0).call(this)}}])})();function h0(t){return Xl.apply(this,arguments)}function Xl(){return Xl=Co(kt().m(function t(e){return kt().w(function(n){for(;;)switch(n.n){case 0:if(!(u0(ps,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,u0(ps,this));case 1:return n.p=1,n.n=2,a0(ps,this,Yt(an,this,lS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,a0(ps,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),Xl.apply(this,arguments)}function lS(t){return Zl.apply(this,arguments)}function Zl(){return Zl=Co(kt().m(function t(e){var n;return kt().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Yt(an,this,dS).call(this);case 4:return r.a(2,Yt(an,this,fS).call(this))}},t,this)})),Zl.apply(this,arguments)}function dS(){if(!this.iss)throw new ms("email is required.","MISSING_CREDENTIALS")}function p0(){return ed.apply(this,arguments)}function ed(){return ed=Co(kt().m(function t(){var e;return kt().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=cS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Yt(an,this,b0).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),ed.apply(this,arguments)}function b0(){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,Fn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function fS(){return td.apply(this,arguments)}function td(){return td=Co(kt().m(function t(){var e,n,r,o,s,a,u,l,f,d;return kt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:f0,exp:e+3600,iat:e,sub:this.sub},n),o=QA.sign({header:{alg:"RS256"},payload:r,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:f0,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=p.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.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&&(a=d.response)!==null&&a!==void 0&&a.data?(u=d.response)===null||u===void 0?void 0:u.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),td.apply(this,arguments)}});var od=X(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.JWTAccess=void 0;var hS=Yl(),pS=Jt(),w0={alg:"RS256",typ:"JWT"},rd=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new pS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let u=Math.floor(Date.now()/1e3),l=t.getExpirationTime(u),f;if(Array.isArray(r)&&(r=r.join(" ")),r?f={iss:this.email,sub:this.email,scope:r,exp:l,iat:u}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:u},n){for(let w in f)if(n[w])throw new Error(`The '${w}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...w0,kid:this.keyId}:w0,p=Object.assign(f,n),m=hS.sign({header:d,payload:p,secret:this.key}),b=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:b}),b}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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};xa.JWTAccess=rd});var id=X(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.JWT=void 0;var E0=C0(),mS=od(),gS=Tr(),Oa=Ct(),sd=class t extends gS.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 n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Oa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Oa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Oa.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new mS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Oa.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new E0.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 n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.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(n=>e(null,n),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(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new E0.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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}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 n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Pa.JWT=sd});var ud=X(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.UserRefreshClient=wo.USER_REFRESH_ACCOUNT_TYPE=void 0;var yS=Tr(),_S=Ct();wo.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ad=class t extends yS.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...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 _S.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};wo.UserRefreshClient=ad});var ld=X(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.Impersonated=Eo.IMPERSONATED_ACCOUNT_TYPE=void 0;var k0=Tr(),bS=Xe(),CS=Jt();Eo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var cd=class t extends k0.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 k0.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,CS.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 n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof bS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Eo.Impersonated=cd});var fd=X(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.OAuthClientAuthHandler=void 0;_s.getErrorFromOAuthErrorResponse=kS;var ko=Xe(),wS=us(),ES=["PUT","POST","PATCH"],dd=class{#e=(0,wS.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ko.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ko.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=ko.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=ko.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ko.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);ko.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!ES.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.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(`${o} 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"]}}}};_s.OAuthClientAuthHandler=dd;function kS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var Ia=X(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.StsCredentials=void 0;var AS=Xe(),SS=Ct(),A0=fd(),vS=Jt(),hd=class t extends A0.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={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:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,vS.removeUndefinedValuesInObject)(o))};SS.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),u=a.data;return u.res=a,u}catch(a){throw a instanceof AS.GaxiosError&&a.response?(0,A0.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Fa.StsCredentials=hd});var Zn=X(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.BaseExternalAccountClient=Ft.CLOUD_RESOURCE_MANAGER=Ft.EXTERNAL_ACCOUNT_TYPE=Ft.EXPIRATION_TIME_OFFSET=void 0;var TS=Xe(),DS=require("stream"),pd=Ct(),RS=Ia(),S0=Jt(),xS=Rl(),OS="urn:ietf:params:oauth:grant-type:token-exchange",PS="urn:ietf:params:oauth:token-type:access_token",md="https://www.googleapis.com/auth/cloud-platform",FS=3600;Ft.EXPIRATION_TIME_OFFSET=300*1e3;Ft.EXTERNAL_ACCOUNT_TYPE="external_account";Ft.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var IS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",NS="https://sts.{universeDomain}/v1/token",gd=class t extends pd.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,S0.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Ft.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Ft.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??NS.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),f=n.get("service_account_impersonation"),d=(0,S0.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new RS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[md],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let p=new RegExp(IS);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=FS),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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};pd.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=TS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof DS.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:OS,audience:this.audience,requestedTokenType:PS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[md]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};pd.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[md]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${xS.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ft.BaseExternalAccountClient=gd});var v0=X(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.FileSubjectTokenSupplier=void 0;var _d=require("util"),bd=require("fs"),BS=(0,_d.promisify)(bd.readFile??(()=>{})),MS=(0,_d.promisify)(bd.realpath??(()=>{})),LS=(0,_d.promisify)(bd.lstat??(()=>{})),yd=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 MS(e),!(await LS(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await BS(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Na.FileSubjectTokenSupplier=yd});var T0=X(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.UrlSubjectTokenSupplier=void 0;var jS=Ct(),Cd=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 n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};jS.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Ba.UrlSubjectTokenSupplier=Cd});var D0=X(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.CertificateSubjectTokenSupplier=At.InvalidConfigurationError=At.CertificateSourceUnavailableError=At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ma=Jt(),La=require("fs"),ja=require("crypto"),US=require("https");At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var un=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};At.CertificateSourceUnavailableError=un;var It=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};At.InvalidConfigurationError=It;var wd=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new It("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new It("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new It("Cannot create mTLS Agent with missing certificate or key");return new US.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Ma.isValidFile)(e))return e;throw new un(`Provided certificate config path is invalid: ${e}`)}let n=process.env[At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Ma.isValidFile)(n))return n;throw new un(`Path from environment variable "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Ma.getWellKnownCertificateConfigFileLocation)();if(await(0,Ma.isValidFile)(r))return r;throw new un(`Could not find certificate configuration file. Searched override path, the "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await La.promises.readFile(e,"utf8")}catch{throw new un(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new It(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof It?r:new It(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await La.promises.readFile(e),new ja.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read certificate file at ${e}: ${a}`)}try{o=await La.promises.readFile(n),(0,ja.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new ja.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await La.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new ja.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new It(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),u;if(a===-1)u=[n,...s];else if(a===0)u=s;else throw new It(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(l=>l.raw.toString("base64")))}catch(r){if(r instanceof It)throw r;let o=r instanceof Error?r.message:String(r);throw new un(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};At.CertificateSubjectTokenSupplier=wd});var Ad=X(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.IdentityPoolClient=void 0;var $S=Zn(),Ed=Jt(),qS=v0(),zS=T0(),R0=D0(),HS=Ia(),x0=Xe(),kd=class t extends $S.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Ed.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,Ed.originalOrCamelOptions)(r),a=(0,Ed.originalOrCamelOptions)(s.get("format")),u=a.get("type")||"text",l=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let f=s.get("file"),d=s.get("url"),p=s.get("certificate"),m=s.get("headers");if(f&&d||d&&p||f&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new qS.FileSubjectTokenSupplier({filePath:f,formatType:u,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new zS.UrlSubjectTokenSupplier({url:d,formatType:u,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let b=new R0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=b}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 R0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new HS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new x0.Gaxios({agent:n})}),this.transporter=new x0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ua.IdentityPoolClient=kd});var vd=X(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.AwsRequestSigner=void 0;var $a=Xe(),P0=us(),O0="AWS4-HMAC-SHA256",WS="aws4_request",Sd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,P0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,u=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await JS({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:u,requestPayload:s,additionalAmzHeaders:a}),d=$a.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});u.token&&$a.Gaxios.mergeHeaders(d,{"x-amz-security-token":u.token});let p={url:r,method:o,headers:d};return s!==void 0&&(p.body=s),p}};qa.AwsRequestSigner=Sd;async function bs(t,e,n){return await t.signWithHmacSha256(e,n)}async function GS(t,e,n,r,o){let s=await bs(t,`AWS4${e}`,n),a=await bs(t,s,r),u=await bs(t,a,o);return await bs(t,u,"aws4_request")}async function JS(t){let e=$a.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=$a.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...u.keys()].sort();f.forEach(A=>{l+=`${A}:${u.get(A)}
53
- `});let d=f.join(";"),p=await t.crypto.sha256DigestHex(n),m=`${t.method.toUpperCase()}
52
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,fs="secret must be a string or buffer",yo="key must be a string or a buffer",TA="key must be a string, a buffer or an object",Gl=typeof Ft.createPublicKey=="function";Gl&&(yo+=" or a KeyObject",fs+="or a KeyObject");function By(t){if(!_o.isBuffer(t)&&typeof t!="string"&&(!Gl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Kt(yo)}function My(t){if(!_o.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Kt(TA)}function vA(t){if(!_o.isBuffer(t)){if(typeof t=="string")return t;if(!Gl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Kt(fs)}}function Jl(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ly(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Kt(t){var e=[].slice.call(arguments,1),n=Iy.format.bind(Iy,t).apply(null,e);return new TypeError(n)}function DA(t){return _o.isBuffer(t)||typeof t=="string"}function hs(t){return DA(t)||(t=JSON.stringify(t)),t}function jy(t){return function(n,r){vA(r),n=hs(n);var o=Ft.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Jl(s)}}var Wl,RA="timingSafeEqual"in Ft?function(e,n){return e.byteLength!==n.byteLength?!1:Ft.timingSafeEqual(e,n)}:function(e,n){return Wl||(Wl=Fy()),Wl(e,n)};function xA(t){return function(n,r,o){var s=jy(t)(n,o);return RA(_o.from(r),_o.from(s))}}function Uy(t){return function(n,r){My(r),n=hs(n);var o=Ft.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Jl(s)}}function $y(t){return function(n,r,o){By(o),n=hs(n),r=Ly(r);var s=Ft.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function OA(t){return function(n,r){My(r),n=hs(n);var o=Ft.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Ft.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ft.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Jl(s)}}function PA(t){return function(n,r,o){By(o),n=hs(n),r=Ly(r);var s=Ft.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Ft.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ft.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function FA(t){var e=Uy(t);return function(){var r=e.apply(null,arguments);return r=Ny.derToJose(r,"ES"+t),r}}function IA(t){var e=$y(t);return function(r,o,s){o=Ny.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function NA(){return function(){return""}}function BA(){return function(e,n){return n===""}}qy.exports=function(e){var n={hs:jy,rs:Uy,ps:OA,es:FA,none:NA},r={hs:xA,rs:$y,ps:PA,es:IA,none:BA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Kt(SA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Kl=X((RO,zy)=>{var MA=require("buffer").Buffer;zy.exports=function(e){return typeof e=="string"?e:typeof e=="number"||MA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Ky=X((xO,Vy)=>{var LA=po().Buffer,Hy=zl(),jA=Vl(),UA=require("stream"),Wy=Kl(),Yl=require("util");function Gy(t,e){return LA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function $A(t,e,n){n=n||"utf8";var r=Gy(Wy(t),"binary"),o=Gy(Wy(e),n);return Yl.format("%s.%s",r,o)}function Jy(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=jA(e.alg),a=$A(e,n,o),u=s.sign(a,r);return Yl.format("%s.%s",a,u)}function Ta(t){var e=t.secret||t.privateKey||t.key,n=new Hy(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Hy(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))}Yl.inherits(Ta,UA);Ta.prototype.sign=function(){try{var e=Jy({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(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Ta.sign=Jy;Vy.exports=Ta});var s0=X((OO,o0)=>{var Qy=po().Buffer,Yy=zl(),qA=Vl(),zA=require("stream"),Xy=Kl(),HA=require("util"),WA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function GA(t){return Object.prototype.toString.call(t)==="[object Object]"}function JA(t){if(GA(t))return t;try{return JSON.parse(t)}catch{return}}function Zy(t){var e=t.split(".",1)[0];return JA(Qy.from(e,"base64").toString("binary"))}function VA(t){return t.split(".",2).join(".")}function e0(t){return t.split(".")[2]}function KA(t,e){e=e||"utf8";var n=t.split(".")[1];return Qy.from(n,"base64").toString(e)}function t0(t){return WA.test(t)&&!!Zy(t)}function n0(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Xy(t);var o=e0(t),s=VA(t),a=qA(e);return a.verify(s,o,n)}function r0(t,e){if(e=e||{},t=Xy(t),!t0(t))return null;var n=Zy(t);if(!n)return null;var r=KA(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:e0(t)}}function bo(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new Yy(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Yy(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))}HA.inherits(bo,zA);bo.prototype.verify=function(){try{var e=n0(this.signature.buffer,this.algorithm,this.key.buffer),n=r0(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};bo.decode=r0;bo.isValid=t0;bo.verify=n0;o0.exports=bo});var Ql=X(Xn=>{var i0=Ky(),va=s0(),YA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Xn.ALGORITHMS=YA;Xn.sign=i0.sign;Xn.verify=va.verify;Xn.decode=va.decode;Xn.isValid=va.isValid;Xn.createSign=function(e){return new i0(e)};Xn.createVerify=function(e){return new va(e)}});var w0=X(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.GoogleToken=void 0;var a0=Da(require("fs")),QA=Xe(),XA=Da(Ql()),ZA=Da(require("path")),eS=require("util");function Da(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(Da=function(s,a){if(!a&&s&&s.__esModule)return s;var u,l,f={__proto__:null,default:s};if(s===null||Fn(s)!="object"&&typeof s!="function")return f;if(u=a?r:n){if(u.has(s))return u.get(s);u.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(u=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?u(f,d,l):f[d]=s[d]);return f})(t,e)}function Fn(t){"@babel/helpers - typeof";return Fn=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},Fn(t)}function tS(t,e){g0(t,e),e.add(t)}function nS(t,e,n){g0(t,e),e.set(t,n)}function g0(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function u0(t,e,n){return t.set(Yt(t,e),n),n}function c0(t,e){return t.get(Yt(t,e))}function Yt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function l0(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,b0(r.key),r)}}function y0(t,e,n){return e&&l0(t.prototype,e),n&&l0(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function _0(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function rS(t,e,n){return e=ys(e),oS(t,rd()?Reflect.construct(e,n||[],ys(t).constructor):e.apply(t,n))}function oS(t,e){if(e&&(Fn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return sS(t)}function sS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function iS(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&&gs(t,e)}function Xl(t){var e=typeof Map=="function"?new Map:void 0;return Xl=function(r){if(r===null||!uS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return aS(r,arguments,ys(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),gs(o,r)},Xl(t)}function aS(t,e,n){if(rd())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&gs(o,n.prototype),o}function rd(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(rd=function(){return!!t})()}function uS(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function gs(t,e){return gs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},gs(t,e)}function ys(t){return ys=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ys(t)}function Et(t,e,n){return(e=b0(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function b0(t){var e=cS(t,"string");return Fn(e)=="symbol"?e:e+""}function cS(t,e){if(Fn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Fn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function At(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(C,w,y,g){var _=w&&w.prototype instanceof u?w:u,E=Object.create(_.prototype);return kt(E,"_invoke",(function(b,S,v){var R,$,H,P=0,K=v||[],q=!1,Y={p:0,n:0,v:t,a:Q,f:Q.bind(t,4),d:function(oe,se){return R=oe,$=0,H=t,Y.n=se,a}};function Q(ee,oe){for($=ee,H=oe,e=0;!q&&P&&!se&&e<K.length;e++){var se,he=K[e],J=Y.p,Z=he[2];ee>3?(se=Z===oe)&&(H=he[($=he[4])?5:($=3,3)],he[4]=he[5]=t):he[0]<=J&&((se=ee<2&&J<he[1])?($=0,Y.v=oe,Y.n=he[1]):J<Z&&(se=ee<3||he[0]>oe||oe>Z)&&(he[4]=ee,he[5]=oe,Y.n=Z,$=0))}if(se||ee>1)return a;throw q=!0,oe}return function(ee,oe,se){if(P>1)throw TypeError("Generator is already running");for(q&&oe===1&&Q(oe,se),$=oe,H=se;(e=$<2?t:H)||!q;){R||($?$<3?($>1&&(Y.n=-1),Q($,H)):Y.n=H:Y.v=H);try{if(P=2,R){if($||(ee="next"),e=R[ee]){if(!(e=e.call(R,H)))throw TypeError("iterator result is not an object");if(!e.done)return e;H=e.value,$<2&&($=0)}else $===1&&(e=R.return)&&e.call(R),$<2&&(H=TypeError("The iterator does not provide a '"+ee+"' method"),$=1);R=t}else if((e=(q=Y.n<0)?H:b.call(S,Y))!==a)break}catch(he){R=t,$=1,H=he}finally{P=1}}return{value:e,done:q}}})(C,y,g),!0),E}var a={};function u(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][r]?e(e([][r]())):(kt(e={},r,function(){return this}),e),h=f.prototype=u.prototype=Object.create(d);function m(C){return Object.setPrototypeOf?Object.setPrototypeOf(C,f):(C.__proto__=f,kt(C,o,"GeneratorFunction")),C.prototype=Object.create(h),C}return l.prototype=f,kt(h,"constructor",f),kt(f,"constructor",l),l.displayName="GeneratorFunction",kt(f,o,"GeneratorFunction"),kt(h),kt(h,o,"Generator"),kt(h,r,function(){return this}),kt(h,"toString",function(){return"[object Generator]"}),(At=function(){return{w:s,m}})()}function kt(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}kt=function(a,u,l,f){if(u)o?o(a,u,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[u]=l;else{var d=function(m,C){kt(a,m,function(w){return this._invoke(m,C,w)})};d("next",0),d("throw",1),d("return",2)}},kt(t,e,n,r)}function d0(t,e,n,r,o,s,a){try{var u=t[s](a),l=u.value}catch(f){return void n(f)}u.done?e(l):Promise.resolve(l).then(r,o)}function Co(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){d0(s,r,o,a,u,"next",l)}function u(l){d0(s,r,o,a,u,"throw",l)}a(void 0)})}}var f0=a0.readFile?(0,eS.promisify)(a0.readFile):Co(At().m(function t(){return At().w(function(e){for(;;)switch(e.n){case 0:throw new ms("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),h0="https://oauth2.googleapis.com/token",lS="https://oauth2.googleapis.com/revoke?token=",ms=(function(t){function e(n,r){var o;return _0(this,e),o=rS(this,e,[n]),Et(o,"code",void 0),o.code=r,o}return iS(e,t),y0(e)})(Xl(Error)),ps=new WeakMap,an=new WeakSet,FO=Ra.GoogleToken=(function(){function t(e){_0(this,t),tS(this,an),Et(this,"expiresAt",void 0),Et(this,"key",void 0),Et(this,"keyFile",void 0),Et(this,"iss",void 0),Et(this,"sub",void 0),Et(this,"scope",void 0),Et(this,"rawToken",void 0),Et(this,"tokenExpires",void 0),Et(this,"email",void 0),Et(this,"additionalClaims",void 0),Et(this,"eagerRefreshThresholdMillis",void 0),Et(this,"transporter",{request:function(r){return(0,QA.request)(r)}}),nS(this,ps,void 0),Yt(an,this,C0).call(this,e)}return y0(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 n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Fn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Yt(an,this,p0).call(this,r).then(function(s){return o(null,s)},n);return}return Yt(an,this,p0).call(this,r)}},{key:"getCredentials",value:(function(){var e=Co(At().m(function r(o){var s,a,u,l,f,d,h;return At().w(function(m){for(;;)switch(m.n){case 0:s=ZA.extname(o),h=s,m.n=h===".json"?1:h===".der"||h===".crt"||h===".pem"?4:h===".p12"||h===".pfx"?6:7;break;case 1:return m.n=2,f0(o,"utf8");case 2:if(a=m.v,u=JSON.parse(a),l=u.private_key,f=u.client_email,!(!l||!f)){m.n=3;break}throw new ms("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:f});case 4:return m.n=5,f0(o,"utf8");case 5:return d=m.v,m.a(2,{privateKey:d});case 6:throw new ms("*.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 ms("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Yt(an,this,m0).call(this).then(function(){return n()},n);return}return Yt(an,this,m0).call(this)}}])})();function p0(t){return Zl.apply(this,arguments)}function Zl(){return Zl=Co(At().m(function t(e){return At().w(function(n){for(;;)switch(n.n){case 0:if(!(c0(ps,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,c0(ps,this));case 1:return n.p=1,n.n=2,u0(ps,this,Yt(an,this,dS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,u0(ps,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),Zl.apply(this,arguments)}function dS(t){return ed.apply(this,arguments)}function ed(){return ed=Co(At().m(function t(e){var n;return At().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Yt(an,this,fS).call(this);case 4:return r.a(2,Yt(an,this,hS).call(this))}},t,this)})),ed.apply(this,arguments)}function fS(){if(!this.iss)throw new ms("email is required.","MISSING_CREDENTIALS")}function m0(){return td.apply(this,arguments)}function td(){return td=Co(At().m(function t(){var e;return At().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=lS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Yt(an,this,C0).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),td.apply(this,arguments)}function C0(){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,Fn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function hS(){return nd.apply(this,arguments)}function nd(){return nd=Co(At().m(function t(){var e,n,r,o,s,a,u,l,f,d;return At().w(function(h){for(;;)switch(h.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:h0,exp:e+3600,iat:e,sub:this.sub},n),o=XA.sign({header:{alg:"RS256"},payload:r,secret:this.key}),h.p=1,h.n=2,this.transporter.request({method:"POST",url:h0,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=h.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,h.a(2,this.rawToken);case 3:throw h.p=3,d=h.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(u=d.response)===null||u===void 0?void 0:u.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return h.a(2)}},t,this,[[1,3]])})),nd.apply(this,arguments)}});var sd=X(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.JWTAccess=void 0;var pS=Ql(),mS=Jt(),E0={alg:"RS256",typ:"JWT"},od=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new mS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let u=Math.floor(Date.now()/1e3),l=t.getExpirationTime(u),f;if(Array.isArray(r)&&(r=r.join(" ")),r?f={iss:this.email,sub:this.email,scope:r,exp:l,iat:u}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:u},n){for(let w in f)if(n[w])throw new Error(`The '${w}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...E0,kid:this.keyId}:E0,h=Object.assign(f,n),m=pS.sign({header:d,payload:h,secret:this.key}),C=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:C}),C}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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};xa.JWTAccess=od});var ad=X(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.JWT=void 0;var k0=w0(),gS=sd(),yS=vr(),Oa=wt(),id=class t extends yS.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 n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Oa.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Oa.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Oa.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new gS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Oa.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new k0.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 n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.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(n=>e(null,n),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(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new k0.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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}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 n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Pa.JWT=id});var cd=X(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.UserRefreshClient=wo.USER_REFRESH_ACCOUNT_TYPE=void 0;var _S=vr(),bS=wt();wo.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ud=class t extends _S.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...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 bS.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(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,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};wo.UserRefreshClient=ud});var dd=X(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.Impersonated=Eo.IMPERSONATED_ACCOUNT_TYPE=void 0;var A0=vr(),CS=Xe(),wS=Jt();Eo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var ld=class t extends A0.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 A0.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,wS.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 n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof CS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Eo.Impersonated=ld});var hd=X(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.OAuthClientAuthHandler=void 0;_s.getErrorFromOAuthErrorResponse=AS;var ko=Xe(),ES=us(),kS=["PUT","POST","PATCH"],fd=class{#e=(0,ES.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ko.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ko.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=ko.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=ko.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ko.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);ko.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!kS.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.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(`${o} 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"]}}}};_s.OAuthClientAuthHandler=fd;function AS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var Ia=X(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.StsCredentials=void 0;var SS=Xe(),TS=wt(),S0=hd(),vS=Jt(),pd=class t extends S0.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={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:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,vS.removeUndefinedValuesInObject)(o))};TS.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),u=a.data;return u.res=a,u}catch(a){throw a instanceof SS.GaxiosError&&a.response?(0,S0.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Fa.StsCredentials=pd});var Zn=X(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.BaseExternalAccountClient=It.CLOUD_RESOURCE_MANAGER=It.EXTERNAL_ACCOUNT_TYPE=It.EXPIRATION_TIME_OFFSET=void 0;var DS=Xe(),RS=require("stream"),md=wt(),xS=Ia(),T0=Jt(),OS=xl(),PS="urn:ietf:params:oauth:grant-type:token-exchange",FS="urn:ietf:params:oauth:token-type:access_token",gd="https://www.googleapis.com/auth/cloud-platform",IS=3600;It.EXPIRATION_TIME_OFFSET=300*1e3;It.EXTERNAL_ACCOUNT_TYPE="external_account";It.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var NS="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",BS="https://sts.{universeDomain}/v1/token",yd=class t extends md.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,T0.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==It.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${It.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??BS.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),f=n.get("service_account_impersonation"),d=(0,T0.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new xS.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[gd],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let h=new RegExp(NS);if(this.workforcePoolUserProject&&!this.audience.match(h))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=IS),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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};md.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=DS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof RS.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:PS,audience:this.audience,requestedTokenType:FS,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[gd]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};md.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[gd]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${OS.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};It.BaseExternalAccountClient=yd});var v0=X(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.FileSubjectTokenSupplier=void 0;var bd=require("util"),Cd=require("fs"),MS=(0,bd.promisify)(Cd.readFile??(()=>{})),LS=(0,bd.promisify)(Cd.realpath??(()=>{})),jS=(0,bd.promisify)(Cd.lstat??(()=>{})),_d=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 LS(e),!(await jS(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await MS(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Na.FileSubjectTokenSupplier=_d});var D0=X(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.UrlSubjectTokenSupplier=void 0;var US=wt(),wd=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 n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};US.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Ba.UrlSubjectTokenSupplier=wd});var R0=X(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.CertificateSubjectTokenSupplier=St.InvalidConfigurationError=St.CertificateSourceUnavailableError=St.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ma=Jt(),La=require("fs"),ja=require("crypto"),$S=require("https");St.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var un=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};St.CertificateSourceUnavailableError=un;var Nt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};St.InvalidConfigurationError=Nt;var Ed=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Nt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Nt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Nt("Cannot create mTLS Agent with missing certificate or key");return new $S.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Ma.isValidFile)(e))return e;throw new un(`Provided certificate config path is invalid: ${e}`)}let n=process.env[St.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Ma.isValidFile)(n))return n;throw new un(`Path from environment variable "${St.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Ma.getWellKnownCertificateConfigFileLocation)();if(await(0,Ma.isValidFile)(r))return r;throw new un(`Could not find certificate configuration file. Searched override path, the "${St.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await La.promises.readFile(e,"utf8")}catch{throw new un(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Nt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Nt?r:new Nt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await La.promises.readFile(e),new ja.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read certificate file at ${e}: ${a}`)}try{o=await La.promises.readFile(n),(0,ja.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new ja.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await La.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new ja.X509Certificate(l)}catch(d){let h=d instanceof Error?d.message:String(d);throw new Nt(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${h}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),u;if(a===-1)u=[n,...s];else if(a===0)u=s;else throw new Nt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(l=>l.raw.toString("base64")))}catch(r){if(r instanceof Nt)throw r;let o=r instanceof Error?r.message:String(r);throw new un(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};St.CertificateSubjectTokenSupplier=Ed});var Sd=X(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.IdentityPoolClient=void 0;var qS=Zn(),kd=Jt(),zS=v0(),HS=D0(),x0=R0(),WS=Ia(),O0=Xe(),Ad=class t extends qS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,kd.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,kd.originalOrCamelOptions)(r),a=(0,kd.originalOrCamelOptions)(s.get("format")),u=a.get("type")||"text",l=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let f=s.get("file"),d=s.get("url"),h=s.get("certificate"),m=s.get("headers");if(f&&d||d&&h||f&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new zS.FileSubjectTokenSupplier({filePath:f,formatType:u,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new HS.UrlSubjectTokenSupplier({url:d,formatType:u,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(h){this.credentialSourceType="certificate";let C=new x0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=C}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 x0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new WS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new O0.Gaxios({agent:n})}),this.transporter=new O0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ua.IdentityPoolClient=Ad});var vd=X(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.AwsRequestSigner=void 0;var $a=Xe(),F0=us(),P0="AWS4-HMAC-SHA256",GS="aws4_request",Td=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,F0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,u=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await VS({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:u,requestPayload:s,additionalAmzHeaders:a}),d=$a.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});u.token&&$a.Gaxios.mergeHeaders(d,{"x-amz-security-token":u.token});let h={url:r,method:o,headers:d};return s!==void 0&&(h.body=s),h}};qa.AwsRequestSigner=Td;async function bs(t,e,n){return await t.signWithHmacSha256(e,n)}async function JS(t,e,n,r,o){let s=await bs(t,`AWS4${e}`,n),a=await bs(t,s,r),u=await bs(t,a,o);return await bs(t,u,"aws4_request")}async function VS(t){let e=$a.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=$a.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...u.keys()].sort();f.forEach(E=>{l+=`${E}:${u.get(E)}
53
+ `});let d=f.join(";"),h=await t.crypto.sha256DigestHex(n),m=`${t.method.toUpperCase()}
54
54
  ${t.canonicalUri}
55
55
  ${t.canonicalQuerystring}
56
56
  ${l}
57
57
  ${d}
58
- ${p}`,b=`${a}/${t.region}/${r}/${WS}`,w=`${O0}
58
+ ${h}`,C=`${a}/${t.region}/${r}/${GS}`,w=`${P0}
59
59
  ${s}
60
- ${b}
61
- `+await t.crypto.sha256DigestHex(m),y=await GS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),g=await bs(t.crypto,y,w),_=`${O0} Credential=${t.securityCredentials.accessKeyId}/${b}, SignedHeaders=${d}, Signature=${(0,P0.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:_,canonicalQuerystring:t.canonicalQuerystring}}});var F0=X(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.DefaultAwsSecurityCredentialsSupplier=void 0;var za=Ct(),Td=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.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.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 r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};za.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return za.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return za.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return za.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};Ha.DefaultAwsSecurityCredentialsSupplier=Td});var Rd=X(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.AwsClient=void 0;var VS=vd(),KS=Zn(),YS=F0(),I0=Jt(),QS=Xe(),Dd=class t extends KS.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 n=(0,I0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,I0.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let a=s.get("region_url"),u=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new YS.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.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 VS.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"}),n=[];return QS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Wa.AwsClient=Dd});var Id=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.InvalidSubjectTokenError=$e.InvalidMessageFieldError=$e.InvalidCodeFieldError=$e.InvalidTokenTypeFieldError=$e.InvalidExpirationTimeFieldError=$e.InvalidSuccessFieldError=$e.InvalidVersionFieldError=$e.ExecutableResponseError=$e.ExecutableResponse=void 0;var Ga="urn:ietf:params:oauth:token-type:saml2",xd="urn:ietf:params:oauth:token-type:id_token",Od="urn:ietf:params:oauth:token-type:jwt",Pd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ja("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Va("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!==Ga&&this.tokenType!==xd&&this.tokenType!==Od)throw new Ka(`Executable response must contain a 'token_type' field when successful and it must be one of ${xd}, ${Od}, or ${Ga}.`);if(this.tokenType===Ga){if(!e.saml_response)throw new Cs(`Executable response must contain a 'saml_response' field when token_type=${Ga}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Cs(`Executable response must contain a 'id_token' field when token_type=${xd} or ${Od}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ya("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Qa("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)}};$e.ExecutableResponse=Pd;var cn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};$e.ExecutableResponseError=cn;var Ja=class extends cn{};$e.InvalidVersionFieldError=Ja;var Va=class extends cn{};$e.InvalidSuccessFieldError=Va;var Fd=class extends cn{};$e.InvalidExpirationTimeFieldError=Fd;var Ka=class extends cn{};$e.InvalidTokenTypeFieldError=Ka;var Ya=class extends cn{};$e.InvalidCodeFieldError=Ya;var Qa=class extends cn{};$e.InvalidMessageFieldError=Qa;var Cs=class extends cn{};$e.InvalidSubjectTokenError=Cs});var Md=X(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.PluggableAuthHandler=Ao.ExecutableError=void 0;var Dr=Id(),XS=require("child_process"),Nd=require("fs"),Xa=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};Ao.ExecutableError=Xa;var Bd=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((n,r)=>{let o=XS.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",u=>{s+=u}),o.stderr.on("data",u=>{s+=u});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",u=>{if(clearTimeout(a),u===0)try{let l=JSON.parse(s),f=new Dr.ExecutableResponse(l);return n(f)}catch(l){return l instanceof Dr.ExecutableResponseError?r(l):r(new Dr.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Xa(s,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Nd.promises.realpath(this.outputFile)}catch{return}if(!(await Nd.promises.lstat(e)).isFile())return;let n=await Nd.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Dr.ExecutableResponse(r).isValid()?new Dr.ExecutableResponse(r):void 0}catch(r){throw r instanceof Dr.ExecutableResponseError?r:new Dr.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};Ao.PluggableAuthHandler=Bd});var jd=X(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.PluggableAuthClient=So.ExecutableError=void 0;var ZS=Zn(),ev=Id(),N0=Md(),tv=Md();Object.defineProperty(So,"ExecutableError",{enumerable:!0,get:function(){return tv.ExecutableError}});var nv=30*1e3,B0=5*1e3,M0=120*1e3,rv="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",L0=1,Ld=class extends ZS.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=nv;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<B0||this.timeoutMillis>M0)throw new Error(`Timeout must be between ${B0} and ${M0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new N0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[rv]!=="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 n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>L0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${L0}.`);if(!e.success)throw new N0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new ev.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}};So.PluggableAuthClient=Ld});var $d=X(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.ExternalAccountClient=void 0;var ov=Zn(),sv=Ad(),iv=Rd(),av=jd(),Ud=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===ov.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new iv.AwsClient(e):e.credential_source?.executable?new av.PluggableAuthClient(e):new sv.IdentityPoolClient(e):null}};Za.ExternalAccountClient=Ud});var q0=X(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.ExternalAccountAuthorizedUserClient=vo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var U0=Ct(),j0=fd(),$0=Xe(),uv=require("stream"),cv=Zn();vo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var lv="https://sts.{universeDomain}/v1/oauthtoken",qd=class t extends j0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};U0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof $0.GaxiosError&&o.response?(0,j0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},zd=class extends U0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new qd({tokenRefreshEndpoint:e.token_url??lv.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=cv.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=$0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof uv.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};vo.ExternalAccountAuthorizedUserClient=zd});var G0=X(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.GoogleAuth=Qt.GoogleAuthExceptionMessages=void 0;var dv=require("child_process"),ws=require("fs"),fv=Xe(),Es=as(),hv=require("os"),Hd=require("path"),pv=us(),mv=Ll(),gv=Ul(),yv=$l(),To=id(),z0=ud(),Do=ld(),_v=$d(),ks=Zn(),Wd=Ct(),H0=q0(),W0=Jt();Qt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
60
+ ${C}
61
+ `+await t.crypto.sha256DigestHex(m),y=await JS(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),g=await bs(t.crypto,y,w),_=`${P0} Credential=${t.securityCredentials.accessKeyId}/${C}, SignedHeaders=${d}, Signature=${(0,F0.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:_,canonicalQuerystring:t.canonicalQuerystring}}});var I0=X(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.DefaultAwsSecurityCredentialsSupplier=void 0;var za=wt(),Dd=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.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.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 r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};za.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return za.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return za.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return za.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){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}};Ha.DefaultAwsSecurityCredentialsSupplier=Dd});var xd=X(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.AwsClient=void 0;var KS=vd(),YS=Zn(),QS=I0(),N0=Jt(),XS=Xe(),Rd=class t extends YS.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 n=(0,N0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,N0.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let a=s.get("region_url"),u=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new QS.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.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 KS.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"}),n=[];return XS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Wa.AwsClient=Rd});var Nd=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.InvalidSubjectTokenError=$e.InvalidMessageFieldError=$e.InvalidCodeFieldError=$e.InvalidTokenTypeFieldError=$e.InvalidExpirationTimeFieldError=$e.InvalidSuccessFieldError=$e.InvalidVersionFieldError=$e.ExecutableResponseError=$e.ExecutableResponse=void 0;var Ga="urn:ietf:params:oauth:token-type:saml2",Od="urn:ietf:params:oauth:token-type:id_token",Pd="urn:ietf:params:oauth:token-type:jwt",Fd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ja("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Va("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!==Ga&&this.tokenType!==Od&&this.tokenType!==Pd)throw new Ka(`Executable response must contain a 'token_type' field when successful and it must be one of ${Od}, ${Pd}, or ${Ga}.`);if(this.tokenType===Ga){if(!e.saml_response)throw new Cs(`Executable response must contain a 'saml_response' field when token_type=${Ga}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Cs(`Executable response must contain a 'id_token' field when token_type=${Od} or ${Pd}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ya("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Qa("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)}};$e.ExecutableResponse=Fd;var cn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};$e.ExecutableResponseError=cn;var Ja=class extends cn{};$e.InvalidVersionFieldError=Ja;var Va=class extends cn{};$e.InvalidSuccessFieldError=Va;var Id=class extends cn{};$e.InvalidExpirationTimeFieldError=Id;var Ka=class extends cn{};$e.InvalidTokenTypeFieldError=Ka;var Ya=class extends cn{};$e.InvalidCodeFieldError=Ya;var Qa=class extends cn{};$e.InvalidMessageFieldError=Qa;var Cs=class extends cn{};$e.InvalidSubjectTokenError=Cs});var Ld=X(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.PluggableAuthHandler=Ao.ExecutableError=void 0;var Dr=Nd(),ZS=require("child_process"),Bd=require("fs"),Xa=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};Ao.ExecutableError=Xa;var Md=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((n,r)=>{let o=ZS.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",u=>{s+=u}),o.stderr.on("data",u=>{s+=u});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",u=>{if(clearTimeout(a),u===0)try{let l=JSON.parse(s),f=new Dr.ExecutableResponse(l);return n(f)}catch(l){return l instanceof Dr.ExecutableResponseError?r(l):r(new Dr.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Xa(s,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Bd.promises.realpath(this.outputFile)}catch{return}if(!(await Bd.promises.lstat(e)).isFile())return;let n=await Bd.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Dr.ExecutableResponse(r).isValid()?new Dr.ExecutableResponse(r):void 0}catch(r){throw r instanceof Dr.ExecutableResponseError?r:new Dr.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};Ao.PluggableAuthHandler=Md});var Ud=X(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.PluggableAuthClient=So.ExecutableError=void 0;var eT=Zn(),tT=Nd(),B0=Ld(),nT=Ld();Object.defineProperty(So,"ExecutableError",{enumerable:!0,get:function(){return nT.ExecutableError}});var rT=30*1e3,M0=5*1e3,L0=120*1e3,oT="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",j0=1,jd=class extends eT.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=rT;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<M0||this.timeoutMillis>L0)throw new Error(`Timeout must be between ${M0} and ${L0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new B0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[oT]!=="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 n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>j0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${j0}.`);if(!e.success)throw new B0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new tT.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}};So.PluggableAuthClient=jd});var qd=X(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.ExternalAccountClient=void 0;var sT=Zn(),iT=Sd(),aT=xd(),uT=Ud(),$d=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===sT.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new aT.AwsClient(e):e.credential_source?.executable?new uT.PluggableAuthClient(e):new iT.IdentityPoolClient(e):null}};Za.ExternalAccountClient=$d});var z0=X(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.ExternalAccountAuthorizedUserClient=To.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var $0=wt(),U0=hd(),q0=Xe(),cT=require("stream"),lT=Zn();To.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var dT="https://sts.{universeDomain}/v1/oauthtoken",zd=class t extends U0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};$0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof q0.GaxiosError&&o.response?(0,U0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Hd=class extends $0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new zd({tokenRefreshEndpoint:e.token_url??dT.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=lT.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=q0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof cT.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};To.ExternalAccountAuthorizedUserClient=Hd});var J0=X(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.GoogleAuth=Qt.GoogleAuthExceptionMessages=void 0;var fT=require("child_process"),ws=require("fs"),hT=Xe(),Es=as(),pT=require("os"),Wd=require("path"),mT=us(),gT=jl(),yT=$l(),_T=ql(),vo=ad(),H0=cd(),Do=dd(),bT=qd(),ks=Zn(),Gd=wt(),W0=z0(),G0=Jt();Qt.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 Gd=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(Qt.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(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Qt.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(Qt.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 Es.universe("universe-domain"),e||=Wd.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Wd.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,W0.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Wd.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof To.JWT?n.scopes=this.scopes:n instanceof ks.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof To.JWT?n.scopes=this.scopes:n instanceof ks.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new mv.Compute(e));throw new Error(Qt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Es.getGCPResidency()||await Es.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=Hd.join(o,".config"))}return n&&(n=Hd.join(n,"gcloud","application_default_credentials.json"),ws.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=ws.realpathSync(e),!ws.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=ws.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Do.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Do.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 n=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 r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Do.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){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 r,o=(0,W0.originalOrCamelOptions)(n).get("universe_domain");return e.type===z0.USER_REFRESH_ACCOUNT_TYPE?(r=new z0.UserRefreshClient(n),r.fromJSON(e)):e.type===Do.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===ks.EXTERNAL_ACCOUNT_TYPE?(r=_v.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===H0.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new H0.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,r=new To.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){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 o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),u=this._cacheClientFromJSON(a,n);return r(u)}catch(a){if(!this.keyFilename)throw a;let u=new To.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),r(u)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new To.JWT({...n,apiKey:e})}_isWindows(){let e=hv.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,dv.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);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 n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==ks.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Es.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Do.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof ks.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,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[n,r]=await Promise.all([Es.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(Qt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Hd.resolve(this.keyFilename),n=ws.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))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 gv.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=fv.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,yv.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof Do.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,pv.createCrypto)();if(r instanceof To.JWT&&r.key)return await s.sign(r.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Qt.GoogleAuth=Gd});var J0=X(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.IAMAuth=void 0;var Jd=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};eu.IAMAuth=Jd});var V0=X(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.DownscopedClient=ln.EXPIRATION_TIME_OFFSET=ln.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var bv=Xe(),Cv=require("stream"),Vd=Ct(),wv=Ia(),Ev="urn:ietf:params:oauth:grant-type:token-exchange",kv="urn:ietf:params:oauth:token-type:access_token",Av="urn:ietf:params:oauth:token-type:access_token";ln.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;ln.EXPIRATION_TIME_OFFSET=300*1e3;var Kd=class extends Vd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Vd.AuthClient?{}:e),e instanceof Vd.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(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>ln.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${ln.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new wv.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=bv.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof Cv.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:Ev,requestedTokenType:kv,subjectToken:e,subjectTokenType:Av},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};ln.DownscopedClient=Kd});var K0=X(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.PassThroughClient=void 0;var Sv=Ct(),Yd=class extends Sv.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};tu.PassThroughClient=Yd});var Xd=X(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.GoogleAuth=ce.auth=ce.PassThroughClient=ce.ExecutableError=ce.PluggableAuthClient=ce.DownscopedClient=ce.BaseExternalAccountClient=ce.ExternalAccountClient=ce.IdentityPoolClient=ce.AwsRequestSigner=ce.AwsClient=ce.UserRefreshClient=ce.LoginTicket=ce.ClientAuthentication=ce.OAuth2Client=ce.CodeChallengeMethod=ce.Impersonated=ce.JWT=ce.JWTAccess=ce.IdTokenClient=ce.IAMAuth=ce.GCPEnv=ce.Compute=ce.DEFAULT_UNIVERSE=ce.AuthClient=ce.gaxios=ce.gcpMetadata=void 0;var Y0=G0();Object.defineProperty(ce,"GoogleAuth",{enumerable:!0,get:function(){return Y0.GoogleAuth}});ce.gcpMetadata=as();ce.gaxios=Xe();var Q0=Ct();Object.defineProperty(ce,"AuthClient",{enumerable:!0,get:function(){return Q0.AuthClient}});Object.defineProperty(ce,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Q0.DEFAULT_UNIVERSE}});var vv=Ll();Object.defineProperty(ce,"Compute",{enumerable:!0,get:function(){return vv.Compute}});var Tv=$l();Object.defineProperty(ce,"GCPEnv",{enumerable:!0,get:function(){return Tv.GCPEnv}});var Dv=J0();Object.defineProperty(ce,"IAMAuth",{enumerable:!0,get:function(){return Dv.IAMAuth}});var Rv=Ul();Object.defineProperty(ce,"IdTokenClient",{enumerable:!0,get:function(){return Rv.IdTokenClient}});var xv=od();Object.defineProperty(ce,"JWTAccess",{enumerable:!0,get:function(){return xv.JWTAccess}});var Ov=id();Object.defineProperty(ce,"JWT",{enumerable:!0,get:function(){return Ov.JWT}});var Pv=ld();Object.defineProperty(ce,"Impersonated",{enumerable:!0,get:function(){return Pv.Impersonated}});var Qd=Tr();Object.defineProperty(ce,"CodeChallengeMethod",{enumerable:!0,get:function(){return Qd.CodeChallengeMethod}});Object.defineProperty(ce,"OAuth2Client",{enumerable:!0,get:function(){return Qd.OAuth2Client}});Object.defineProperty(ce,"ClientAuthentication",{enumerable:!0,get:function(){return Qd.ClientAuthentication}});var Fv=Il();Object.defineProperty(ce,"LoginTicket",{enumerable:!0,get:function(){return Fv.LoginTicket}});var Iv=ud();Object.defineProperty(ce,"UserRefreshClient",{enumerable:!0,get:function(){return Iv.UserRefreshClient}});var Nv=Rd();Object.defineProperty(ce,"AwsClient",{enumerable:!0,get:function(){return Nv.AwsClient}});var Bv=vd();Object.defineProperty(ce,"AwsRequestSigner",{enumerable:!0,get:function(){return Bv.AwsRequestSigner}});var Mv=Ad();Object.defineProperty(ce,"IdentityPoolClient",{enumerable:!0,get:function(){return Mv.IdentityPoolClient}});var Lv=$d();Object.defineProperty(ce,"ExternalAccountClient",{enumerable:!0,get:function(){return Lv.ExternalAccountClient}});var jv=Zn();Object.defineProperty(ce,"BaseExternalAccountClient",{enumerable:!0,get:function(){return jv.BaseExternalAccountClient}});var Uv=V0();Object.defineProperty(ce,"DownscopedClient",{enumerable:!0,get:function(){return Uv.DownscopedClient}});var X0=jd();Object.defineProperty(ce,"PluggableAuthClient",{enumerable:!0,get:function(){return X0.PluggableAuthClient}});Object.defineProperty(ce,"ExecutableError",{enumerable:!0,get:function(){return X0.ExecutableError}});var $v=K0();Object.defineProperty(ce,"PassThroughClient",{enumerable:!0,get:function(){return $v.PassThroughClient}});var qv=new Y0.GoogleAuth;ce.auth=qv});var P_=X((PI,Rf)=>{"use strict";var AR=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,SR=/(\w*(\.\w*)*)\..*/;Rf.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,O_(r.stack)}};function O_(t){let e=t.match(AR);return e?e[1].split(/[/\\]/).slice(-1)[0].match(SR)[1]:"anonymous"}Rf.exports.extractPluginName=O_});var I_=X((FI,F_)=>{"use strict";F_.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var N_=X((II,xu)=>{"use strict";var vR=P_(),TR=I_(),DR=0;function xf(t,e={}){let n=!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||(n=!0,e.name=vR(t)+"-auto-"+DR++),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 r=TR(e.name);return!n&&!t[r]&&(t[r]=t),t}xu.exports=xf;xu.exports.default=xf;xu.exports.fastifyPlugin=xf});var Is,Pf=Le(()=>{"use strict";Is=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,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:a}=n||{},u="";if(o){let l=new Date().toISOString();u+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(u+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":u+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?u+=this.toMarkdown(e):u+=String(e);break;case"text":default:typeof e=="object"?u+=JSON.stringify(e,null,2):u+=String(e);break}return a&&Object.keys(a).length>0&&(u+=`
67
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Jd=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(Qt.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(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Qt.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(Qt.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 Es.universe("universe-domain"),e||=Gd.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Gd.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,G0.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Gd.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof vo.JWT?n.scopes=this.scopes:n instanceof ks.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof vo.JWT?n.scopes=this.scopes:n instanceof ks.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new gT.Compute(e));throw new Error(Qt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Es.getGCPResidency()||await Es.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=Wd.join(o,".config"))}return n&&(n=Wd.join(n,"gcloud","application_default_credentials.json"),ws.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=ws.realpathSync(e),!ws.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=ws.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Do.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Do.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 n=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 r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Do.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){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 r,o=(0,G0.originalOrCamelOptions)(n).get("universe_domain");return e.type===H0.USER_REFRESH_ACCOUNT_TYPE?(r=new H0.UserRefreshClient(n),r.fromJSON(e)):e.type===Do.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===ks.EXTERNAL_ACCOUNT_TYPE?(r=bT.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===W0.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new W0.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,r=new vo.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){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 o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),u=this._cacheClientFromJSON(a,n);return r(u)}catch(a){if(!this.keyFilename)throw a;let u=new vo.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),r(u)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new vo.JWT({...n,apiKey:e})}_isWindows(){let e=pT.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,fT.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);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 n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==ks.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Es.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Do.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof ks.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,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[n,r]=await Promise.all([Es.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(Qt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Wd.resolve(this.keyFilename),n=ws.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))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 yT.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=hT.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,_T.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof Do.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,mT.createCrypto)();if(r instanceof vo.JWT&&r.key)return await s.sign(r.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Qt.GoogleAuth=Jd});var V0=X(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.IAMAuth=void 0;var Vd=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};eu.IAMAuth=Vd});var K0=X(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.DownscopedClient=ln.EXPIRATION_TIME_OFFSET=ln.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var CT=Xe(),wT=require("stream"),Kd=wt(),ET=Ia(),kT="urn:ietf:params:oauth:grant-type:token-exchange",AT="urn:ietf:params:oauth:token-type:access_token",ST="urn:ietf:params:oauth:token-type:access_token";ln.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;ln.EXPIRATION_TIME_OFFSET=300*1e3;var Yd=class extends Kd.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Kd.AuthClient?{}:e),e instanceof Kd.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(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>ln.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${ln.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new ET.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(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=CT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof wT.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:kT,requestedTokenType:AT,subjectToken:e,subjectTokenType:ST},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.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 n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};ln.DownscopedClient=Yd});var Y0=X(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.PassThroughClient=void 0;var TT=wt(),Qd=class extends TT.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};tu.PassThroughClient=Qd});var Zd=X(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.GoogleAuth=ce.auth=ce.PassThroughClient=ce.ExecutableError=ce.PluggableAuthClient=ce.DownscopedClient=ce.BaseExternalAccountClient=ce.ExternalAccountClient=ce.IdentityPoolClient=ce.AwsRequestSigner=ce.AwsClient=ce.UserRefreshClient=ce.LoginTicket=ce.ClientAuthentication=ce.OAuth2Client=ce.CodeChallengeMethod=ce.Impersonated=ce.JWT=ce.JWTAccess=ce.IdTokenClient=ce.IAMAuth=ce.GCPEnv=ce.Compute=ce.DEFAULT_UNIVERSE=ce.AuthClient=ce.gaxios=ce.gcpMetadata=void 0;var Q0=J0();Object.defineProperty(ce,"GoogleAuth",{enumerable:!0,get:function(){return Q0.GoogleAuth}});ce.gcpMetadata=as();ce.gaxios=Xe();var X0=wt();Object.defineProperty(ce,"AuthClient",{enumerable:!0,get:function(){return X0.AuthClient}});Object.defineProperty(ce,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return X0.DEFAULT_UNIVERSE}});var vT=jl();Object.defineProperty(ce,"Compute",{enumerable:!0,get:function(){return vT.Compute}});var DT=ql();Object.defineProperty(ce,"GCPEnv",{enumerable:!0,get:function(){return DT.GCPEnv}});var RT=V0();Object.defineProperty(ce,"IAMAuth",{enumerable:!0,get:function(){return RT.IAMAuth}});var xT=$l();Object.defineProperty(ce,"IdTokenClient",{enumerable:!0,get:function(){return xT.IdTokenClient}});var OT=sd();Object.defineProperty(ce,"JWTAccess",{enumerable:!0,get:function(){return OT.JWTAccess}});var PT=ad();Object.defineProperty(ce,"JWT",{enumerable:!0,get:function(){return PT.JWT}});var FT=dd();Object.defineProperty(ce,"Impersonated",{enumerable:!0,get:function(){return FT.Impersonated}});var Xd=vr();Object.defineProperty(ce,"CodeChallengeMethod",{enumerable:!0,get:function(){return Xd.CodeChallengeMethod}});Object.defineProperty(ce,"OAuth2Client",{enumerable:!0,get:function(){return Xd.OAuth2Client}});Object.defineProperty(ce,"ClientAuthentication",{enumerable:!0,get:function(){return Xd.ClientAuthentication}});var IT=Nl();Object.defineProperty(ce,"LoginTicket",{enumerable:!0,get:function(){return IT.LoginTicket}});var NT=cd();Object.defineProperty(ce,"UserRefreshClient",{enumerable:!0,get:function(){return NT.UserRefreshClient}});var BT=xd();Object.defineProperty(ce,"AwsClient",{enumerable:!0,get:function(){return BT.AwsClient}});var MT=vd();Object.defineProperty(ce,"AwsRequestSigner",{enumerable:!0,get:function(){return MT.AwsRequestSigner}});var LT=Sd();Object.defineProperty(ce,"IdentityPoolClient",{enumerable:!0,get:function(){return LT.IdentityPoolClient}});var jT=qd();Object.defineProperty(ce,"ExternalAccountClient",{enumerable:!0,get:function(){return jT.ExternalAccountClient}});var UT=Zn();Object.defineProperty(ce,"BaseExternalAccountClient",{enumerable:!0,get:function(){return UT.BaseExternalAccountClient}});var $T=K0();Object.defineProperty(ce,"DownscopedClient",{enumerable:!0,get:function(){return $T.DownscopedClient}});var Z0=Ud();Object.defineProperty(ce,"PluggableAuthClient",{enumerable:!0,get:function(){return Z0.PluggableAuthClient}});Object.defineProperty(ce,"ExecutableError",{enumerable:!0,get:function(){return Z0.ExecutableError}});var qT=Y0();Object.defineProperty(ce,"PassThroughClient",{enumerable:!0,get:function(){return qT.PassThroughClient}});var zT=new Q0.GoogleAuth;ce.auth=zT});var F_=X((BI,xf)=>{"use strict";var SR=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,TR=/(\w*(\.\w*)*)\..*/;xf.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,P_(r.stack)}};function P_(t){let e=t.match(SR);return e?e[1].split(/[/\\]/).slice(-1)[0].match(TR)[1]:"anonymous"}xf.exports.extractPluginName=P_});var N_=X((MI,I_)=>{"use strict";I_.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var B_=X((LI,Ou)=>{"use strict";var vR=F_(),DR=N_(),RR=0;function Of(t,e={}){let n=!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||(n=!0,e.name=vR(t)+"-auto-"+RR++),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 r=DR(e.name);return!n&&!t[r]&&(t[r]=t),t}Ou.exports=Of;Ou.exports.default=Of;Ou.exports.fastifyPlugin=Of});var Is,Ff=Le(()=>{"use strict";Is=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,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:a}=n||{},u="";if(o){let l=new Date().toISOString();u+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(u+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":u+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?u+=this.toMarkdown(e):u+=String(e);break;case"text":default:typeof e=="object"?u+=JSON.stringify(e,null,2):u+=String(e);break}return a&&Object.keys(a).length>0&&(u+=`
68
68
  `+(this.config.colors?`${this.colors.dim}`:""),u+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(u+=this.colors.reset)),u}toMarkdown(e,n=0){let r=" ".repeat(n);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${r}-
69
69
  ${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
70
70
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${r}${o}:
71
71
  ${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
72
- `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var Ns,Ff=Le(()=>{"use strict";Ns=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 n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},u={data:e};return o&&(u.timestamp=new Date().toISOString()),s&&(u.prefix=s),a&&Object.keys(a).length>0&&(u.metadata=a),u}async sendRequest(e,n,r,o,s){let a=new AbortController,u=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:a.signal});if(clearTimeout(u),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(u),l}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let u=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(f){if(u=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw u}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var Oo,If,B_,Bs,Nf=Le(()=>{"use strict";Oo=require("fs"),If=require("path"),B_=require("os"),Bs=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,B_.tmpdir)();this.baseDir=(0,If.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Oo.existsSync)(this.baseDir)||(0,Oo.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return(0,If.join)(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return(0,Oo.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Bf,Po,M_=Le(()=>{"use strict";Pf();Ff();Nf();Bf=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new Is(e.config);case"webhook":return new Ns(e.config);case"temp-file":return new Bs(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,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,u])=>{try{await u.output(e,r)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},a=e.map(async u=>{let l=this.handlers.get(u);if(!l){console.warn(`[OutputManager] Handler ${u} not found`),s.failed.push(u);return}try{await l.output(n,o)?s.success.push(u):s.failed.push(u)}catch(f){console.error(`[OutputManager] Handler ${u} failed:`,f),s.failed.push(u)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},Po=new Bf});var PR={};hi(PR,{ActiveProbeService:()=>Ps,ConfigService:()=>hr,ProviderHealthStore:()=>Ho,ProviderService:()=>yr,SSEParserTransform:()=>Or,SSESerializerTransform:()=>Fs,TokenizerService:()=>xr,TransformerService:()=>Rr,calculateTokenCount:()=>Rc,default:()=>OR,extractSessionIdFromUserId:()=>Qr,getActiveProbeService:()=>vf,getAllQuotaResults:()=>Tp,getAllRateLimitInfo:()=>kp,getHealthStore:()=>Je,getQuotaAdapter:()=>Tu,getQuotaResult:()=>vi,getRateLimitInfo:()=>Ep,getRuntimeDebugLog:()=>up,initProviderHealthPersistence:()=>Ei,initQuotaStorePersistence:()=>Ti,initRateLimitPersistence:()=>ki,normalizeSessionId:()=>mr,pluginManager:()=>Df,resetActiveProbeService:()=>x_,rewriteStream:()=>Of,router:()=>eo,searchProjectBySession:()=>xc,sessionUsageCache:()=>Ai,setRuntimeDebugLog:()=>ap,startActiveProbe:()=>Du,stopActiveProbe:()=>Ru,storeQuotaResult:()=>Si,tokenSpeedPlugin:()=>Lf});module.exports=zh(PR);var $_=xe(require("fastify"),1),q_=xe(require("@fastify/cors"),1);var zo=require("fs"),hc=require("path"),ep=require("dotenv"),tp=xe(fc(),1),hr=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:(0,hc.join)(process.cwd(),this.options.jsonPath);if((0,zo.existsSync)(e))try{let n=(0,zo.readFileSync)(e,"utf-8"),r=tp.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,hc.join)(process.cwd(),this.options.envPath);if((0,zo.existsSync)(e))try{let n=(0,ep.config)({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}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,n){this.config[e]=n}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 He(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function np(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}var rp=require("undici");function op(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([f,d])=>{d&&s.set(f,d)});let a,u=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let f=new AbortController,d=()=>f.abort();n.signal.addEventListener("abort",d),u.addEventListener("abort",d),a=f.signal}else a=u;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new rp.ProxyAgent(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var MC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Gr={maxBodyLength:4096,maxStreamChunks:100},pc=!1;function ap(t){pc=t}function up(){return pc}function _i(t){return pc||t.get("DEBUG_LOG")===!0}function cp(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Gr:{maxBodyLength:e.maxBodyLength??Gr.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Gr.maxStreamChunks}}function lp(t){let e={};for(let[n,r]of Object.entries(t))MC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function bi(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function dp(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:lp(n.headers),body:bi(r,Gr.maxBodyLength)})}function fp(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:lp(n.headers),...n.body!==void 0?{body:bi(n.body,Gr.maxBodyLength)}:{}})}function sp(t,e,n,r){let o=LC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:bi(r,Gr.maxBodyLength)})}function LC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:bi(r,512)})}}if(e.length)return e.length===1?e[0]:e}function ip(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function hp(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:u,value:l}=await o.read();if(u)break;a+=l;let f=a.split(`
72
+ `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var Ns,If=Le(()=>{"use strict";Ns=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 n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},u={data:e};return o&&(u.timestamp=new Date().toISOString()),s&&(u.prefix=s),a&&Object.keys(a).length>0&&(u.metadata=a),u}async sendRequest(e,n,r,o,s){let a=new AbortController,u=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:a.signal});if(clearTimeout(u),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(u),l}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let u=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(f){if(u=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw u}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var Oo,Nf,M_,Bs,Bf=Le(()=>{"use strict";Oo=require("fs"),Nf=require("path"),M_=require("os"),Bs=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,M_.tmpdir)();this.baseDir=(0,Nf.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Oo.existsSync)(this.baseDir)||(0,Oo.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return(0,Nf.join)(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return(0,Oo.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Mf,Po,L_=Le(()=>{"use strict";Ff();If();Bf();Mf=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new Is(e.config);case"webhook":return new Ns(e.config);case"temp-file":return new Bs(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,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,u])=>{try{await u.output(e,r)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},a=e.map(async u=>{let l=this.handlers.get(u);if(!l){console.warn(`[OutputManager] Handler ${u} not found`),s.failed.push(u);return}try{await l.output(n,o)?s.success.push(u):s.failed.push(u)}catch(f){console.error(`[OutputManager] Handler ${u} failed:`,f),s.failed.push(u)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},Po=new Mf});var FR={};hi(FR,{ActiveProbeService:()=>Ps,ConfigService:()=>hr,ProviderHealthStore:()=>Ho,ProviderService:()=>yr,SSEParserTransform:()=>Or,SSESerializerTransform:()=>Fs,TokenizerService:()=>xr,TransformerService:()=>Rr,calculateTokenCount:()=>xc,default:()=>PR,extractSessionIdFromUserId:()=>Qr,getActiveProbeService:()=>vf,getAllQuotaResults:()=>Dp,getAllRateLimitInfo:()=>Ap,getHealthStore:()=>Je,getQuotaAdapter:()=>Du,getQuotaResult:()=>Ti,getRateLimitInfo:()=>kp,getRuntimeDebugLog:()=>cp,initProviderHealthPersistence:()=>Ei,initQuotaStorePersistence:()=>vi,initRateLimitPersistence:()=>ki,normalizeSessionId:()=>mr,pluginManager:()=>Rf,resetActiveProbeService:()=>O_,rewriteStream:()=>Pf,router:()=>eo,searchProjectBySession:()=>Oc,sessionUsageCache:()=>Ai,setRuntimeDebugLog:()=>up,startActiveProbe:()=>Ru,stopActiveProbe:()=>xu,storeQuotaResult:()=>Si,tokenSpeedPlugin:()=>jf});module.exports=Hh(FR);var q_=xe(require("fastify"),1),z_=xe(require("@fastify/cors"),1);var zo=require("fs"),pc=require("path"),tp=require("dotenv"),np=xe(hc(),1),hr=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:(0,pc.join)(process.cwd(),this.options.jsonPath);if((0,zo.existsSync)(e))try{let n=(0,zo.readFileSync)(e,"utf-8"),r=np.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,pc.join)(process.cwd(),this.options.envPath);if((0,zo.existsSync)(e))try{let n=(0,tp.config)({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}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,n){this.config[e]=n}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 He(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function rp(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}var op=require("undici");function sp(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([f,d])=>{d&&s.set(f,d)});let a,u=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let f=new AbortController,d=()=>f.abort();n.signal.addEventListener("abort",d),u.addEventListener("abort",d),a=f.signal}else a=u;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new op.ProxyAgent(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var LC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Gr={maxBodyLength:4096,maxStreamChunks:100},mc=!1;function up(t){mc=t}function cp(){return mc}function _i(t){return mc||t.get("DEBUG_LOG")===!0}function lp(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Gr:{maxBodyLength:e.maxBodyLength??Gr.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Gr.maxStreamChunks}}function dp(t){let e={};for(let[n,r]of Object.entries(t))LC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function bi(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function fp(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:dp(n.headers),body:bi(r,Gr.maxBodyLength)})}function hp(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:dp(n.headers),...n.body!==void 0?{body:bi(n.body,Gr.maxBodyLength)}:{}})}function ip(t,e,n,r){let o=jC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:bi(r,Gr.maxBodyLength)})}function jC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:bi(r,512)})}}if(e.length)return e.length===1?e[0]:e}function ap(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function pp(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:u,value:l}=await o.read();if(u)break;a+=l;let f=a.split(`
73
73
 
74
- `);a=f.pop()||"";for(let d of f)d.trim()&&(s<r.maxStreamChunks?sp(e,n,s,d):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&sp(e,n,s,a.trim()),s++),ip(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),ip(e,n,s)}finally{o.releaseLock()}})()}var Ci="2.3.18";Wn();var Sn=require("fs"),kc=require("path"),wp=require("@wengine-ai/claude-code-router-shared"),wc=(0,kc.join)(wp.HOME_DIR,"runtime"),Ec=(0,kc.join)(wc,"rate-limit.json"),Vr=new Map,_p=!1,GC=null,JC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],VC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],KC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Wo(t,e,n){let r=u=>{if(n instanceof Headers)return n.get(u);let l=Object.keys(n).find(f=>f.toLowerCase()===u);return l?n[l]:null},o=Cc(r,JC),s=Cc(r,VC),a=Cc(r,KC);(o||s||a)&&Vr.set(t,{provider:t,remaining:bp(o),limit:bp(s),reset:YC(a),capturedAt:Date.now()})}function Ep(t){return Vr.get(t)}function kp(){return Array.from(Vr.values())}function Cc(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function bp(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function YC(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=QC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function QC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function XC(){try{if(!(0,Sn.existsSync)(Ec))return;let t=JSON.parse((0,Sn.readFileSync)(Ec,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Vr.set(n.provider,n)}}catch{}}function Cp(){try{if(Vr.size===0)return;(0,Sn.existsSync)(wc)||(0,Sn.mkdirSync)(wc,{recursive:!0}),(0,Sn.writeFileSync)(Ec,JSON.stringify(Array.from(Vr.values()),null,2),"utf-8")}catch{}}function ki(){_p||(_p=!0,XC(),GC=setInterval(Cp,6e4),process.on("exit",Cp))}wi();var Kr=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let n=e?.input_tokens??e?.prompt_tokens??0,r=e?.output_tokens??e?.completion_tokens??0,o=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:n,output_tokens:r,total_tokens:e?.total_tokens??n+r,input_tokens_details:{cached_tokens:o,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:o,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let[r,o]=e.body.tee(),s=r.getReader(),a="";try{let{value:g,done:_}=await s.read();!_&&g&&(a=new TextDecoder().decode(g))}finally{s.releaseLock()}if(r.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}let f=this.prependToStream(a,o),d=new TextDecoder,p=new TextEncoder,m="",b=!1,w=this,y=new ReadableStream({async start(g){let _=f.getReader(),A=-1,C="",v=T=>(T!==C&&(A++,C=T),A);try{for(;;){let{done:T,value:R}=await _.read();if(T){b||g.enqueue(p.encode(`data: [DONE]
74
+ `);a=f.pop()||"";for(let d of f)d.trim()&&(s<r.maxStreamChunks?ip(e,n,s,d):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&ip(e,n,s,a.trim()),s++),ap(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),ap(e,n,s)}finally{o.releaseLock()}})()}var Ci="2.3.19";Wn();var Sn=require("fs"),Ac=require("path"),Ep=require("@wengine-ai/claude-code-router-shared"),Ec=(0,Ac.join)(Ep.HOME_DIR,"runtime"),kc=(0,Ac.join)(Ec,"rate-limit.json"),Vr=new Map,bp=!1,JC=null,VC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],KC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],YC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Wo(t,e,n){let r=u=>{if(n instanceof Headers)return n.get(u);let l=Object.keys(n).find(f=>f.toLowerCase()===u);return l?n[l]:null},o=wc(r,VC),s=wc(r,KC),a=wc(r,YC);(o||s||a)&&Vr.set(t,{provider:t,remaining:Cp(o),limit:Cp(s),reset:QC(a),capturedAt:Date.now()})}function kp(t){return Vr.get(t)}function Ap(){return Array.from(Vr.values())}function wc(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function Cp(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function QC(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=XC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function XC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function ZC(){try{if(!(0,Sn.existsSync)(kc))return;let t=JSON.parse((0,Sn.readFileSync)(kc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Vr.set(n.provider,n)}}catch{}}function wp(){try{if(Vr.size===0)return;(0,Sn.existsSync)(Ec)||(0,Sn.mkdirSync)(Ec,{recursive:!0}),(0,Sn.writeFileSync)(kc,JSON.stringify(Array.from(Vr.values()),null,2),"utf-8")}catch{}}function ki(){bp||(bp=!0,ZC(),JC=setInterval(wp,6e4),process.on("exit",wp))}wi();var Kr=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let n=e?.input_tokens??e?.prompt_tokens??0,r=e?.output_tokens??e?.completion_tokens??0,o=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:n,output_tokens:r,total_tokens:e?.total_tokens??n+r,input_tokens_details:{cached_tokens:o,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:o,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let[r,o]=e.body.tee(),s=r.getReader(),a="";try{let{value:g,done:_}=await s.read();!_&&g&&(a=new TextDecoder().decode(g))}finally{s.releaseLock()}if(r.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}let f=this.prependToStream(a,o),d=new TextDecoder,h=new TextEncoder,m="",C=!1,w=this,y=new ReadableStream({async start(g){let _=f.getReader(),E=-1,b="",S=v=>(v!==b&&(E++,b=v),E);try{for(;;){let{done:v,value:R}=await _.read();if(v){C||g.enqueue(h.encode(`data: [DONE]
75
75
 
76
- `));break}let $=d.decode(R,{stream:!0});m+=$;let G=m.split(/\r?\n/);m=G.pop()||"";for(let P of G)if(P.trim())try{if(P.startsWith("event: "))continue;if(P.startsWith("data: ")){let K=P.slice(5).trim();if(K==="[DONE]"){b=!0,g.enqueue(p.encode(`data: [DONE]
76
+ `));break}let $=d.decode(R,{stream:!0});m+=$;let H=m.split(/\r?\n/);m=H.pop()||"";for(let P of H)if(P.trim())try{if(P.startsWith("event: "))continue;if(P.startsWith("data: ")){let K=P.slice(5).trim();if(K==="[DONE]"){C=!0,g.enqueue(h.encode(`data: [DONE]
77
77
 
78
- `));continue}try{let z=JSON.parse(K);if(z.type==="response.output_text.delta"){let Y={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:v(z.type),delta:{content:z.delta||""},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
78
+ `));continue}try{let q=JSON.parse(K);if(q.type==="response.output_text.delta"){let Y={id:q.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model,choices:[{index:S(q.type),delta:{content:q.delta||""},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
79
79
 
80
- `))}else if(z.type==="response.output_item.added"&&z.item?.type==="function_call"){let Y={id:z.item.call_id||z.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:v(z.type),delta:{role:"assistant",tool_calls:[{index:0,id:z.item.call_id||z.item.id,function:{name:z.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
80
+ `))}else if(q.type==="response.output_item.added"&&q.item?.type==="function_call"){let Y={id:q.item.call_id||q.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model||"gpt-5-codex-",choices:[{index:S(q.type),delta:{role:"assistant",tool_calls:[{index:0,id:q.item.call_id||q.item.id,function:{name:q.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
81
81
 
82
- `))}else if(z.type==="response.output_item.added"&&z.item?.type==="message"){let Y=[];(z.item.content||[]).forEach(ee=>{ee.type==="output_text"&&Y.push({type:"text",text:ee.text||""})});let Q={role:"assistant"};if(Y.length===1&&Y[0].type==="text"?Q.content=Y[0].text:Y.length>0&&(Q.content=Y),Q.content){let ee={id:z.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:v(z.type),delta:Q,finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(ee)}
82
+ `))}else if(q.type==="response.output_item.added"&&q.item?.type==="message"){let Y=[];(q.item.content||[]).forEach(ee=>{ee.type==="output_text"&&Y.push({type:"text",text:ee.text||""})});let Q={role:"assistant"};if(Y.length===1&&Y[0].type==="text"?Q.content=Y[0].text:Y.length>0&&(Q.content=Y),Q.content){let ee={id:q.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model,choices:[{index:S(q.type),delta:Q,finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(ee)}
83
83
 
84
- `))}}else if(z.type==="response.output_text.annotation.added"){let Y={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex",choices:[{index:v(z.type),delta:{annotations:[{type:"url_citation",url_citation:{url:z.annotation?.url||"",title:z.annotation?.title||"",content:"",start_index:z.annotation?.start_index||0,end_index:z.annotation?.end_index||0}}]},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
84
+ `))}}else if(q.type==="response.output_text.annotation.added"){let Y={id:q.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model||"gpt-5-codex",choices:[{index:S(q.type),delta:{annotations:[{type:"url_citation",url_citation:{url:q.annotation?.url||"",title:q.annotation?.title||"",content:"",start_index:q.annotation?.start_index||0,end_index:q.annotation?.end_index||0}}]},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
85
85
 
86
- `))}else if(z.type==="response.function_call_arguments.delta"){let Y={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:v(z.type),delta:{tool_calls:[{index:0,function:{arguments:z.delta||""}}]},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
86
+ `))}else if(q.type==="response.function_call_arguments.delta"){let Y={id:q.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model||"gpt-5-codex-",choices:[{index:S(q.type),delta:{tool_calls:[{index:0,function:{arguments:q.delta||""}}]},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
87
87
 
88
- `))}else if(z.type==="response.completed"){let Y=z.response?.output?.some(ee=>ee.type==="function_call")?"tool_calls":"stop",Q={id:z.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:Y}]};g.enqueue(p.encode(`data: ${JSON.stringify(Q)}
88
+ `))}else if(q.type==="response.completed"){let Y=q.response?.output?.some(ee=>ee.type==="function_call")?"tool_calls":"stop",Q={id:q.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:Y}]};g.enqueue(h.encode(`data: ${JSON.stringify(Q)}
89
89
 
90
- `)),b=!0}else if(z.type==="response.reasoning_summary_text.delta"){let Y={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:v(z.type),delta:{thinking:{content:z.delta||""}},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
90
+ `)),C=!0}else if(q.type==="response.reasoning_summary_text.delta"){let Y={id:q.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model,choices:[{index:S(q.type),delta:{thinking:{content:q.delta||""}},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
91
91
 
92
- `))}else if(z.type==="response.reasoning_summary_part.done"&&z.part){let Y={id:z.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:z.response?.model,choices:[{index:A,delta:{thinking:{signature:z.item_id}},finish_reason:null}]};g.enqueue(p.encode(`data: ${JSON.stringify(Y)}
92
+ `))}else if(q.type==="response.reasoning_summary_part.done"&&q.part){let Y={id:q.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:q.response?.model,choices:[{index:E,delta:{thinking:{signature:q.item_id}},finish_reason:null}]};g.enqueue(h.encode(`data: ${JSON.stringify(Y)}
93
93
 
94
- `))}}catch{g.enqueue(p.encode(P+`
95
- `))}}else g.enqueue(p.encode(P+`
96
- `))}catch(K){console.error("Error processing line:",P,K),g.enqueue(p.encode(P+`
97
- `))}}m.trim()&&g.enqueue(p.encode(m+`
98
- `)),b||g.enqueue(p.encode(`data: [DONE]
94
+ `))}}catch{g.enqueue(h.encode(P+`
95
+ `))}}else g.enqueue(h.encode(P+`
96
+ `))}catch(K){console.error("Error processing line:",P,K),g.enqueue(h.encode(P+`
97
+ `))}}m.trim()&&g.enqueue(h.encode(m+`
98
+ `)),C||g.enqueue(h.encode(`data: [DONE]
99
99
 
100
- `))}catch(T){console.error("Stream error:",T),g.error(T)}finally{try{_.releaseLock()}catch(T){console.error("Error releasing reader lock:",T)}g.close()}}});return new Response(y,{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,n){let r={...e};if(delete r.cache_control,e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[o,s]=e.body.tee(),a=o.getReader(),u="";try{let{value:m,done:b}=await a.read();!b&&m&&(u=new TextDecoder().decode(m))}finally{a.releaseLock()}o.cancel().catch(()=>{});let l=u.includes("message_start")||u.includes("content_block_start"),f=u.includes("chat.completion.chunk");if(u.includes("response.created")||u.includes("response.output_text.delta")||u.includes("response.in_progress")||u.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(f&&!l){let m=this.convertOpenAIChatStreamToResponsesAPI(s,n);return new Response(m,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,n);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let o=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(o)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,n){let o=new TextEncoder().encode(e),s=n.getReader(),a=!1;return new ReadableStream({async pull(u){a||(a=!0,u.enqueue(o));try{let{done:l,value:f}=await s.read();l?u.close():u.enqueue(f)}catch(l){u.error(l)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,u=0,l=!1,f=!1,d="",p=-1,m=[],b=(y,g)=>o.encode(`event: ${y}
100
+ `))}catch(v){console.error("Stream error:",v),g.error(v)}finally{try{_.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}g.close()}}});return new Response(y,{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,n){let r={...e};if(delete r.cache_control,e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[o,s]=e.body.tee(),a=o.getReader(),u="";try{let{value:m,done:C}=await a.read();!C&&m&&(u=new TextDecoder().decode(m))}finally{a.releaseLock()}o.cancel().catch(()=>{});let l=u.includes("message_start")||u.includes("content_block_start"),f=u.includes("chat.completion.chunk");if(u.includes("response.created")||u.includes("response.output_text.delta")||u.includes("response.in_progress")||u.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(f&&!l){let m=this.convertOpenAIChatStreamToResponsesAPI(s,n);return new Response(m,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let h=this.convertAnthropicStreamToResponsesAPI(s,n);return new Response(h,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let o=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(o)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,n){let o=new TextEncoder().encode(e),s=n.getReader(),a=!1;return new ReadableStream({async pull(u){a||(a=!0,u.enqueue(o));try{let{done:l,value:f}=await s.read();l?u.close():u.enqueue(f)}catch(l){u.error(l)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,u=0,l=!1,f=!1,d="",h=-1,m=[],C=(y,g)=>o.encode(`event: ${y}
101
101
  data: ${JSON.stringify(g)}
102
102
 
103
- `),w=(y,g=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:y,model:s,output:g,usage:this.buildResponsesUsage()});return new ReadableStream({async start(y){try{let g=e.getReader(),_="",A=!1,C=v=>{if(!A){A=!0;for(let T of m)if(T.type==="function_call"){let R=m.indexOf(T);y.enqueue(b("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:R,arguments:T.arguments||""})),T.status="completed",y.enqueue(b("response.output_item.done",{type:"response.output_item.done",output_index:R,item:T}))}for(let T of m)if(T.type==="message"){let R=m.indexOf(T);T.status="completed",y.enqueue(b("response.output_item.done",{type:"response.output_item.done",output_index:R,item:T}))}y.enqueue(b("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:v?.model||s,output:m.slice(),usage:v?.usage?{...this.buildResponsesUsage(v.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:v,value:T}=await g.read();if(v)break;_+=r.decode(T,{stream:!0});let R=_.split(`
104
- `);_=R.pop()||"";for(let $ of R){let G=$.trim();if(!G||G.startsWith("event:")||!G.startsWith("data:"))continue;let P=G.slice(5).trim();if(P==="[DONE]"){C({}),y.enqueue(o.encode(`data: [DONE]
103
+ `),w=(y,g=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:y,model:s,output:g,usage:this.buildResponsesUsage()});return new ReadableStream({async start(y){try{let g=e.getReader(),_="",E=!1,b=S=>{if(!E){E=!0;for(let v of m)if(v.type==="function_call"){let R=m.indexOf(v);y.enqueue(C("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:R,arguments:v.arguments||""})),v.status="completed",y.enqueue(C("response.output_item.done",{type:"response.output_item.done",output_index:R,item:v}))}for(let v of m)if(v.type==="message"){let R=m.indexOf(v);v.status="completed",y.enqueue(C("response.output_item.done",{type:"response.output_item.done",output_index:R,item:v}))}y.enqueue(C("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:S?.model||s,output:m.slice(),usage:S?.usage?{...this.buildResponsesUsage(S.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:S,value:v}=await g.read();if(S)break;_+=r.decode(v,{stream:!0});let R=_.split(`
104
+ `);_=R.pop()||"";for(let $ of R){let H=$.trim();if(!H||H.startsWith("event:")||!H.startsWith("data:"))continue;let P=H.slice(5).trim();if(P==="[DONE]"){b({}),y.enqueue(o.encode(`data: [DONE]
105
105
 
106
- `));continue}let K;try{K=JSON.parse(P)}catch{continue}l||(l=!0,y.enqueue(b("response.created",{type:"response.created",response:w("in_progress")})),y.enqueue(b("response.in_progress",{type:"response.in_progress",response:w("in_progress")})));let z=K.choices?.[0];if(!z)continue;let Y=z.delta;if(Y?.content){if(!f){f=!0;let Q=u++,ee={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};m.push(ee),y.enqueue(b("response.output_item.added",{type:"response.output_item.added",output_index:Q,item:ee}))}y.enqueue(b("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:u-1,content_index:0,delta:Y.content}))}if(Array.isArray(Y?.tool_calls))for(let Q of Y.tool_calls){if(Q.id){d=Q.id,p=u++;let ee={id:Q.id,type:"function_call",status:"in_progress",call_id:Q.id,name:Q.function?.name||"",arguments:""};m.push(ee),y.enqueue(b("response.output_item.added",{type:"response.output_item.added",output_index:p,item:ee}))}if(Q.function?.arguments){y.enqueue(b("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:d,output_index:p,delta:Q.function.arguments}));let ee=m.find(oe=>oe.call_id===d);ee&&(ee.arguments+=Q.function.arguments)}}z.finish_reason&&C(K)}}A||C({}),y.close()}catch(g){y.error(g)}}})}convertAnthropicStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,u="",l="",f=-1,d="",p="",m="",b=-1,w="",y="",g=-1,_=0,A=!1,C=!1,v=!1,T=!1,R=null,$=[],G=(ee,oe)=>o.encode(`event: ${ee}
106
+ `));continue}let K;try{K=JSON.parse(P)}catch{continue}l||(l=!0,y.enqueue(C("response.created",{type:"response.created",response:w("in_progress")})),y.enqueue(C("response.in_progress",{type:"response.in_progress",response:w("in_progress")})));let q=K.choices?.[0];if(!q)continue;let Y=q.delta;if(Y?.content){if(!f){f=!0;let Q=u++,ee={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};m.push(ee),y.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:Q,item:ee}))}y.enqueue(C("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:u-1,content_index:0,delta:Y.content}))}if(Array.isArray(Y?.tool_calls))for(let Q of Y.tool_calls){if(Q.id){d=Q.id,h=u++;let ee={id:Q.id,type:"function_call",status:"in_progress",call_id:Q.id,name:Q.function?.name||"",arguments:""};m.push(ee),y.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:h,item:ee}))}if(Q.function?.arguments){y.enqueue(C("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:d,output_index:h,delta:Q.function.arguments}));let ee=m.find(oe=>oe.call_id===d);ee&&(ee.arguments+=Q.function.arguments)}}q.finish_reason&&b(K)}}E||b({}),y.close()}catch(g){y.error(g)}}})}convertAnthropicStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,u="",l="",f=-1,d="",h="",m="",C=-1,w="",y="",g=-1,_=0,E=!1,b=!1,S=!1,v=!1,R=null,$=[],H=(ee,oe)=>o.encode(`event: ${ee}
107
107
  data: ${JSON.stringify(oe)}
108
108
 
109
- `),P=(ee,oe=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:ee,model:s,output:oe,usage:this.buildResponsesUsage()}),K=()=>{A||(A=!0,Q.enqueue(G("response.created",{type:"response.created",response:P("in_progress")})),Q.enqueue(G("response.in_progress",{type:"response.in_progress",response:P("in_progress")})))},z=(ee,oe)=>{Q.enqueue(G("response.output_item.done",{type:"response.output_item.done",output_index:ee,item:{...oe,status:"completed"}}))},Y=ee=>{if(!T){if(T=!0,C){let oe=$.find(se=>se.type==="message");oe&&(oe.content=[{type:"output_text",text:u}],oe.status="completed")}for(let oe of $)oe.type==="function_call"&&(oe.status="completed");return G("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:$,usage:ee?{...this.buildResponsesUsage(ee)}:this.buildResponsesUsage()}})}},Q;return new ReadableStream({async start(ee){Q=ee;try{let oe=e.getReader(),se="";for(;;){let{done:J,value:Z}=await oe.read();if(J)break;se+=r.decode(Z,{stream:!0});let ue=se.split(`
110
- `);se=ue.pop()||"";for(let je of ue){let Ce=je.trim();if(!Ce||Ce.startsWith("event:")||!Ce.startsWith("data:"))continue;let V=Ce.slice(5).trim();if(V==="[DONE]")continue;let ae;try{ae=JSON.parse(V)}catch{continue}if(ae.type==="message_start"&&(a=ae.message?.id||a,K()),ae.type==="content_block_start"){let te=ae.content_block;if(R=te?.type||null,te?.type==="tool_use"){d=te.id||"",p=te.name||"",m="",b=_++;let ve={id:d,type:"function_call",status:"in_progress",call_id:d,name:p,arguments:""};$.push(ve),Q.enqueue(G("response.output_item.added",{type:"response.output_item.added",output_index:b,item:ve}))}if(te?.type==="thinking"&&(w=te.thinking||"",!v)){v=!0,g=_++,y=`rs_${a}`;let ve={id:y,type:"reasoning",status:"in_progress",summary:[]};$.push(ve),Q.enqueue(G("response.output_item.added",{type:"response.output_item.added",output_index:g,item:ve}))}if(te?.type==="text"&&(u=te?.text||"",!C)){C=!0,f=_++,l=`${a}_msg`;let ve={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(ve),Q.enqueue(G("response.output_item.added",{type:"response.output_item.added",output_index:f,item:ve}))}}if(ae.type==="content_block_delta"){let te=ae.delta;if(te?.type==="text_delta"){if(!C){C=!0,f=_++,l=`${a}_msg`;let ve={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(ve),Q.enqueue(G("response.output_item.added",{type:"response.output_item.added",output_index:f,item:ve}))}u+=te.text||"",Q.enqueue(G("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:f,content_index:0,delta:te.text||""}))}te?.type==="thinking_delta"&&(w+=te.thinking||"",Q.enqueue(G("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:y||`rs_${a}`,output_index:g>=0?g:0,summary_index:0,delta:te.thinking||""}))),te?.type==="input_json_delta"&&(m+=te.partial_json||"",Q.enqueue(G("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:d||"call_0",output_index:b>=0?b:0,delta:te.partial_json||""})))}if(ae.type==="content_block_stop"){if(R==="tool_use"&&d){Q.enqueue(G("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:d,output_index:b,arguments:m}));let te=$.find(ve=>ve.call_id===d);te&&(te.arguments=m,te.status="completed"),te&&z(b,te)}if(R==="text"&&C){Q.enqueue(G("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:f,content_index:0,text:u}));let te=$.find(ve=>ve.type==="message");te&&(te.content=[{type:"output_text",text:u}],z(f,te))}if(R==="thinking"&&v){let te=$.find(ve=>ve.type==="reasoning");te&&(te.summary=[{type:"summary_text",text:w}],z(g,te))}R=null}if(ae.type==="message_delta"){let te=Y(ae.usage);te&&Q.enqueue(te)}if(ae.type==="message_stop"){let te=Y();te&&Q.enqueue(te),Q.enqueue(o.encode(`data: [DONE]
109
+ `),P=(ee,oe=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:ee,model:s,output:oe,usage:this.buildResponsesUsage()}),K=()=>{E||(E=!0,Q.enqueue(H("response.created",{type:"response.created",response:P("in_progress")})),Q.enqueue(H("response.in_progress",{type:"response.in_progress",response:P("in_progress")})))},q=(ee,oe)=>{Q.enqueue(H("response.output_item.done",{type:"response.output_item.done",output_index:ee,item:{...oe,status:"completed"}}))},Y=ee=>{if(!v){if(v=!0,b){let oe=$.find(se=>se.type==="message");oe&&(oe.content=[{type:"output_text",text:u}],oe.status="completed")}for(let oe of $)oe.type==="function_call"&&(oe.status="completed");return H("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:$,usage:ee?{...this.buildResponsesUsage(ee)}:this.buildResponsesUsage()}})}},Q;return new ReadableStream({async start(ee){Q=ee;try{let oe=e.getReader(),se="";for(;;){let{done:J,value:Z}=await oe.read();if(J)break;se+=r.decode(Z,{stream:!0});let ue=se.split(`
110
+ `);se=ue.pop()||"";for(let je of ue){let Ce=je.trim();if(!Ce||Ce.startsWith("event:")||!Ce.startsWith("data:"))continue;let V=Ce.slice(5).trim();if(V==="[DONE]")continue;let ae;try{ae=JSON.parse(V)}catch{continue}if(ae.type==="message_start"&&(a=ae.message?.id||a,K()),ae.type==="content_block_start"){let te=ae.content_block;if(R=te?.type||null,te?.type==="tool_use"){d=te.id||"",h=te.name||"",m="",C=_++;let Te={id:d,type:"function_call",status:"in_progress",call_id:d,name:h,arguments:""};$.push(Te),Q.enqueue(H("response.output_item.added",{type:"response.output_item.added",output_index:C,item:Te}))}if(te?.type==="thinking"&&(w=te.thinking||"",!S)){S=!0,g=_++,y=`rs_${a}`;let Te={id:y,type:"reasoning",status:"in_progress",summary:[]};$.push(Te),Q.enqueue(H("response.output_item.added",{type:"response.output_item.added",output_index:g,item:Te}))}if(te?.type==="text"&&(u=te?.text||"",!b)){b=!0,f=_++,l=`${a}_msg`;let Te={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(Te),Q.enqueue(H("response.output_item.added",{type:"response.output_item.added",output_index:f,item:Te}))}}if(ae.type==="content_block_delta"){let te=ae.delta;if(te?.type==="text_delta"){if(!b){b=!0,f=_++,l=`${a}_msg`;let Te={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};$.push(Te),Q.enqueue(H("response.output_item.added",{type:"response.output_item.added",output_index:f,item:Te}))}u+=te.text||"",Q.enqueue(H("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:f,content_index:0,delta:te.text||""}))}te?.type==="thinking_delta"&&(w+=te.thinking||"",Q.enqueue(H("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:y||`rs_${a}`,output_index:g>=0?g:0,summary_index:0,delta:te.thinking||""}))),te?.type==="input_json_delta"&&(m+=te.partial_json||"",Q.enqueue(H("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:d||"call_0",output_index:C>=0?C:0,delta:te.partial_json||""})))}if(ae.type==="content_block_stop"){if(R==="tool_use"&&d){Q.enqueue(H("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:d,output_index:C,arguments:m}));let te=$.find(Te=>Te.call_id===d);te&&(te.arguments=m,te.status="completed"),te&&q(C,te)}if(R==="text"&&b){Q.enqueue(H("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:f,content_index:0,text:u}));let te=$.find(Te=>Te.type==="message");te&&(te.content=[{type:"output_text",text:u}],q(f,te))}if(R==="thinking"&&S){let te=$.find(Te=>Te.type==="reasoning");te&&(te.summary=[{type:"summary_text",text:w}],q(g,te))}R=null}if(ae.type==="message_delta"){let te=Y(ae.usage);te&&Q.enqueue(te)}if(ae.type==="message_stop"){let te=Y();te&&Q.enqueue(te),Q.enqueue(o.encode(`data: [DONE]
111
111
 
112
- `))}}}K();let he=Y();he&&Q.enqueue(he),se="",Q.close()}catch(oe){Q.error(oe)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let n=e.output?.find(f=>f.type==="message"),r=e.output?.find(f=>f.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(f=>({type:"url_citation",url_citation:{url:f.url||"",title:f.title||"",content:"",start_index:f.start_index||0,end_index:f.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,u=null;if(n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let f=[],d=[];if(n.content.forEach(p=>{if(p.type==="output_text")f.push(p.text||"");else if(p.type==="output_image"){let m=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});m&&d.push(m)}else if(p.type==="output_image_base64"){let m=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});m&&d.push(m)}}),d.length>0){let p=[];f.length>0&&p.push({type:"text",text:f.join("")}),p.push(...d),s=p}else s=f.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.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:s||null,tool_calls:a,thinking:u,annotations:o},logprobs:null,finish_reason:a?"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,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}: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 Op=require("tiktoken");var Ac=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Ai=new Ac(100);var Di=require("fs/promises"),Oi=require("fs/promises"),Ri=require("path"),Zr=require("@wengine-ai/claude-code-router-shared");Wn();var vn=require("fs"),Tc=require("path"),vp=require("@wengine-ai/claude-code-router-shared"),Sc=(0,Tc.join)(vp.HOME_DIR,"runtime"),vc=(0,Tc.join)(Sc,"quota-store.json"),Yr=new Map,Ap=!1,ZC=null;function Si(t,e){t&&Yr.set(t,{...e,provider:t,capturedAt:Date.now()})}function vi(t){let e=Yr.get(t);return e?{...e}:void 0}function Tp(){return Array.from(Yr.values()).map(t=>({...t}))}function ew(){try{if(!(0,vn.existsSync)(vc))return;let t=JSON.parse((0,vn.readFileSync)(vc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;Yr.set(n.provider,n)}}catch{}}function Sp(){try{if(Yr.size===0)return;(0,vn.existsSync)(Sc)||(0,vn.mkdirSync)(Sc,{recursive:!0}),(0,vn.writeFileSync)(vc,JSON.stringify(Array.from(Yr.values()),null,2),"utf-8")}catch{}}function Ti(){Ap||(Ap=!0,ew(),ZC=setInterval(Sp,6e4),process.on("exit",Sp))}wi();var tw=/^[A-Za-z0-9_-]+$/;function mr(t){if(typeof t!="string")return;let e=t.trim();if(!(!e||!tw.test(e)))return e}function Qr(t){if(!t)return;if(typeof t=="object")return mr(t.session_id??t.sessionId);if(typeof t!="string")return;let e=t.trim();if(!e)return;try{let o=JSON.parse(e),s=mr(o?.session_id??o?.sessionId);if(s)return s}catch{}let n="_session_",r=e.lastIndexOf(n);if(r!==-1)return mr(e.slice(r+n.length))}var Tn=(0,Op.get_encoding)("cl100k_base"),Rc=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=Tn.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=Tn.encode(s.text).length:s.type==="tool_use"?r+=Tn.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=Tn.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=Tn.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=Tn.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=Tn.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=Tn.encode(o.name+o.description).length),o.input_schema&&(r+=Tn.encode(JSON.stringify(o.input_schema)).length)}),r},Pp=async(t,e)=>{if(t.sessionId){let n=await xc(t.sessionId);if(n){let r=(0,Ri.join)(Zr.HOME_DIR,n,"config.json"),o=(0,Ri.join)(Zr.HOME_DIR,n,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,Di.readFile)(o,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}try{let s=JSON.parse(await(0,Di.readFile)(r,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}}}};function xi(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function Fp(t){let e=xi(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n,isCcrAlias:!0};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n,isCcrAlias:!1}:{family:null,extended:n,isCcrAlias:!1}}function nw(t,e){if(!e||!t)return null;let n=xi(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=Fp(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=xi(o);if(a&&n.includes(a))return s}return null}function Ip(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function Dc(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function Go(t,e,n){let r=t.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!r||r.enabled===!1)return null;let o=r.models?.find(s=>String(s).toLowerCase()===n.toLowerCase());return o?{provider:r,model:String(o)}:null}function tt(t,e,n,r,o){let s=Dc(t);if(!s)return t;let{providerName:a,routeModel:u}=s,l=Go(e,a,u);if(!l){if(o===!0&&r&&!n){let d=Jr(),p=d.getPromotion(a,u,r,e);if(p){let m=Dc(p);if(m){let b=Go(e,m.providerName,m.routeModel);if(b)return`${b.provider.name},${b.model}`}d.clear(a,u,r)}}return null}if(o===!0&&r&&!n){let d=Jr(),p=d.getPromotion(a,u,r,e);if(p){let m=Dc(p);if(m){let b=Go(e,m.providerName,m.routeModel);if(b)return`${b.provider.name},${b.model}`}d.clear(a,u,r)}}if(!n&&!Je().isAvailable(l.provider.name,l.model))return null;let f=vi(l.provider.name);if(f){let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,p=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||p)return null}return`${l.provider.name},${l.model}`}function $t(t,e,n,r,o){let s=Je(),a=[n?.[t],r?.[t]];for(let u of a)if(!(!Array.isArray(u)||u.length===0))for(let l of u){let f=tt(l,e);if(f)return f}return null}function rw(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function ow(t){let e=xi(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(e))}function sw(t,e,n,r,o,s,a,u,l){let f=n.longContextThreshold??l??6e4,d=Math.max(e,Ip(o)),p=t.modelFamily;if((s||d>2e5)&&n.extendedContext){let y=tt(n.extendedContext,r,!1,"extendedContext",u);if(y)return t.log.info(`Family: using extended context model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:y,scenarioType:"extendedContext",isFallback:!1};let g=u?$t("extendedContext",r,n.fallback,a,p):null;if(g)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:g,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(d>f&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let y=n.longContext?tt(n.longContext,r,!1,"longContext",u):null;if(y)return t.log.info(`Family: using long context model, tokens: ${d}, estimated: ${e}`),{model:y,scenarioType:"longContext",isFallback:!1};let g=u?$t("longContext",r,n.fallback,a,p):null;if(g)return t.log.info(`Family: using long context fallback model, tokens: ${d}, estimated: ${e}`),{model:g,scenarioType:"longContext",isFallback:!0};t.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(t.body.tools)&&t.body.tools.some(y=>y.type?.startsWith("web_search"))&&n.webSearch){let y=tt(n.webSearch,r,!1,"webSearch",u);if(y)return{model:y,scenarioType:"webSearch",isFallback:!1};let g=u?$t("webSearch",r,n.fallback,a,p):null;if(g)return t.log.info("Family: using webSearch fallback model"),{model:g,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking?.type==="enabled"&&n.think){let y=tt(n.think,r,!1,"think",u);if(y)return{model:y,scenarioType:"think",isFallback:!1};let g=u?$t("think",r,n.fallback,a,p):null;if(g)return t.log.info("Family: using think fallback model"),{model:g,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let y=tt(n.default,r,!1,"default",u);if(y)return{model:y,scenarioType:"default",isFallback:!1};let g=u?$t("default",r,n.fallback,a,p):null;if(g)return t.log.info("Family: using default fallback model"),{model:g,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var iw=async(t,e,n,r)=>{let o=await Pp(t,n),s=n.get("providers")||[],a=o||n.get("Router"),u=a?.enableFallback===!0,l=u?a?.fallback||n.get("fallback"):void 0;if(t.body.model.includes(",")){let A=tt(t.body.model,s,!1,"default",u);if(A)return{model:A,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let C=u?$t("default",s,void 0,l):null;if(C)return t.log.info(`Using fallback for explicit model: ${C}`),{model:C,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:f,extended:d,isCcrAlias:p}=Fp(t.body.model),m=a?.families?.[f||""];if(m&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${f}${d?" (1M)":""}`),t.modelFamily=f,t.familyFallback=m.fallback;let A=sw(t,e,m,s,r,d,l,u,a?.longContextThreshold);if(A)return{model:A.model,scenarioType:A.scenarioType}}let b=p&&!a?.enableFamilyRouting?null:nw(t.body.model,a?.models);if(b){let A=tt(b,s,!1,"modelMapping",u);if(A)return t.log.info(`Using mapped model for ${t.body.model}: ${b}`),{model:A,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${b} unavailable (fail pool), skipping`)}let w=Math.max(e,Ip(r)),y=a?.extendedContextThreshold||2e5;if(w>y&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${w}, estimated: ${e}, threshold: ${y}`);let A=tt(a.extendedContext,s,!1,"extendedContext",u);if(A)return{model:A,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let C=u?$t("extendedContext",s,void 0,l):null;if(C)return{model:C,scenarioType:"extendedContext"}}let g=a?.longContextThreshold||6e4;if(w>g&&a?.longContext){t.log.info(`Using long context model due to token count: ${w}, estimated: ${e}, threshold: ${g}`);let A=tt(a.longContext,s,!1,"longContext",u);if(A)return{model:A,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let C=u?$t("longContext",s,void 0,l):null;if(C)return{model:C,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let A=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(A)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${A[1]}</CCR-SUBAGENT-MODEL>`,""),{model:A[1],scenarioType:"default"}}if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&a?.background){t.log.info(`Using background model for ${t.body.model}`);let A=tt(a.background,s,!1,"background",u);if(A)return{model:A,scenarioType:"background"};t.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(A=>A.type?.startsWith("web_search"))&&a?.webSearch){let A=tt(a.webSearch,s,!1,"webSearch",u);if(A)return{model:A,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let C=u?$t("webSearch",s,void 0,l):null;if(C)return{model:C,scenarioType:"webSearch"}}if(t.body.thinking?.type==="enabled"&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let A=tt(a.think,s,!1,"think",u);if(A)return{model:A,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let C=u?$t("think",s,void 0,l):null;if(C)return{model:C,scenarioType:"think"}}if(a?.default){let A=tt(a.default,s,!1,"default",u);if(A)return{model:A,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let C=u?$t("default",s,void 0,l):null;if(C)return{model:C,scenarioType:"default"};let v=tt(a.default,s,!0,"default",u);if(v)return t.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state`),{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},eo=async(t,e,n)=>{let{configService:r,event:o}=n;t.originalModel=t.body.model;let s=Qr(t.body.metadata?.user_id);s&&(t.sessionId=s);let u=await Pp(t,r)||r.get("Router"),l=u?.enableFallback===!0,f=r.get("providers")||[];t.enableFallback=l,t.fallbackConfig=u?.fallback||r.get("fallback");let d=Ai.get(t.sessionId),{messages:p,system:m=[],tools:b}=t.body,w=r.get("REWRITE_SYSTEM_PROMPT");if(w&&m.length>1&&m[1]?.text?.includes("<env>")){let y=await(0,Di.readFile)(w,"utf-8");m[1].text=`${y}<env>${m[1].text.split("<env>").pop()}`}try{let[y,g]=t.body.model.split(","),_=n.tokenizerService?.getTokenizerConfigForModel(y,g),A;n.tokenizerService?A=(await n.tokenizerService.countTokens({messages:p,system:m,tools:b},_)).tokenCount:A=Rc(p,m,b),t.tokenCount=A;let C,v=r.get("CUSTOM_ROUTER_PATH");if(v)try{C=await require(v)(t,r.getAll(),{event:o})}catch(T){t.log.error(`failed to load custom router: ${T.message}`)}if(C)t.scenarioType="default";else{let T=await iw(t,A,r,d);C=T.model,t.scenarioType=T.scenarioType}if(u?.image&&C!==u.image&&rw(t)&&!ow(C)){let T=tt(u.image,f,!1,"image",l);T?(t.log.info(`Using image model fallback for ${C}`),C=T,t.scenarioType="image"):(t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${C}`),t.scenarioType="image")}typeof C=="string"&&C.trim()?t.body.model=C:(t.log.warn(`Router could not resolve a valid model for ${t.originalModel||t.body.model}; keeping original request model`),t.scenarioType=t.scenarioType||"default")}catch(y){t.log.error(`Error in router middleware: ${y.message}`),t.body.model=u?.default,t.scenarioType="default"}},gr=new Map,Dp=1e3,Xr=new Set,Rp=1e3,aw=3,uw=50,cw=t=>new Promise(e=>setTimeout(e,t));function lw(){if(gr.size<=Dp)return;let t=[...gr.keys()].slice(0,gr.size-Dp);for(let e of t)gr.delete(e)}function dw(){if(Xr.size<=Rp)return;let t=[...Xr].slice(0,Xr.size-Rp);for(let e of t)Xr.delete(e)}var xp=async t=>{let e=await(0,Oi.opendir)(Zr.CLAUDE_PROJECTS_DIR),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=(0,Ri.join)(Zr.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,Oi.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return s;return null},xc=async t=>{let e=mr(t);if(!e)return null;if(gr.has(e))return gr.get(e)||null;try{let n=await xp(e);if(!n&&!Xr.has(e)){Xr.add(e),dw();for(let r=0;r<aw&&!n;r++)await cw(uw),n=await xp(e)}return n?(gr.set(e,n),lw(),n):null}catch(n){return console.error("Error searching for project by session:",n),null}};var fw=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;function Np(t){let e=[],n=Array.isArray(t.input)?t.input:[t.input];for(let r of n)if(r.type==="function_call")e.push({role:"assistant",tool_calls:[{id:r.call_id,type:"function",function:{name:r.name,arguments:r.arguments||"{}"}}]});else if(r.type==="function_call_output")e.push({role:"tool",tool_call_id:r.call_id,content:typeof r.output=="string"?r.output:JSON.stringify(r.output)});else if(r.type==="reasoning"){let o=Array.isArray(r.summary)?r.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
112
+ `))}}}K();let he=Y();he&&Q.enqueue(he),se="",Q.close()}catch(oe){Q.error(oe)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let n=e.output?.find(f=>f.type==="message"),r=e.output?.find(f=>f.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(f=>({type:"url_citation",url_citation:{url:f.url||"",title:f.title||"",content:"",start_index:f.start_index||0,end_index:f.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,u=null;if(n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let f=[],d=[];if(n.content.forEach(h=>{if(h.type==="output_text")f.push(h.text||"");else if(h.type==="output_image"){let m=this.buildImageContent({url:h.image_url,mime_type:h.mime_type});m&&d.push(m)}else if(h.type==="output_image_base64"){let m=this.buildImageContent({b64_json:h.image_base64,mime_type:h.mime_type});m&&d.push(m)}}),d.length>0){let h=[];f.length>0&&h.push({type:"text",text:f.join("")}),h.push(...d),s=h}else s=f.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.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:s||null,tool_calls:a,thinking:u,annotations:o},logprobs:null,finish_reason:a?"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,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}: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 Pp=require("tiktoken");var Sc=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Ai=new Sc(100);var Di=require("fs/promises"),Oi=require("fs/promises"),Ri=require("path"),Zr=require("@wengine-ai/claude-code-router-shared");Wn();var Tn=require("fs"),Dc=require("path"),vp=require("@wengine-ai/claude-code-router-shared"),Tc=(0,Dc.join)(vp.HOME_DIR,"runtime"),vc=(0,Dc.join)(Tc,"quota-store.json"),Yr=new Map,Sp=!1,ew=null;function Si(t,e){t&&Yr.set(t,{...e,provider:t,capturedAt:Date.now()})}function Ti(t){let e=Yr.get(t);return e?{...e}:void 0}function Dp(){return Array.from(Yr.values()).map(t=>({...t}))}function tw(){try{if(!(0,Tn.existsSync)(vc))return;let t=JSON.parse((0,Tn.readFileSync)(vc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;Yr.set(n.provider,n)}}catch{}}function Tp(){try{if(Yr.size===0)return;(0,Tn.existsSync)(Tc)||(0,Tn.mkdirSync)(Tc,{recursive:!0}),(0,Tn.writeFileSync)(vc,JSON.stringify(Array.from(Yr.values()),null,2),"utf-8")}catch{}}function vi(){Sp||(Sp=!0,tw(),ew=setInterval(Tp,6e4),process.on("exit",Tp))}wi();var nw=/^[A-Za-z0-9_-]+$/;function mr(t){if(typeof t!="string")return;let e=t.trim();if(!(!e||!nw.test(e)))return e}function Qr(t){if(!t)return;if(typeof t=="object")return mr(t.session_id??t.sessionId);if(typeof t!="string")return;let e=t.trim();if(!e)return;try{let o=JSON.parse(e),s=mr(o?.session_id??o?.sessionId);if(s)return s}catch{}let n="_session_",r=e.lastIndexOf(n);if(r!==-1)return mr(e.slice(r+n.length))}var vn=(0,Pp.get_encoding)("cl100k_base"),xc=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=vn.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=vn.encode(s.text).length:s.type==="tool_use"?r+=vn.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=vn.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=vn.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=vn.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=vn.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=vn.encode(o.name+o.description).length),o.input_schema&&(r+=vn.encode(JSON.stringify(o.input_schema)).length)}),r},Fp=async(t,e)=>{if(t.sessionId){let n=await Oc(t.sessionId);if(n){let r=(0,Ri.join)(Zr.HOME_DIR,n,"config.json"),o=(0,Ri.join)(Zr.HOME_DIR,n,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,Di.readFile)(o,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}try{let s=JSON.parse(await(0,Di.readFile)(r,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}}}};function xi(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function Ip(t){let e=xi(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n,isCcrAlias:!0};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n,isCcrAlias:!1}:{family:null,extended:n,isCcrAlias:!1}}function rw(t,e){if(!e||!t)return null;let n=xi(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=Ip(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=xi(o);if(a&&n.includes(a))return s}return null}function Np(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function Rc(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function Go(t,e,n){let r=t.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!r||r.enabled===!1)return null;let o=r.models?.find(s=>String(s).toLowerCase()===n.toLowerCase());return o?{provider:r,model:String(o)}:null}function tt(t,e,n,r,o){let s=Rc(t);if(!s)return t;let{providerName:a,routeModel:u}=s,l=Go(e,a,u);if(!l){if(o===!0&&r&&!n){let d=Jr(),h=d.getPromotion(a,u,r,e);if(h){let m=Rc(h);if(m){let C=Go(e,m.providerName,m.routeModel);if(C)return`${C.provider.name},${C.model}`}d.clear(a,u,r)}}return null}if(o===!0&&r&&!n){let d=Jr(),h=d.getPromotion(a,u,r,e);if(h){let m=Rc(h);if(m){let C=Go(e,m.providerName,m.routeModel);if(C)return`${C.provider.name},${C.model}`}d.clear(a,u,r)}}if(!n&&!Je().isAvailable(l.provider.name,l.model))return null;let f=Ti(l.provider.name);if(f){let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,h=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||h)return null}return`${l.provider.name},${l.model}`}function qt(t,e,n,r,o){let s=Je(),a=[n?.[t],r?.[t]];for(let u of a)if(!(!Array.isArray(u)||u.length===0))for(let l of u){let f=tt(l,e);if(f)return f}return null}function ow(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function sw(t){let e=xi(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(e))}function iw(t,e,n,r,o,s,a,u,l){let f=n.longContextThreshold??l??6e4,d=Math.max(e,Np(o)),h=t.modelFamily;if((s||d>2e5)&&n.extendedContext){let y=tt(n.extendedContext,r,!1,"extendedContext",u);if(y)return t.log.info(`Family: using extended context model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:y,scenarioType:"extendedContext",isFallback:!1};let g=u?qt("extendedContext",r,n.fallback,a,h):null;if(g)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:g,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(d>f&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let y=n.longContext?tt(n.longContext,r,!1,"longContext",u):null;if(y)return t.log.info(`Family: using long context model, tokens: ${d}, estimated: ${e}`),{model:y,scenarioType:"longContext",isFallback:!1};let g=u?qt("longContext",r,n.fallback,a,h):null;if(g)return t.log.info(`Family: using long context fallback model, tokens: ${d}, estimated: ${e}`),{model:g,scenarioType:"longContext",isFallback:!0};t.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(t.body.tools)&&t.body.tools.some(y=>y.type?.startsWith("web_search"))&&n.webSearch){let y=tt(n.webSearch,r,!1,"webSearch",u);if(y)return{model:y,scenarioType:"webSearch",isFallback:!1};let g=u?qt("webSearch",r,n.fallback,a,h):null;if(g)return t.log.info("Family: using webSearch fallback model"),{model:g,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking?.type==="enabled"&&n.think){let y=tt(n.think,r,!1,"think",u);if(y)return{model:y,scenarioType:"think",isFallback:!1};let g=u?qt("think",r,n.fallback,a,h):null;if(g)return t.log.info("Family: using think fallback model"),{model:g,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let y=tt(n.default,r,!1,"default",u);if(y)return{model:y,scenarioType:"default",isFallback:!1};let g=u?qt("default",r,n.fallback,a,h):null;if(g)return t.log.info("Family: using default fallback model"),{model:g,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var aw=async(t,e,n,r)=>{let o=await Fp(t,n),s=n.get("providers")||[],a=o||n.get("Router"),u=a?.enableFallback===!0,l=u?a?.fallback||n.get("fallback"):void 0;if(t.body.model.includes(",")){let E=tt(t.body.model,s,!1,"default",u);if(E)return{model:E,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let b=u?qt("default",s,void 0,l):null;if(b)return t.log.info(`Using fallback for explicit model: ${b}`),{model:b,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:f,extended:d,isCcrAlias:h}=Ip(t.body.model),m=a?.families?.[f||""];if(m&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${f}${d?" (1M)":""}`),t.modelFamily=f,t.familyFallback=m.fallback;let E=iw(t,e,m,s,r,d,l,u,a?.longContextThreshold);if(E)return{model:E.model,scenarioType:E.scenarioType}}let C=h&&!a?.enableFamilyRouting?null:rw(t.body.model,a?.models);if(C){let E=tt(C,s,!1,"modelMapping",u);if(E)return t.log.info(`Using mapped model for ${t.body.model}: ${C}`),{model:E,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${C} unavailable (fail pool), skipping`)}let w=Math.max(e,Np(r)),y=a?.extendedContextThreshold||2e5;if(w>y&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${w}, estimated: ${e}, threshold: ${y}`);let E=tt(a.extendedContext,s,!1,"extendedContext",u);if(E)return{model:E,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let b=u?qt("extendedContext",s,void 0,l):null;if(b)return{model:b,scenarioType:"extendedContext"}}let g=a?.longContextThreshold||6e4;if(w>g&&a?.longContext){t.log.info(`Using long context model due to token count: ${w}, estimated: ${e}, threshold: ${g}`);let E=tt(a.longContext,s,!1,"longContext",u);if(E)return{model:E,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let b=u?qt("longContext",s,void 0,l):null;if(b)return{model:b,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let E=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(E)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${E[1]}</CCR-SUBAGENT-MODEL>`,""),{model:E[1],scenarioType:"default"}}if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&a?.background){t.log.info(`Using background model for ${t.body.model}`);let E=tt(a.background,s,!1,"background",u);if(E)return{model:E,scenarioType:"background"};t.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(E=>E.type?.startsWith("web_search"))&&a?.webSearch){let E=tt(a.webSearch,s,!1,"webSearch",u);if(E)return{model:E,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let b=u?qt("webSearch",s,void 0,l):null;if(b)return{model:b,scenarioType:"webSearch"}}if(t.body.thinking?.type==="enabled"&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let E=tt(a.think,s,!1,"think",u);if(E)return{model:E,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let b=u?qt("think",s,void 0,l):null;if(b)return{model:b,scenarioType:"think"}}if(a?.default){let E=tt(a.default,s,!1,"default",u);if(E)return{model:E,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let b=u?qt("default",s,void 0,l):null;if(b)return{model:b,scenarioType:"default"};let S=tt(a.default,s,!0,"default",u);if(S)return t.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state`),{model:S,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},eo=async(t,e,n)=>{let{configService:r,event:o}=n;t.originalModel=t.body.model;let s=Qr(t.body.metadata?.user_id);s&&(t.sessionId=s);let u=await Fp(t,r)||r.get("Router"),l=u?.enableFallback===!0,f=r.get("providers")||[];t.enableFallback=l,t.fallbackConfig=u?.fallback||r.get("fallback");let d=Ai.get(t.sessionId),{messages:h,system:m=[],tools:C}=t.body,w=r.get("REWRITE_SYSTEM_PROMPT");if(w&&m.length>1&&m[1]?.text?.includes("<env>")){let y=await(0,Di.readFile)(w,"utf-8");m[1].text=`${y}<env>${m[1].text.split("<env>").pop()}`}try{let[y,g]=t.body.model.split(","),_=n.tokenizerService?.getTokenizerConfigForModel(y,g),E;n.tokenizerService?E=(await n.tokenizerService.countTokens({messages:h,system:m,tools:C},_)).tokenCount:E=xc(h,m,C),t.tokenCount=E;let b,S=r.get("CUSTOM_ROUTER_PATH");if(S)try{b=await require(S)(t,r.getAll(),{event:o})}catch(v){t.log.error(`failed to load custom router: ${v.message}`)}if(b)t.scenarioType="default";else{let v=await aw(t,E,r,d);b=v.model,t.scenarioType=v.scenarioType}if(u?.image&&b!==u.image&&ow(t)&&!sw(b)){let v=tt(u.image,f,!1,"image",l);v?(t.log.info(`Using image model fallback for ${b}`),b=v,t.scenarioType="image"):(t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${b}`),t.scenarioType="image")}typeof b=="string"&&b.trim()?t.body.model=b:(t.log.warn(`Router could not resolve a valid model for ${t.originalModel||t.body.model}; keeping original request model`),t.scenarioType=t.scenarioType||"default")}catch(y){t.log.error(`Error in router middleware: ${y.message}`),t.body.model=u?.default,t.scenarioType="default"}},gr=new Map,Rp=1e3,Xr=new Set,xp=1e3,uw=3,cw=50,lw=t=>new Promise(e=>setTimeout(e,t));function dw(){if(gr.size<=Rp)return;let t=[...gr.keys()].slice(0,gr.size-Rp);for(let e of t)gr.delete(e)}function fw(){if(Xr.size<=xp)return;let t=[...Xr].slice(0,Xr.size-xp);for(let e of t)Xr.delete(e)}var Op=async t=>{let e=await(0,Oi.opendir)(Zr.CLAUDE_PROJECTS_DIR),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=(0,Ri.join)(Zr.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,Oi.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return s;return null},Oc=async t=>{let e=mr(t);if(!e)return null;if(gr.has(e))return gr.get(e)||null;try{let n=await Op(e);if(!n&&!Xr.has(e)){Xr.add(e),fw();for(let r=0;r<uw&&!n;r++)await lw(cw),n=await Op(e)}return n?(gr.set(e,n),dw(),n):null}catch(n){return console.error("Error searching for project by session:",n),null}};var hw=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;function Bp(t){let e=[],n=Array.isArray(t.input)?t.input:[t.input];for(let r of n)if(r.type==="function_call")e.push({role:"assistant",tool_calls:[{id:r.call_id,type:"function",function:{name:r.name,arguments:r.arguments||"{}"}}]});else if(r.type==="function_call_output")e.push({role:"tool",tool_call_id:r.call_id,content:typeof r.output=="string"?r.output:JSON.stringify(r.output)});else if(r.type==="reasoning"){let o=Array.isArray(r.summary)?r.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
113
113
  `):"";o&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
114
- ${o}`}],_reasoningItem:!0})}else if(r.role){let o=r.content;Array.isArray(o)&&(o=o.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:r.role,content:o})}t.messages=e,delete t.input,t.instructions&&typeof t.instructions=="string"&&(t.system=t.instructions,delete t.instructions),Array.isArray(t.tools)&&(t.tools=t.tools.filter(r=>r&&typeof r=="object").map(r=>r.type==="function"&&r.name&&!r.function?{type:"function",function:{name:r.name,description:r.description||"",parameters:r.parameters||{type:"object",properties:{}}}}:r.function?.name?r:r.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),t.reasoning&&typeof t.reasoning=="object"&&(t.reasoning={enabled:!0,effort:t.reasoning.effort}),delete t.store,delete t.previous_response_id,delete t.include}async function Bp(t,e,n,r){let o=t.body;r.endPoint==="/v1/responses"&&o?.input&&!o?.messages&&Np(o),r.endPoint==="/v1/responses"&&!t.provider&&typeof o?.model=="string"&&fw.test(o.model)&&await eo(t,e,{configService:n.configService,tokenizerService:n.tokenizerService});let s=t.provider;if(!s&&o?.model){let f=o.model.split(",");f.length>1&&(s=f[0],o.model=f.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let f=n.providerService.resolveModelRoute(o.model);f&&(a=f.provider,o.model=f.targetModel)}if(!a&&o?.model){let d=n.configService.get("Router")?.default;if(d&&d.includes(",")){let[p,...m]=d.split(","),b=n.providerService.getProvider(p);b&&(a=b,o.model=m.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw He(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let u=mw(t),l=r.endPoint==="/v1/messages"&&u;u&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),t.isCodexOnMessagesEndpoint=l,t.codexDetected=u;try{r.endPoint==="/v1/responses"&&o.input&&!o.messages&&Np(o);let{requestBody:f,config:d,bypass:p}=await Lp(o,a,r,t.headers,{req:t});if(f?.messages&&!p&&!t.isTargetAnthropic){let y=f.messages,g=new Set,_=[],A=[];for(let C of y){if(C?.role!=="system"){A.push(C);continue}let v=JSON.stringify(C.content??"");g.has(v)||(g.add(v),_.push(C))}_.length>0&&A.length>0&&(f.messages=[..._,...A])}let m=await jp(f,d,a,n,p,r,{req:t});try{a?.baseUrl&&m?.headers&&Wo(s,a.baseUrl,m.headers)}catch{}let b=await Up(f,m,a,r,p,{req:t,isCodexOnMessagesEndpoint:l});b=await Mp(o,b,a.name||s);let w=$p(b,e,o,n);try{let y=o.model||t.originalModel;s&&y&&Je().recordSuccess(s,y)}catch{}return w}catch(f){if(!t.__retryAttempted){t.__retryAttempted=!0;try{return await Bp(t,e,n,r)}catch(p){if(t.__fallbackExhausted)throw p;f=p}}let d=await hw(t,e,n,r,f);if(d)return d;throw t.__fallbackExhausted=!0,f}}async function Mp(t,e,n){if(!t?.stream||!e?.body)return e;let r=e.body.getReader(),o=await r.read();if(o.done)throw r.releaseLock(),He(`Provider returned empty streaming response from ${n}`,400,"provider_response_error");let s=new TextDecoder().decode(o.value);if(s.includes("event: error")){r.releaseLock();let l=s.length<500?s:s.slice(0,500);throw He(`Provider ${n} returned error in SSE stream: ${l}`,400,"provider_response_error")}if(s.split(`
115
- `).filter(l=>l.startsWith("data:")&&l.trim().length>5).length===0){r.releaseLock();let l=s.length<500?s:s.slice(0,500);throw He(`Provider ${n} returned streaming response with no SSE data lines: ${l}`,400,"provider_response_error")}let u=new ReadableStream({start:l=>{l.enqueue(o.value);let f=()=>{r.read().then(({done:d,value:p})=>{d?l.close():(l.enqueue(p),f())}).catch(d=>l.error(d))};f()},cancel:()=>{r.cancel()}});return new Response(u,{headers:e.headers,status:e.status,statusText:e.statusText})}async function hw(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,u=t.modelFamily,l=t.fallbackConfig??n.configService.get("fallback"),f=Je(),d=t.provider||"",p=t.body.model||"",m=new Set,b=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&Pi(o.rawBody)||o?.message&&Pi(o.message);if(d&&p&&(b?(f.markRateLimited(d,p,120,o?.message),t.log.warn(`Primary model ${d},${p} rate-limited, will try fallbacks`)):f.recordFailure(d,p,o?.message),m.add(`${d},${p}`),n.recordUsage?.({provider:d,model:p,originalModel:t.originalModel||p,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!(t.enableFallback??n.configService.get("Router")?.enableFallback===!0))return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let y=A=>{let[C,...v]=A.split(","),T=C?.trim(),R=v.join(",").trim();return!T||!R?null:{provider:T,model:R,key:`${T},${R}`}},g=[];if(u){let A=a?.[s];Array.isArray(A)&&A.length>0?g.push({name:`${u}/${s}`,models:A}):t.log.warn(`No ${u} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&g.push({name:`global/${s}`,models:l[s]}),g.length===0&&s!=="image"&&t.body?.messages?.some(v=>v.role==="user"&&Array.isArray(v.content)&&v.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(R=>R.type==="image"||R.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),g.push({name:"global/image (auto-detected)",models:l.image})),g.length===0)return null;let _=g.reduce((A,C)=>A+C.models.length,0);t.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${g.length} fallback stage(s)`);for(let A of g){t.log.info(`Trying ${A.name} fallback stage with ${A.models.length} models`);for(let C of A.models){let v=y(C);if(!v){t.log.warn(`Fallback model '${C}' is invalid, skipping`);continue}if(m.has(v.key))continue;m.add(v.key);let T=n.providerService.getProviders(),R=Go(T,v.provider,v.model);if(!R){t.log.warn(`Fallback model ${C} is not configured or provider is disabled, skipping`);continue}let $=R.provider.name,G=R.model;if(!f.isAvailable($,G)){t.log.warn(`Fallback model ${C} unavailable (fail pool), skipping`);continue}let P;for(let K=1;K<=2;K++)try{t.log.info(`Trying fallback model: ${$},${G}${K>1?" (retry)":""}`);let z={...t.body};z.model=G;let Y={...t,provider:$,body:z},Q=R.provider,{requestBody:ee,config:oe,bypass:se}=await Lp(z,Q,r,t.headers,{req:Y}),he=await jp(ee,oe,Q,n,se,r,{req:Y});try{Q?.baseUrl&&he?.headers&&Wo($,Q.baseUrl,he.headers)}catch{}let J=await Up(ee,he,Q,r,se,{req:Y,isCodexOnMessagesEndpoint:t.isCodexOnMessagesEndpoint||!1});return J=await Mp(z,J,$),t.log.info(`Fallback model ${$},${G} succeeded`),f.recordSuccess($,G),d&&p&&(Jr().promote(d,p,s,$,G),t.log.info(`Promoted fallback model ${$},${G} for ${d},${p}:${s}`),b?t.log.info(`Rate-limited original model ${d},${p} already marked unavailable with cooldown`):(f.forceOpen(d,p,o?.message),t.log.info(`Marked original model ${d},${p} as unavailable`))),t.provider=$,t.body=z,$p(J,e,z,n)}catch(z){if(P=z,K===1){t.log.warn(`Fallback model ${$},${G} failed, retrying once: ${z.message}`);continue}}f.recordFailure($,G,P?.message),t.log.warn(`Fallback model ${$},${G} failed after retry: ${P?.message}`),n.recordUsage?.({provider:$,model:G,originalModel:t.originalModel||p||t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:P?.message||String(P),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})}}return t.log.error(`All fallback models failed for ${s}`),null}async function Lp(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let f=0;f<a.length;f++){let d=a[f],p=typeof d=="string"?d:d?.text??"";if(p.includes("cch=")){let m=p.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof d=="string"?a[f]=m:typeof d?.text=="string"&&(d.text=m)}}let u={},l=!1;if(l=pw(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],u.headers=r),!l&&typeof n.transformRequestOut=="function"){let f=await n.transformRequestOut(s);f.body?(s=f.body,u=f.config||{}):s=f}if(!l&&e.transformer?.use?.length)for(let f of e.transformer.use){if(!f||typeof f.transformRequestIn!="function")continue;let d=await f.transformRequestIn(s,e,o);d.body?(s=d.body,u={...u,...d.config}):s=d}if(!l&&e.transformer?.[t.model]?.use?.length)for(let f of e.transformer[t.model].use)!f||typeof f.transformRequestIn!="function"||(s=await f.transformRequestIn(s,e,o));return{requestBody:s,config:u,bypass:l}}function pw(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function mw(t){let e=t.headers||{},n=e["x-anthropic-billing-header"]||"";if(typeof n=="string"&&n.includes("cc_version="))return!1;let r=e["user-agent"]||"";if(typeof r=="string"&&/codex/i.test(r))return!0;let o=t.pathname||t.url||"";if(typeof o=="string"&&o.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=t.originalModel||t.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function jp(t,e,n,r,o,s,a){let u=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let d=r.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,n);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 ${n.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];_i(r.configService)&&dp(r.log,a.req.id,{url:String(u),headers:l,body:t});let f=await op(u,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!f.ok){let d=await f.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${f.status}): ${d}`);let p=He(`Error from provider(${n.name},${t.model}: ${f.status}): ${d}`,f.status,"provider_response_error");throw p.isRateLimit=f.status===429||Pi(d),p.rawBody=d,p}if(f.ok){let d=f.headers.get("content-type")||"",p=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${p} contentType=${d} ok=${f.ok} status=${f.status} hasBody=${!!f.body}`),!p||d.includes("application/json")){let m=f.clone(),b="";try{if(b=await m.text(),!b||b.trim()==="")throw new SyntaxError("Empty JSON body");let w=JSON.parse(b);if(w&&typeof w=="object"&&w.error&&(typeof w.error=="string"||typeof w.error=="object"&&Object.keys(w.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${f.status}): ${b}`);let g=Pi(b),_=He(`Error from provider(${n.name},${t.model}: ${f.status}): ${b}`,400,"provider_response_error");throw _.isRateLimit=g,_.rawBody=b,_}}catch(w){if(w instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${b}"`);let y=He(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw y.rawBody=b,y}throw w}}}if(!t.stream&&_i(r.configService)){let p=await f.clone().text();fp(r.log,a.req.id,{status:f.status,headers:Object.fromEntries(f.headers.entries()),body:p})}return f}async function Up(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let u of Array.from(n.transformer.use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let u of Array.from(n.transformer[t.model].use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Kr().transformResponseIn(a,{...s,provider:n})}catch(u){console.error("Failed to apply Responses API conversion for codex client:",u)}return a}function $p(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&_i(r.configService)){let[s,a]=t.body.tee(),u=cp(r.configService);return hp(s,r.log,e.request.id,u),e.send(a)}return e.send(t.body)}else return t.json()}var Oc=async t=>{t.get("/",async()=>({message:"LLMs API",version:Ci})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Je().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>Bp(r,o,t,n));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(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:u}=n.body;if(!o?.trim())throw He("Provider name is required",400,"invalid_request");if(!s||!gw(s))throw He("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw He("API key is required",400,"invalid_request");if(!u||!Array.isArray(u)||u.length===0)throw He("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw He(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw He("Provider not found",404,"provider_not_found");return r}),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(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw He("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw He("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(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw He("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function Pi(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function gw(t){try{return new URL(t),!0}catch{return!1}}var yr=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;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(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,u={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,u),this.modelRoutes.has(s)||this.modelRoutes.set(s,u)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Qe=[];for(let t=0;t<256;++t)Qe.push((t+256).toString(16).slice(1));function qp(t,e=0){return(Qe[t[e+0]]+Qe[t[e+1]]+Qe[t[e+2]]+Qe[t[e+3]]+"-"+Qe[t[e+4]]+Qe[t[e+5]]+"-"+Qe[t[e+6]]+Qe[t[e+7]]+"-"+Qe[t[e+8]]+Qe[t[e+9]]+"-"+Qe[t[e+10]]+Qe[t[e+11]]+Qe[t[e+12]]+Qe[t[e+13]]+Qe[t[e+14]]+Qe[t[e+15]]).toLowerCase()}var zp=require("crypto"),Ii=new Uint8Array(256),Fi=Ii.length;function Pc(){return Fi>Ii.length-16&&((0,zp.randomFillSync)(Ii),Fi=0),Ii.slice(Fi,Fi+=16)}var Hp=require("crypto"),Fc={randomUUID:Hp.randomUUID};function yw(t,e,n){if(Fc.randomUUID&&!e&&!t)return Fc.randomUUID();t=t||{};let r=t.random??t.rng?.()??Pc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return qp(r)}var qt=yw;var Wp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Gp=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function _w(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Jp(t){let e=[],n=[],r=m=>{if(typeof m=="string"){n.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(b=>{if(typeof b=="string"){n.push({type:"text",text:b});return}b&&typeof b=="object"&&b.type==="text"&&b.text&&n.push({...b})})},o=()=>{let m=new Map;for(let b=0;b<n.length;b++){let w=n[b],y=w?.text??JSON.stringify(w),g=m.get(y);if(g===void 0){m.set(y,b);continue}!n[g]?.cache_control&&w?.cache_control&&(n[g]=w),n.splice(b,1),b--}};t.messages.forEach(m=>{m.role==="system"?r(m.content):e.push(m)}),o();let s=[];for(let m=0;m<e.length;m++){let b=e[m];if(b.role==="tool"){let w=b.content;try{typeof b.content=="string"&&(w=JSON.parse(b.content))}catch{}w!=null&&typeof w!="object"&&typeof w!="string"&&(w=String(w));let y={type:"tool_result",tool_use_id:b.tool_call_id,content:w};b.cache_control&&(y.cache_control=b.cache_control);let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(y):s.push({role:"user",content:[y]})}else if(b.role==="user"){let w=[];typeof b.content=="string"?w.push({type:"text",text:b.content}):Array.isArray(b.content)&&b.content.forEach(g=>{g&&typeof g=="object"&&g.type==="image_url"&&g.image_url?.url?w.push({type:"image",source:{type:"base64",media_type:g.media_type||"image/jpeg",data:g.image_url.url.split(",")[1]||g.image_url.url}}):w.push(g)});let y=s[s.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(...w):s.push({role:"user",content:w.length>0?w:[{type:"text",text:" "}]})}else if(b.role==="assistant"){let w=[];b.content&&(typeof b.content=="string"?w.push({type:"text",text:b.content}):Array.isArray(b.content)&&w.push(...b.content)),b.tool_calls&&b.tool_calls.length>0&&b.tool_calls.forEach(g=>{let _={};try{_=JSON.parse(g.function.arguments)}catch{_=g.function.arguments}w.push({type:"tool_use",id:g.id,name:g.function.name,input:_})}),b.thinking&&w.unshift({type:"thinking",thinking:b.thinking.content,signature:b.thinking.signature});let y=s[s.length-1];y&&y.role==="assistant"&&Array.isArray(y.content)?y.content.push(...w):s.push({role:"assistant",content:w.length>0?w:[{type:"text",text:" "}]})}}let a=()=>{let m=n.filter(b=>b?.cache_control).length;for(let b of s)Array.isArray(b.content)&&(m+=b.content.filter(w=>w?.cache_control).length);return m},u=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},l=()=>{for(let m=s.length-1;m>=0;m--){let b=s[m]?.content;if(!Array.isArray(b))continue;let w=b.find(y=>y?.cache_control);if(w?.cache_control)return w.cache_control}for(let m=n.length-1;m>=0;m--)if(n[m]?.cache_control)return n[m].cache_control;return{type:"ephemeral"}},f=(m,b)=>{if(!Array.isArray(m?.content)||m.content.some(y=>y?.cache_control))return!1;let w=m.content.find(y=>y&&typeof y=="object"&&!y.cache_control);return w?(w.cache_control=u(b),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let b=s,w=l(),y=[];for(let g=b.length-1;g>=0;g--)b[g]?.role!=="user"||!Array.isArray(b[g].content)||y.push(g);for(let g of y){if(m<=0)break;f(b[g],w)&&m--}})();let p={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let m=n.some(b=>b?.cache_control);p.system=m?n:n.map(b=>b.text||"").join(`
114
+ ${o}`}],_reasoningItem:!0})}else if(r.role){let o=r.content;Array.isArray(o)&&(o=o.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:r.role,content:o})}t.messages=e,delete t.input,t.instructions&&typeof t.instructions=="string"&&(t.system=t.instructions,delete t.instructions),Array.isArray(t.tools)&&(t.tools=t.tools.filter(r=>r&&typeof r=="object").map(r=>r.type==="function"&&r.name&&!r.function?{type:"function",function:{name:r.name,description:r.description||"",parameters:r.parameters||{type:"object",properties:{}}}}:r.function?.name?r:r.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),t.reasoning&&typeof t.reasoning=="object"&&(t.reasoning={enabled:!0,effort:t.reasoning.effort}),delete t.store,delete t.previous_response_id,delete t.include}async function Mp(t,e,n,r){let o=t.body;r.endPoint==="/v1/responses"&&o?.input&&!o?.messages&&Bp(o),r.endPoint==="/v1/responses"&&!t.provider&&typeof o?.model=="string"&&hw.test(o.model)&&await eo(t,e,{configService:n.configService,tokenizerService:n.tokenizerService});let s=t.provider;if(!s&&o?.model){let f=o.model.split(",");f.length>1&&(s=f[0],o.model=f.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let f=n.providerService.resolveModelRoute(o.model);f&&(a=f.provider,o.model=f.targetModel)}if(!a&&o?.model){let d=n.configService.get("Router")?.default;if(d&&d.includes(",")){let[h,...m]=d.split(","),C=n.providerService.getProvider(h);C&&(a=C,o.model=m.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw He(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let u=gw(t),l=r.endPoint==="/v1/messages"&&u;u&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),t.isCodexOnMessagesEndpoint=l,t.codexDetected=u;try{r.endPoint==="/v1/responses"&&o.input&&!o.messages&&Bp(o);let{requestBody:f,config:d,bypass:h}=await jp(o,a,r,t.headers,{req:t});if(f?.messages&&!h&&!t.isTargetAnthropic){let y=f.messages,g=new Set,_=[],E=[];for(let b of y){if(b?.role!=="system"){E.push(b);continue}let S=JSON.stringify(b.content??"");g.has(S)||(g.add(S),_.push(b))}_.length>0&&E.length>0&&(f.messages=[..._,...E])}let m=await Up(f,d,a,n,h,r,{req:t});try{a?.baseUrl&&m?.headers&&Wo(s,a.baseUrl,m.headers)}catch{}let C=await $p(f,m,a,r,h,{req:t,isCodexOnMessagesEndpoint:l});C=await Lp(o,C,a.name||s);let w=qp(C,e,o,n);try{let y=o.model||t.originalModel;s&&y&&Je().recordSuccess(s,y)}catch{}return w}catch(f){if(!t.__retryAttempted){t.__retryAttempted=!0;try{return await Mp(t,e,n,r)}catch(h){if(t.__fallbackExhausted)throw h;f=h}}let d=await pw(t,e,n,r,f);if(d)return d;throw t.__fallbackExhausted=!0,f}}async function Lp(t,e,n){if(!t?.stream||!e?.body)return e;let r=e.body.getReader(),o=await r.read();if(o.done)throw r.releaseLock(),He(`Provider returned empty streaming response from ${n}`,400,"provider_response_error");let s=new TextDecoder().decode(o.value);if(s.includes("event: error")){r.releaseLock();let l=s.length<500?s:s.slice(0,500);throw He(`Provider ${n} returned error in SSE stream: ${l}`,400,"provider_response_error")}if(s.split(`
115
+ `).filter(l=>l.startsWith("data:")&&l.trim().length>5).length===0){r.releaseLock();let l=s.length<500?s:s.slice(0,500);throw He(`Provider ${n} returned streaming response with no SSE data lines: ${l}`,400,"provider_response_error")}let u=new ReadableStream({start:l=>{l.enqueue(o.value);let f=()=>{r.read().then(({done:d,value:h})=>{d?l.close():(l.enqueue(h),f())}).catch(d=>l.error(d))};f()},cancel:()=>{r.cancel()}});return new Response(u,{headers:e.headers,status:e.status,statusText:e.statusText})}async function pw(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,u=t.modelFamily,l=t.fallbackConfig??n.configService.get("fallback"),f=Je(),d=t.provider||"",h=t.body.model||"",m=new Set,C=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&Pi(o.rawBody)||o?.message&&Pi(o.message);if(d&&h&&(C?(f.markRateLimited(d,h,120,o?.message),t.log.warn(`Primary model ${d},${h} rate-limited, will try fallbacks`)):f.recordFailure(d,h,o?.message),m.add(`${d},${h}`),n.recordUsage?.({provider:d,model:h,originalModel:t.originalModel||h,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!(t.enableFallback??n.configService.get("Router")?.enableFallback===!0))return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let y=E=>{let[b,...S]=E.split(","),v=b?.trim(),R=S.join(",").trim();return!v||!R?null:{provider:v,model:R,key:`${v},${R}`}},g=[];if(u){let E=a?.[s];Array.isArray(E)&&E.length>0?g.push({name:`${u}/${s}`,models:E}):t.log.warn(`No ${u} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&g.push({name:`global/${s}`,models:l[s]}),g.length===0&&s!=="image"&&t.body?.messages?.some(S=>S.role==="user"&&Array.isArray(S.content)&&S.content.some(v=>v.type==="image"||v.type==="image_url"||Array.isArray(v?.content)&&v.content.some(R=>R.type==="image"||R.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),g.push({name:"global/image (auto-detected)",models:l.image})),g.length===0)return null;let _=g.reduce((E,b)=>E+b.models.length,0);t.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${g.length} fallback stage(s)`);for(let E of g){t.log.info(`Trying ${E.name} fallback stage with ${E.models.length} models`);for(let b of E.models){let S=y(b);if(!S){t.log.warn(`Fallback model '${b}' is invalid, skipping`);continue}if(m.has(S.key))continue;m.add(S.key);let v=n.providerService.getProviders(),R=Go(v,S.provider,S.model);if(!R){t.log.warn(`Fallback model ${b} is not configured or provider is disabled, skipping`);continue}let $=R.provider.name,H=R.model;if(!f.isAvailable($,H)){t.log.warn(`Fallback model ${b} unavailable (fail pool), skipping`);continue}let P;for(let K=1;K<=2;K++)try{t.log.info(`Trying fallback model: ${$},${H}${K>1?" (retry)":""}`);let q={...t.body};q.model=H;let Y={...t,provider:$,body:q},Q=R.provider,{requestBody:ee,config:oe,bypass:se}=await jp(q,Q,r,t.headers,{req:Y}),he=await Up(ee,oe,Q,n,se,r,{req:Y});try{Q?.baseUrl&&he?.headers&&Wo($,Q.baseUrl,he.headers)}catch{}let J=await $p(ee,he,Q,r,se,{req:Y,isCodexOnMessagesEndpoint:t.isCodexOnMessagesEndpoint||!1});return J=await Lp(q,J,$),t.log.info(`Fallback model ${$},${H} succeeded`),f.recordSuccess($,H),d&&h&&(Jr().promote(d,h,s,$,H),t.log.info(`Promoted fallback model ${$},${H} for ${d},${h}:${s}`),C?t.log.info(`Rate-limited original model ${d},${h} already marked unavailable with cooldown`):(f.forceOpen(d,h,o?.message),t.log.info(`Marked original model ${d},${h} as unavailable`))),t.provider=$,t.body=q,qp(J,e,q,n)}catch(q){if(P=q,K===1){t.log.warn(`Fallback model ${$},${H} failed, retrying once: ${q.message}`);continue}}f.recordFailure($,H,P?.message),t.log.warn(`Fallback model ${$},${H} failed after retry: ${P?.message}`),n.recordUsage?.({provider:$,model:H,originalModel:t.originalModel||h||t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:P?.message||String(P),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})}}return t.log.error(`All fallback models failed for ${s}`),null}async function jp(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let f=0;f<a.length;f++){let d=a[f],h=typeof d=="string"?d:d?.text??"";if(h.includes("cch=")){let m=h.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof d=="string"?a[f]=m:typeof d?.text=="string"&&(d.text=m)}}let u={},l=!1;if(l=mw(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],u.headers=r),!l&&typeof n.transformRequestOut=="function"){let f=await n.transformRequestOut(s);f.body?(s=f.body,u=f.config||{}):s=f}if(!l&&e.transformer?.use?.length)for(let f of e.transformer.use){if(!f||typeof f.transformRequestIn!="function")continue;let d=await f.transformRequestIn(s,e,o);d.body?(s=d.body,u={...u,...d.config}):s=d}if(!l&&e.transformer?.[t.model]?.use?.length)for(let f of e.transformer[t.model].use)!f||typeof f.transformRequestIn!="function"||(s=await f.transformRequestIn(s,e,o));return{requestBody:s,config:u,bypass:l}}function mw(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function gw(t){let e=t.headers||{},n=e["x-anthropic-billing-header"]||"";if(typeof n=="string"&&n.includes("cc_version="))return!1;let r=e["user-agent"]||"";if(typeof r=="string"&&/codex/i.test(r))return!0;let o=t.pathname||t.url||"";if(typeof o=="string"&&o.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=t.originalModel||t.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Up(t,e,n,r,o,s,a){let u=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let d=r.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,n);if(d.body){t=d.body;let h=e.headers||{};d.config?.headers&&(h={...h,...d.config.headers},delete h.host,delete d.config.headers),e={...e,...d.config,headers:h}}else t=d}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];_i(r.configService)&&fp(r.log,a.req.id,{url:String(u),headers:l,body:t});let f=await sp(u,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!f.ok){let d=await f.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${f.status}): ${d}`);let h=He(`Error from provider(${n.name},${t.model}: ${f.status}): ${d}`,f.status,"provider_response_error");throw h.isRateLimit=f.status===429||Pi(d),h.rawBody=d,h}if(f.ok){let d=f.headers.get("content-type")||"",h=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${h} contentType=${d} ok=${f.ok} status=${f.status} hasBody=${!!f.body}`),!h||d.includes("application/json")){let m=f.clone(),C="";try{if(C=await m.text(),!C||C.trim()==="")throw new SyntaxError("Empty JSON body");let w=JSON.parse(C);if(w&&typeof w=="object"&&w.error&&(typeof w.error=="string"||typeof w.error=="object"&&Object.keys(w.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${f.status}): ${C}`);let g=Pi(C),_=He(`Error from provider(${n.name},${t.model}: ${f.status}): ${C}`,400,"provider_response_error");throw _.isRateLimit=g,_.rawBody=C,_}}catch(w){if(w instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${C}"`);let y=He(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw y.rawBody=C,y}throw w}}}if(!t.stream&&_i(r.configService)){let h=await f.clone().text();hp(r.log,a.req.id,{status:f.status,headers:Object.fromEntries(f.headers.entries()),body:h})}return f}async function $p(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let u of Array.from(n.transformer.use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let u of Array.from(n.transformer[t.model].use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Kr().transformResponseIn(a,{...s,provider:n})}catch(u){console.error("Failed to apply Responses API conversion for codex client:",u)}return a}function qp(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&_i(r.configService)){let[s,a]=t.body.tee(),u=lp(r.configService);return pp(s,r.log,e.request.id,u),e.send(a)}return e.send(t.body)}else return t.json()}var Pc=async t=>{t.get("/",async()=>({message:"LLMs API",version:Ci})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Je().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>Mp(r,o,t,n));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(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:u}=n.body;if(!o?.trim())throw He("Provider name is required",400,"invalid_request");if(!s||!yw(s))throw He("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw He("API key is required",400,"invalid_request");if(!u||!Array.isArray(u)||u.length===0)throw He("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw He(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw He("Provider not found",404,"provider_not_found");return r}),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(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw He("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw He("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(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw He("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function Pi(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function yw(t){try{return new URL(t),!0}catch{return!1}}var yr=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;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(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,u={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,u),this.modelRoutes.has(s)||this.modelRoutes.set(s,u)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Qe=[];for(let t=0;t<256;++t)Qe.push((t+256).toString(16).slice(1));function zp(t,e=0){return(Qe[t[e+0]]+Qe[t[e+1]]+Qe[t[e+2]]+Qe[t[e+3]]+"-"+Qe[t[e+4]]+Qe[t[e+5]]+"-"+Qe[t[e+6]]+Qe[t[e+7]]+"-"+Qe[t[e+8]]+Qe[t[e+9]]+"-"+Qe[t[e+10]]+Qe[t[e+11]]+Qe[t[e+12]]+Qe[t[e+13]]+Qe[t[e+14]]+Qe[t[e+15]]).toLowerCase()}var Hp=require("crypto"),Ii=new Uint8Array(256),Fi=Ii.length;function Fc(){return Fi>Ii.length-16&&((0,Hp.randomFillSync)(Ii),Fi=0),Ii.slice(Fi,Fi+=16)}var Wp=require("crypto"),Ic={randomUUID:Wp.randomUUID};function _w(t,e,n){if(Ic.randomUUID&&!e&&!t)return Ic.randomUUID();t=t||{};let r=t.random??t.rng?.()??Fc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return zp(r)}var pt=_w;var Gp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Jp=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function bw(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Vp(t){let e=[],n=[],r=m=>{if(typeof m=="string"){n.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(C=>{if(typeof C=="string"){n.push({type:"text",text:C});return}C&&typeof C=="object"&&C.type==="text"&&C.text&&n.push({...C})})},o=()=>{let m=new Map;for(let C=0;C<n.length;C++){let w=n[C],y=w?.text??JSON.stringify(w),g=m.get(y);if(g===void 0){m.set(y,C);continue}!n[g]?.cache_control&&w?.cache_control&&(n[g]=w),n.splice(C,1),C--}};t.messages.forEach(m=>{m.role==="system"?r(m.content):e.push(m)}),o();let s=[];for(let m=0;m<e.length;m++){let C=e[m];if(C.role==="tool"){let w=C.content;try{typeof C.content=="string"&&(w=JSON.parse(C.content))}catch{}w!=null&&typeof w!="object"&&typeof w!="string"&&(w=String(w));let y={type:"tool_result",tool_use_id:C.tool_call_id,content:w};C.cache_control&&(y.cache_control=C.cache_control);let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(y):s.push({role:"user",content:[y]})}else if(C.role==="user"){let w=[];typeof C.content=="string"?w.push({type:"text",text:C.content}):Array.isArray(C.content)&&C.content.forEach(g=>{g&&typeof g=="object"&&g.type==="image_url"&&g.image_url?.url?w.push({type:"image",source:{type:"base64",media_type:g.media_type||"image/jpeg",data:g.image_url.url.split(",")[1]||g.image_url.url}}):w.push(g)});let y=s[s.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(...w):s.push({role:"user",content:w.length>0?w:[{type:"text",text:" "}]})}else if(C.role==="assistant"){let w=[];C.content&&(typeof C.content=="string"?w.push({type:"text",text:C.content}):Array.isArray(C.content)&&w.push(...C.content)),C.tool_calls&&C.tool_calls.length>0&&C.tool_calls.forEach(g=>{let _={};try{_=JSON.parse(g.function.arguments)}catch{_=g.function.arguments}w.push({type:"tool_use",id:g.id,name:g.function.name,input:_})}),C.thinking&&w.unshift({type:"thinking",thinking:C.thinking.content,signature:C.thinking.signature});let y=s[s.length-1];y&&y.role==="assistant"&&Array.isArray(y.content)?y.content.push(...w):s.push({role:"assistant",content:w.length>0?w:[{type:"text",text:" "}]})}}let a=()=>{let m=n.filter(C=>C?.cache_control).length;for(let C of s)Array.isArray(C.content)&&(m+=C.content.filter(w=>w?.cache_control).length);return m},u=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},l=()=>{for(let m=s.length-1;m>=0;m--){let C=s[m]?.content;if(!Array.isArray(C))continue;let w=C.find(y=>y?.cache_control);if(w?.cache_control)return w.cache_control}for(let m=n.length-1;m>=0;m--)if(n[m]?.cache_control)return n[m].cache_control;return{type:"ephemeral"}},f=(m,C)=>{if(!Array.isArray(m?.content)||m.content.some(y=>y?.cache_control))return!1;let w=m.content.find(y=>y&&typeof y=="object"&&!y.cache_control);return w?(w.cache_control=u(C),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let C=s,w=l(),y=[];for(let g=C.length-1;g>=0;g--)C[g]?.role!=="user"||!Array.isArray(C[g].content)||y.push(g);for(let g of y){if(m<=0)break;f(C[g],w)&&m--}})();let h={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let m=n.some(C=>C?.cache_control);h.system=m?n:n.map(C=>C.text||"").join(`
116
116
 
117
- `)}return t.tools&&t.tools.length>0&&(p.tools=_w(t.tools),t.tool_choice&&(t.tool_choice==="auto"?p.tool_choice={type:"auto"}:t.tool_choice==="any"||t.tool_choice==="required"?p.tool_choice={type:"any"}:typeof t.tool_choice=="string"?p.tool_choice={type:"tool",name:t.tool_choice}:typeof t.tool_choice=="object"&&t.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:t.tool_choice.function.name}))),p}var Ni=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n){let r={};return this.useBearer?(r.authorization=`Bearer ${n.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=n.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let n=[];if(e.system){if(typeof e.system=="string")n.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));n.push({role:"system",content:s})}}let r=JSON.parse(JSON.stringify(e.messages||[]));r?.forEach(s=>{s.role==="system"&&n.push({role:"system",content:s.content})}),r?.forEach(s=>{if(s.role!=="system"&&(s.role==="user"||s.role==="assistant")){if(typeof s.content=="string"){n.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);a.length&&a.forEach(l=>{let f={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};n.push(f)});let u=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);u.length&&n.push({role:"user",content:u.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Gp(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},u=s.content.filter(d=>d.type==="text"&&d.text);u.length&&(a.content=u.map(d=>d.text).join(`
118
- `));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let f=s.content.find(d=>d.type==="thinking");f&&(a.thinking={content:f.thinking,signature:f.signature}),n.push(a)}return}}});let o={messages:n,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&&(o.reasoning={effort:Wp(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformRequestIn(e,n,r){if(!this.isAnthropicMessagesEndpoint(n.baseUrl))return e;r&&r.req&&(r.req.isTargetAnthropic=!0);let o=Jp(e),s={};return this.useBearer?(s.authorization=`Bearer ${n.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=n.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:o,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,n){if(n?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema}}))}async convertOpenAIStreamToAnthropic(e,n){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,u=null,l="unknown",f=!1,d=!1,p=!1,m=new Map,b=new Map,w=0,y=0,g=0,_=!1,A=!1,C=0,v=-1,T=()=>{let P=C;return C++,P},R=P=>{if(!_)try{o.enqueue(P);let K=new TextDecoder().decode(P);this.logger.debug({reqId:n.req.id,data:K,type:"send data"})}catch(K){if(K instanceof TypeError&&K.message.includes("Controller is already closed"))_=!0;else throw this.logger.debug({reqId:n.req.id,error:K instanceof Error?K.message:String(K),type:"send data error"}),K}},$=()=>{if(!_)try{if(!f){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),o.close(),_=!0;return}if(v>=0){let K={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
117
+ `)}return t.tools&&t.tools.length>0&&(h.tools=bw(t.tools),t.tool_choice&&(t.tool_choice==="auto"?h.tool_choice={type:"auto"}:t.tool_choice==="any"||t.tool_choice==="required"?h.tool_choice={type:"any"}:typeof t.tool_choice=="string"?h.tool_choice={type:"tool",name:t.tool_choice}:typeof t.tool_choice=="object"&&t.tool_choice.type==="function"&&(h.tool_choice={type:"tool",name:t.tool_choice.function.name}))),h}var Ni=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n){let r={};return this.useBearer?(r.authorization=`Bearer ${n.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=n.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let n=[];if(e.system){if(typeof e.system=="string")n.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));n.push({role:"system",content:s})}}let r=JSON.parse(JSON.stringify(e.messages||[]));r?.forEach(s=>{s.role==="system"&&n.push({role:"system",content:s.content})}),r?.forEach(s=>{if(s.role!=="system"&&(s.role==="user"||s.role==="assistant")){if(typeof s.content=="string"){n.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);a.length&&a.forEach(l=>{let f={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};n.push(f)});let u=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);u.length&&n.push({role:"user",content:u.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Jp(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},u=s.content.filter(d=>d.type==="text"&&d.text);u.length&&(a.content=u.map(d=>d.text).join(`
118
+ `));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let f=s.content.find(d=>d.type==="thinking");f&&(a.thinking={content:f.thinking,signature:f.signature}),n.push(a)}return}}});let o={messages:n,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&&(o.reasoning={effort:Gp(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformRequestIn(e,n,r){if(!this.isAnthropicMessagesEndpoint(n.baseUrl))return e;r&&r.req&&(r.req.isTargetAnthropic=!0);let o=Vp(e),s={};return this.useBearer?(s.authorization=`Bearer ${n.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=n.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:o,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,n){if(n?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema}}))}async convertOpenAIStreamToAnthropic(e,n){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,u=null,l="unknown",f=!1,d=!1,h=!1,m=new Map,C=new Map,w=0,y=0,g=0,_=!1,E=!1,b=0,S=-1,v=()=>{let P=b;return b++,P},R=P=>{if(!_)try{o.enqueue(P);let K=new TextDecoder().decode(P);this.logger.debug({reqId:n.req.id,data:K,type:"send data"})}catch(K){if(K instanceof TypeError&&K.message.includes("Controller is already closed"))_=!0;else throw this.logger.debug({reqId:n.req.id,error:K instanceof Error?K.message:String(K),type:"send data error"}),K}},$=()=>{if(!_)try{if(!f){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),o.close(),_=!0;return}if(S>=0){let K={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
119
119
  data: ${JSON.stringify(K)}
120
120
 
121
- `)),v=-1}if(u)R(s.encode(`event: message_delta
121
+ `)),S=-1}if(u)R(s.encode(`event: message_delta
122
122
  data: ${JSON.stringify(u)}
123
123
 
124
124
  `)),u=null;else{let K=n?.req?.tokenCount||0;R(s.encode(`event: message_delta
@@ -127,228 +127,228 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
127
127
  `))}let P={type:"message_stop"};R(s.encode(`event: message_stop
128
128
  data: ${JSON.stringify(P)}
129
129
 
130
- `)),o.close(),_=!0}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))_=!0;else throw P}},G=null;try{G=e.getReader();let P=new TextDecoder,K="";for(;!_;){let{done:z,value:Y}=await G.read();if(z)break;K+=P.decode(Y,{stream:!0});let Q=K.split(`
130
+ `)),o.close(),_=!0}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))_=!0;else throw P}},H=null;try{H=e.getReader();let P=new TextDecoder,K="";for(;!_;){let{done:q,value:Y}=await H.read();if(q)break;K+=P.decode(Y,{stream:!0});let Q=K.split(`
131
131
  `);K=Q.pop()||"";for(let ee of Q){if(_)break;if(!ee.startsWith("data:"))continue;let oe=ee.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:oe}),oe!=="[DONE]")try{let se=JSON.parse(oe);if(w++,this.logger.debug({reqId:n.req.id,response:se,tppe:"Original Response"}),se.error){n?.req&&(n.req.sseError=se.error);let J={type:"error",message:{type:"api_error",message:JSON.stringify(se.error)}};R(s.encode(`event: error
132
132
  data: ${JSON.stringify(J)}
133
133
 
134
- `));continue}if(l=se.model||l,!f&&!_&&!p){f=!0;let J=n?.req?.tokenCount||0,Z={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:J,output_tokens:0}}};R(s.encode(`event: message_start
134
+ `));continue}if(l=se.model||l,!f&&!_&&!h){f=!0;let J=n?.req?.tokenCount||0,Z={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:J,output_tokens:0}}};R(s.encode(`event: message_start
135
135
  data: ${JSON.stringify(Z)}
136
136
 
137
- `))}let he=se.choices?.[0];if(se.usage){let J=se.usage?.prompt_tokens_details?.cached_tokens||0,ue=(se.usage?.prompt_tokens||0)-J,je=se.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:n.req.id,phase:"anthropic_transformer_usage",providerUsage:se.usage,mappedUsage:{input_tokens:ue,output_tokens:je,cache_read_input_tokens:J},choicesLength:Array.isArray(se.choices)?se.choices.length:void 0,finishReason:he?.finish_reason});let Ce={input_tokens:ue,output_tokens:je,cache_read_input_tokens:J};if(!u)u={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...Ce}};else{let V=u.usage||{};u.usage={input_tokens:Ce.input_tokens||V.input_tokens||0,output_tokens:Ce.output_tokens||V.output_tokens||0,cache_read_input_tokens:Ce.cache_read_input_tokens||V.cache_read_input_tokens||0}}}if(!he)continue;if(he?.delta?.thinking&&!_&&!p&&!d){if(!A){let J=T(),Z={type:"content_block_start",index:J,content_block:{type:"thinking",thinking:""}};R(s.encode(`event: content_block_start
137
+ `))}let he=se.choices?.[0];if(se.usage){let J=se.usage?.prompt_tokens_details?.cached_tokens||0,ue=(se.usage?.prompt_tokens||0)-J,je=se.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:n.req.id,phase:"anthropic_transformer_usage",providerUsage:se.usage,mappedUsage:{input_tokens:ue,output_tokens:je,cache_read_input_tokens:J},choicesLength:Array.isArray(se.choices)?se.choices.length:void 0,finishReason:he?.finish_reason});let Ce={input_tokens:ue,output_tokens:je,cache_read_input_tokens:J};if(!u)u={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...Ce}};else{let V=u.usage||{};u.usage={input_tokens:Ce.input_tokens||V.input_tokens||0,output_tokens:Ce.output_tokens||V.output_tokens||0,cache_read_input_tokens:Ce.cache_read_input_tokens||V.cache_read_input_tokens||0}}}if(!he)continue;if(he?.delta?.thinking&&!_&&!h&&!d){if(!E){let J=v(),Z={type:"content_block_start",index:J,content_block:{type:"thinking",thinking:""}};R(s.encode(`event: content_block_start
138
138
  data: ${JSON.stringify(Z)}
139
139
 
140
- `)),v=J,A=!0}if(he.delta.thinking.signature){let J={type:"content_block_delta",index:v,delta:{type:"signature_delta",signature:he.delta.thinking.signature}};R(s.encode(`event: content_block_delta
140
+ `)),S=J,E=!0}if(he.delta.thinking.signature){let J={type:"content_block_delta",index:S,delta:{type:"signature_delta",signature:he.delta.thinking.signature}};R(s.encode(`event: content_block_delta
141
141
  data: ${JSON.stringify(J)}
142
142
 
143
- `));let Z={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
143
+ `));let Z={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
144
144
  data: ${JSON.stringify(Z)}
145
145
 
146
- `)),v=-1}else if(he.delta.thinking.content){let J={type:"content_block_delta",index:v,delta:{type:"thinking_delta",thinking:he.delta.thinking.content||""}};R(s.encode(`event: content_block_delta
146
+ `)),S=-1}else if(he.delta.thinking.content){let J={type:"content_block_delta",index:S,delta:{type:"thinking_delta",thinking:he.delta.thinking.content||""}};R(s.encode(`event: content_block_delta
147
147
  data: ${JSON.stringify(J)}
148
148
 
149
- `))}}if(he?.delta?.content&&!_&&!p){if(y++,v>=0&&!d){let Z={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
149
+ `))}}if(he?.delta?.content&&!_&&!h){if(y++,S>=0&&!d){let Z={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
150
150
  data: ${JSON.stringify(Z)}
151
151
 
152
- `)),v=-1}if(!d&&!p){d=!0;let J=T(),Z={type:"content_block_start",index:J,content_block:{type:"text",text:""}};R(s.encode(`event: content_block_start
152
+ `)),S=-1}if(!d&&!h){d=!0;let J=v(),Z={type:"content_block_start",index:J,content_block:{type:"text",text:""}};R(s.encode(`event: content_block_start
153
153
  data: ${JSON.stringify(Z)}
154
154
 
155
- `)),v=J}if(!_&&!p){let J={type:"content_block_delta",index:v,delta:{type:"text_delta",text:he.delta.content}};R(s.encode(`event: content_block_delta
155
+ `)),S=J}if(!_&&!h){let J={type:"content_block_delta",index:S,delta:{type:"text_delta",text:he.delta.content}};R(s.encode(`event: content_block_delta
156
156
  data: ${JSON.stringify(J)}
157
157
 
158
- `))}}if(he?.delta?.annotations?.length&&!_&&!p){if(v>=0&&d){let J={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
158
+ `))}}if(he?.delta?.annotations?.length&&!_&&!h){if(S>=0&&d){let J={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
159
159
  data: ${JSON.stringify(J)}
160
160
 
161
- `)),v=-1,d=!1}he?.delta?.annotations.forEach(J=>{let Z=T(),ue={type:"content_block_start",index:Z,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${qt()}`,content:[{type:"web_search_result",title:J.url_citation.title,url:J.url_citation.url}]}};R(s.encode(`event: content_block_start
161
+ `)),S=-1,d=!1}he?.delta?.annotations.forEach(J=>{let Z=v(),ue={type:"content_block_start",index:Z,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${pt()}`,content:[{type:"web_search_result",title:J.url_citation.title,url:J.url_citation.url}]}};R(s.encode(`event: content_block_start
162
162
  data: ${JSON.stringify(ue)}
163
163
 
164
164
  `));let je={type:"content_block_stop",index:Z};R(s.encode(`event: content_block_stop
165
165
  data: ${JSON.stringify(je)}
166
166
 
167
- `)),v=-1})}if(he?.delta?.tool_calls&&!_&&!p){g++;let J=new Set;for(let Z of he.delta.tool_calls){if(_)break;let ue=Z.index??0;if(J.has(ue))continue;if(J.add(ue),!b.has(ue)){if(v>=0){let Oe={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
167
+ `)),S=-1})}if(he?.delta?.tool_calls&&!_&&!h){g++;let J=new Set;for(let Z of he.delta.tool_calls){if(_)break;let ue=Z.index??0;if(J.has(ue))continue;if(J.add(ue),!C.has(ue)){if(S>=0){let Oe={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
168
168
  data: ${JSON.stringify(Oe)}
169
169
 
170
- `)),v=-1}let Ce=T();b.set(ue,Ce);let V=Z.id||`call_ccr_${ue}`,ae=Z.function?.name||`tool_${ue}`,te={type:"content_block_start",index:Ce,content_block:{type:"tool_use",id:V,name:ae,input:{}}};R(s.encode(`event: content_block_start
170
+ `)),S=-1}let Ce=v();C.set(ue,Ce);let V=Z.id||`call_ccr_${ue}`,ae=Z.function?.name||`tool_${ue}`,te={type:"content_block_start",index:Ce,content_block:{type:"tool_use",id:V,name:ae,input:{}}};R(s.encode(`event: content_block_start
171
171
  data: ${JSON.stringify(te)}
172
172
 
173
- `)),v=Ce;let ve={id:V,name:ae,arguments:"",contentBlockIndex:Ce};m.set(ue,ve)}else if(Z.id&&Z.function?.name){let Ce=m.get(ue);Ce.id.startsWith("call_")&&Ce.name.startsWith("tool_")&&(Ce.id=Z.id,Ce.name=Z.function.name)}if(Z.function?.arguments&&!_&&!p){let Ce=b.get(ue);if(Ce===void 0)continue;let V=m.get(ue);V&&(V.arguments+=Z.function.arguments);try{let ae={type:"content_block_delta",index:Ce,delta:{type:"input_json_delta",partial_json:Z.function.arguments}};R(s.encode(`event: content_block_delta
173
+ `)),S=Ce;let Te={id:V,name:ae,arguments:"",contentBlockIndex:Ce};m.set(ue,Te)}else if(Z.id&&Z.function?.name){let Ce=m.get(ue);Ce.id.startsWith("call_")&&Ce.name.startsWith("tool_")&&(Ce.id=Z.id,Ce.name=Z.function.name)}if(Z.function?.arguments&&!_&&!h){let Ce=C.get(ue);if(Ce===void 0)continue;let V=m.get(ue);V&&(V.arguments+=Z.function.arguments);try{let ae={type:"content_block_delta",index:Ce,delta:{type:"input_json_delta",partial_json:Z.function.arguments}};R(s.encode(`event: content_block_delta
174
174
  data: ${JSON.stringify(ae)}
175
175
 
176
176
  `))}catch{try{let ae=Z.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),te={type:"content_block_delta",index:Ce,delta:{type:"input_json_delta",partial_json:ae}};R(s.encode(`event: content_block_delta
177
177
  data: ${JSON.stringify(te)}
178
178
 
179
- `))}catch(ae){console.error(ae)}}}}}if(he?.finish_reason&&!_&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),v>=0){let J={type:"content_block_stop",index:v};R(s.encode(`event: content_block_stop
179
+ `))}catch(ae){console.error(ae)}}}}}if(he?.finish_reason&&!_&&!h){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),S>=0){let J={type:"content_block_stop",index:S};R(s.encode(`event: content_block_stop
180
180
  data: ${JSON.stringify(J)}
181
181
 
182
- `)),v=-1}if(!_){let Z={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[he.finish_reason]||"end_turn";u?u.delta={...u.delta,stop_reason:Z,stop_sequence:null}:u={type:"message_delta",delta:{stop_reason:Z,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(se){this.logger?.error(`parseError: ${se.name} message: ${se.message} stack: ${se.stack} data: ${oe}`)}}}$()}catch(P){if(!_)try{o.error(P)}catch(K){console.error(K)}}finally{if(G)try{G.releaseLock()}catch(P){console.error(P)}}},cancel:o=>{this.logger.debug({reqId:n.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message.annotations){let l=`srvtoolu_${qt()}`;o.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:l,content:r.message.annotations.map(f=>({type:"web_search_result",url:f.url_citation.url,title:f.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(l=>{let f={};try{let d=l.function.arguments||"{}";typeof d=="object"?f=d:typeof d=="string"&&(f=JSON.parse(d))}catch{f={text:l.function.arguments||""}}o.push({type:"tool_use",id:l.id,name:l.function.name,input:f})}),r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,u={id:e.id?.startsWith("msg_")?e.id:`msg_${qt().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":r.finish_reason==="length"?"max_tokens":r.finish_reason==="tool_calls"?"tool_use":r.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:n.req.id,result:u},"Conversion complete, final Anthropic response"),u}catch{throw He(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var to={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function bw(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(to).includes(r)?r:to.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(to).includes(o)?o:to.TYPE_UNSPECIFIED})}}}function Jo(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&bw(t.type,e);for(let[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(u))continue;let l=u.toUpperCase();e.type=Object.values(to).includes(l)?l:to.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=Jo(u);else if(r.includes(a)){let l=[];for(let f of u){if(f.type=="null"){e.nullable=!0;continue}l.push(Jo(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(u))l[f]=Jo(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=u}return e}function Cw(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=Jo(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Jo(e.response));return t}function Bi(t){let e=[],n=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));n?.length&&e.push(Cw({functionDeclarations:n})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let f;l.role==="assistant"?f="model":(["user","system"].includes(l.role),f="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=>{let m={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(m.thoughtSignature=l.thinking.signature),m})),d.length===0&&d.push({text:""}),o.push({role:f,parts:d}),f==="model"&&l.tool_calls){let p=l.tool_calls.map(m=>{let b=s.find(w=>w.tool_call_id===m.id);return{functionResponse:{name:m?.function?.name,response:{result:b?.content}}}});o.push({role:"user",parts:p})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],f,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?f=d:d<l[0]?f=l[0]:d>l[1]&&(f=l[1]),a.thinkingConfig.thinkingBudget=f)}let u={contents:o,tools:e.length?e:void 0,generationConfig:a};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]),u.toolConfig=l}return u}function Mi(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,u=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:u};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?l.messages.push({role:"user",content:f}):typeof f.text=="string"?l.messages.push({role:"user",content:f.text||null}):f.role==="user"?l.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&l.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(f=>{Array.isArray(f.functionDeclarations)&&f.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function Li(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json();n?.debug({response:r},`${e} response:`);let o="",s="",a=r.candidates[0]?.content?.parts||[],u=[];for(let p of a)p.text&&p.thought===!0?o+=p.text:u.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=u?.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||{})}}))||[],f=u?.filter(p=>p.text)?.map(p=>p.text)?.join(`
183
- `)||"",d={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:f,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.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 r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,u=!1,l="",f=0,d=-1,p=new ReadableStream({async start(m){let b=async(g,_)=>{if(g.startsWith("data: ")){let A=g.slice(6).trim();if(A){n?.debug({chunkStr:A},`${e} chunk:`);try{let C=JSON.parse(A);if(!C.candidates||!C.candidates[0]){n?.debug({chunkStr:A},"Invalid chunk structure");return}let v=C.candidates[0],T=v.content?.parts||[];T.filter(P=>P.text&&P.thought===!0).forEach(P=>{u||(u=!0);let K={choices:[{delta:{role:"assistant",content:null,thinking:{content:P.text}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
182
+ `)),S=-1}if(!_){let Z={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[he.finish_reason]||"end_turn";u?u.delta={...u.delta,stop_reason:Z,stop_sequence:null}:u={type:"message_delta",delta:{stop_reason:Z,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}h=!0}}catch(se){this.logger?.error(`parseError: ${se.name} message: ${se.message} stack: ${se.stack} data: ${oe}`)}}}$()}catch(P){if(!_)try{o.error(P)}catch(K){console.error(K)}}finally{if(H)try{H.releaseLock()}catch(P){console.error(P)}}},cancel:o=>{this.logger.debug({reqId:n.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message.annotations){let l=`srvtoolu_${pt()}`;o.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:l,content:r.message.annotations.map(f=>({type:"web_search_result",url:f.url_citation.url,title:f.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(l=>{let f={};try{let d=l.function.arguments||"{}";typeof d=="object"?f=d:typeof d=="string"&&(f=JSON.parse(d))}catch{f={text:l.function.arguments||""}}o.push({type:"tool_use",id:l.id,name:l.function.name,input:f})}),r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,u={id:e.id?.startsWith("msg_")?e.id:`msg_${pt().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":r.finish_reason==="length"?"max_tokens":r.finish_reason==="tool_calls"?"tool_use":r.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:n.req.id,result:u},"Conversion complete, final Anthropic response"),u}catch{throw He(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var to={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function Cw(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(to).includes(r)?r:to.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(to).includes(o)?o:to.TYPE_UNSPECIFIED})}}}function Jo(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&Cw(t.type,e);for(let[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(u))continue;let l=u.toUpperCase();e.type=Object.values(to).includes(l)?l:to.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=Jo(u);else if(r.includes(a)){let l=[];for(let f of u){if(f.type=="null"){e.nullable=!0;continue}l.push(Jo(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(u))l[f]=Jo(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=u}return e}function ww(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=Jo(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Jo(e.response));return t}function Bi(t){let e=[],n=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));n?.length&&e.push(ww({functionDeclarations:n})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let f;l.role==="assistant"?f="model":(["user","system"].includes(l.role),f="user");let d=[];if(typeof l.content=="string"){let h={text:l.content};l.thinking?.signature&&(h.thoughtSignature=l.thinking.signature),d.push(h)}else Array.isArray(l.content)?d.push(...l.content.map(h=>{if(h.type==="text")return{text:h.text||""};if(h.type==="image_url")return h.image_url.url.startsWith("http")?{file_data:{mime_type:h.media_type,file_uri:h.image_url.url}}:{inlineData:{mime_type:h.media_type,data:h.image_url.url?.split(",")?.pop()||h.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(h=>{let m={functionCall:{id:h.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:h.function.name,args:JSON.parse(h.function.arguments||"{}")}};return l.thinking?.signature&&(m.thoughtSignature=l.thinking.signature),m})),d.length===0&&d.push({text:""}),o.push({role:f,parts:d}),f==="model"&&l.tool_calls){let h=l.tool_calls.map(m=>{let C=s.find(w=>w.tool_call_id===m.id);return{functionResponse:{name:m?.function?.name,response:{result:C?.content}}}});o.push({role:"user",parts:h})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],f,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?f=d:d<l[0]?f=l[0]:d>l[1]&&(f=l[1]),a.thinkingConfig.thinkingBudget=f)}let u={contents:o,tools:e.length?e:void 0,generationConfig:a};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]),u.toolConfig=l}return u}function Mi(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,u=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:u};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?l.messages.push({role:"user",content:f}):typeof f.text=="string"?l.messages.push({role:"user",content:f.text||null}):f.role==="user"?l.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&l.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(f=>{Array.isArray(f.functionDeclarations)&&f.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function Li(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json();n?.debug({response:r},`${e} response:`);let o="",s="",a=r.candidates[0]?.content?.parts||[],u=[];for(let h of a)h.text&&h.thought===!0?o+=h.text:u.push(h);s=a.find(h=>h.thoughtSignature)?.thoughtSignature;let l=u?.filter(h=>h.functionCall)?.map(h=>({id:h.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:h.functionCall?.name,arguments:JSON.stringify(h.functionCall?.args||{})}}))||[],f=u?.filter(h=>h.text)?.map(h=>h.text)?.join(`
183
+ `)||"",d={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:f,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.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 r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,u=!1,l="",f=0,d=-1,h=new ReadableStream({async start(m){let C=async(g,_)=>{if(g.startsWith("data: ")){let E=g.slice(6).trim();if(E){n?.debug({chunkStr:E},`${e} chunk:`);try{let b=JSON.parse(E);if(!b.candidates||!b.candidates[0]){n?.debug({chunkStr:E},"Invalid chunk structure");return}let S=b.candidates[0],v=S.content?.parts||[];v.filter(P=>P.text&&P.thought===!0).forEach(P=>{u||(u=!0);let K={choices:[{delta:{role:"assistant",content:null,thinking:{content:P.text}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
184
184
 
185
- `))});let R=T.find(P=>P.thoughtSignature)?.thoughtSignature;if(R&&!s){if(!u){let K={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
185
+ `))});let R=v.find(P=>P.thoughtSignature)?.thoughtSignature;if(R&&!s){if(!u){let K={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
186
186
 
187
- `))}let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:R}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(_.enqueue(o.encode(`data: ${JSON.stringify(P)}
187
+ `))}let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:R}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(_.enqueue(o.encode(`data: ${JSON.stringify(P)}
188
188
 
189
- `)),s=!0,f++,l){let K={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
189
+ `)),s=!0,f++,l){let K={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(K)}
190
190
 
191
- `)),l="",a||(a=!0)}}let $=T.filter(P=>P.functionCall).map(P=>({id:P.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:P.functionCall?.name,arguments:JSON.stringify(P.functionCall?.args||{})}})),G=T.filter(P=>P.text&&P.thought!==!0).map(P=>P.text).join(`
192
- `);if(!G&&s&&!a){let P={choices:[{delta:{role:"assistant",content:"(no content)"},index:f,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(P)}
191
+ `)),l="",a||(a=!0)}}let $=v.filter(P=>P.functionCall).map(P=>({id:P.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:P.functionCall?.name,arguments:JSON.stringify(P.functionCall?.args||{})}})),H=v.filter(P=>P.text&&P.thought!==!0).map(P=>P.text).join(`
192
+ `);if(!H&&s&&!a){let P={choices:[{delta:{role:"assistant",content:"(no content)"},index:f,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(P)}
193
193
 
194
- `)),a||(a=!0)}if(u&&G&&!s)if(C.modelVersion.includes("3")){l+=G;return}else{let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(P)}
194
+ `)),a||(a=!0)}if(u&&H&&!s)if(b.modelVersion.includes("3")){l+=H;return}else{let P={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(o.encode(`data: ${JSON.stringify(P)}
195
195
 
196
- `)),s=!0}if(G){l||f++;let P={choices:[{delta:{role:"assistant",content:G},finish_reason:v.finishReason?.toLowerCase()||null,index:f,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}}};v?.groundingMetadata?.groundingChunks?.length&&(P.choices[0].delta.annotations=v.groundingMetadata.groundingChunks.map((K,z)=>{let Y=v?.groundingMetadata?.groundingSupports?.filter(Q=>Q.groundingChunkIndices?.includes(z));return{type:"url_citation",url_citation:{url:K?.web?.uri||"",title:K?.web?.title||"",content:Y?.[0]?.segment?.text||"",start_index:Y?.[0]?.segment?.startIndex||0,end_index:Y?.[0]?.segment?.endIndex||0}}})),_.enqueue(o.encode(`data: ${JSON.stringify(P)}
196
+ `)),s=!0}if(H){l||f++;let P={choices:[{delta:{role:"assistant",content:H},finish_reason:S.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};S?.groundingMetadata?.groundingChunks?.length&&(P.choices[0].delta.annotations=S.groundingMetadata.groundingChunks.map((K,q)=>{let Y=S?.groundingMetadata?.groundingSupports?.filter(Q=>Q.groundingChunkIndices?.includes(q));return{type:"url_citation",url_citation:{url:K?.web?.uri||"",title:K?.web?.title||"",content:Y?.[0]?.segment?.text||"",start_index:Y?.[0]?.segment?.startIndex||0,end_index:Y?.[0]?.segment?.endIndex||0}}})),_.enqueue(o.encode(`data: ${JSON.stringify(P)}
197
197
 
198
- `)),!a&&G&&(a=!0)}$.length>0&&($.forEach(P=>{f++,d++;let K={choices:[{delta:{role:"assistant",tool_calls:[{...P,index:d}]},finish_reason:v.finishReason?.toLowerCase()||null,index:f,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}}};v?.groundingMetadata?.groundingChunks?.length&&(K.choices[0].delta.annotations=v.groundingMetadata.groundingChunks.map((z,Y)=>{let Q=v?.groundingMetadata?.groundingSupports?.filter(ee=>ee.groundingChunkIndices?.includes(Y));return{type:"url_citation",url_citation:{url:z?.web?.uri||"",title:z?.web?.title||"",content:Q?.[0]?.segment?.text||"",start_index:Q?.[0]?.segment?.startIndex||0,end_index:Q?.[0]?.segment?.endIndex||0}}})),_.enqueue(o.encode(`data: ${JSON.stringify(K)}
198
+ `)),!a&&H&&(a=!0)}$.length>0&&($.forEach(P=>{f++,d++;let K={choices:[{delta:{role:"assistant",tool_calls:[{...P,index:d}]},finish_reason:S.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};S?.groundingMetadata?.groundingChunks?.length&&(K.choices[0].delta.annotations=S.groundingMetadata.groundingChunks.map((q,Y)=>{let Q=S?.groundingMetadata?.groundingSupports?.filter(ee=>ee.groundingChunkIndices?.includes(Y));return{type:"url_citation",url_citation:{url:q?.web?.uri||"",title:q?.web?.title||"",content:Q?.[0]?.segment?.text||"",start_index:Q?.[0]?.segment?.startIndex||0,end_index:Q?.[0]?.segment?.endIndex||0}}})),_.enqueue(o.encode(`data: ${JSON.stringify(K)}
199
199
 
200
- `))}),!a&&G&&(a=!0))}catch(C){n?.error(`Error parsing ${e} stream chunk`,A,C.message)}}}},w=t.body.getReader(),y="";try{for(;;){let{done:g,value:_}=await w.read();if(g){y&&await b(y,m);break}y+=r.decode(_,{stream:!0});let A=y.split(`
201
- `);y=A.pop()||"";for(let C of A)await b(C,m)}}catch(g){m.error(g)}finally{m.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ji=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,n){return{body:Bi(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}transformRequestOut=Mi;async transformResponseOut(e){return Li(e,this.name,this.logger)}};async function zv(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xe(Xd(),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:
200
+ `))}),!a&&H&&(a=!0))}catch(b){n?.error(`Error parsing ${e} stream chunk`,E,b.message)}}}},w=t.body.getReader(),y="";try{for(;;){let{done:g,value:_}=await w.read();if(g){y&&await C(y,m);break}y+=r.decode(_,{stream:!0});let E=y.split(`
201
+ `);y=E.pop()||"";for(let b of E)await C(b,m)}}catch(g){m.error(g)}finally{m.close()}}});return new Response(h,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ji=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,n){return{body:Bi(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}transformRequestOut=Mi;async transformResponseOut(e){return Li(e,this.name,this.logger)}};async function HT(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xe(Zd(),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:
202
202
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
203
203
  2. Run "gcloud auth application-default login"
204
- 3. Use Google Cloud environment with default service account`)}}var nu=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let u=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(u);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 s=await zv();return{body:Bi(e),config:{url:new URL(`./v1beta1/projects/${r}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Mi(e)}async transformResponseOut(e){return Li(e,this.name)}};var ru=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let n=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),r=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||n;return r&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,u="";if(typeof o.content=="string"){let f=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);f&&(u=f[1].trim(),o.content=o.content.replace(f[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):u&&(o.reasoning_content=u),r&&!o.reasoning_content&&(o.reasoning_content=" "),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,b,w)=>{let y=m.split(`
205
- `);for(let g of y)g.trim()&&b.enqueue(w.encode(g+`
206
- `))},p=(m,b)=>{let{controller:w,encoder:y}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let g=JSON.parse(m.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(_)}
204
+ 3. Use Google Cloud environment with default service account`)}}var nu=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let u=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(u);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 s=await HT();return{body:Bi(e),config:{url:new URL(`./v1beta1/projects/${r}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Mi(e)}async transformResponseOut(e){return Li(e,this.name)}};var ru=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let n=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),r=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||n;return r&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,u="";if(typeof o.content=="string"){let f=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);f&&(u=f[1].trim(),o.content=o.content.replace(f[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):u&&(o.reasoning_content=u),r&&!o.reasoning_content&&(o.reasoning_content=" "),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,C,w)=>{let y=m.split(`
205
+ `);for(let g of y)g.trim()&&C.enqueue(w.encode(g+`
206
+ `))},h=(m,C)=>{let{controller:w,encoder:y}=C;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let g=JSON.parse(m.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){C.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(_)}
207
207
 
208
- `;w.enqueue(y.encode(A));return}if(g.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let _="ccr_think_signature",A=g.choices[0].delta.content,C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:_}}}]};delete C.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(C)}
208
+ `;w.enqueue(y.encode(E));return}if(g.choices?.[0]?.delta?.content&&C.reasoningContent()&&!C.isReasoningComplete()){C.setReasoningComplete(!0);let _="ccr_think_signature",E=g.choices[0].delta.content,b={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:C.reasoningContent(),signature:_}}}]};delete b.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(b)}
209
209
 
210
- `;w.enqueue(y.encode(v));let T={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:A}}]};delete T.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(T)}
210
+ `;w.enqueue(y.encode(S));let v={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:E}}]};delete v.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(v)}
211
211
 
212
212
  `;w.enqueue(y.encode(R));return}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){let _=`data: ${JSON.stringify(g)}
213
213
 
214
214
  `;w.enqueue(y.encode(_))}}catch{w.enqueue(y.encode(m+`
215
215
  `))}else w.enqueue(y.encode(m+`
216
- `))};try{for(;;){let{done:m,value:b}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(b,{stream:!0});a+=w;let y=a.split(`
217
- `);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:_=>o+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
216
+ `))};try{for(;;){let{done:m,value:C}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(C,{stream:!0});a+=w;let y=a.split(`
217
+ `);a=y.pop()||"";for(let g of y)if(g.trim())try{h(g,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:_=>o+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
218
218
  `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{f.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(u,{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 ou=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
219
219
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
220
220
  Examples:
221
221
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
222
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="",a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,b,w)=>{let y=m.split(`
223
- `);for(let g of y)g.trim()&&b.enqueue(w.encode(g+`
224
- `))},p=(m,b)=>{let{controller:w,encoder:y,exitToolIndex:g,setExitToolIndex:_,appendExitToolResponse:A}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let C=JSON.parse(m.slice(6));if(C.choices[0]?.delta?.tool_calls?.length){let v=C.choices[0].delta.tool_calls[0];if(v.function?.name==="ExitTool"){_(v.index);return}else if(g()>-1&&v.index===g()&&v.function.arguments){A(v.function.arguments);try{let T=JSON.parse(b.exitToolResponse());C.choices=[{delta:{role:"assistant",content:T.response||""}}];let R=`data: ${JSON.stringify(C)}
222
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="",a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,C,w)=>{let y=m.split(`
223
+ `);for(let g of y)g.trim()&&C.enqueue(w.encode(g+`
224
+ `))},h=(m,C)=>{let{controller:w,encoder:y,exitToolIndex:g,setExitToolIndex:_,appendExitToolResponse:E}=C;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let b=JSON.parse(m.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let S=b.choices[0].delta.tool_calls[0];if(S.function?.name==="ExitTool"){_(S.index);return}else if(g()>-1&&S.index===g()&&S.function.arguments){E(S.function.arguments);try{let v=JSON.parse(C.exitToolResponse());b.choices=[{delta:{role:"assistant",content:v.response||""}}];let R=`data: ${JSON.stringify(b)}
225
225
 
226
- `;w.enqueue(y.encode(R))}catch{}return}}if(C.choices?.[0]?.delta&&Object.keys(C.choices[0].delta).length>0){let v=`data: ${JSON.stringify(C)}
226
+ `;w.enqueue(y.encode(R))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let S=`data: ${JSON.stringify(b)}
227
227
 
228
- `;w.enqueue(y.encode(v))}}catch{w.enqueue(y.encode(m+`
228
+ `;w.enqueue(y.encode(S))}}catch{w.enqueue(y.encode(m+`
229
229
  `))}else w.enqueue(y.encode(m+`
230
- `))};try{for(;;){let{done:m,value:b}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(b,{stream:!0});a+=w;let y=a.split(`
231
- `);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:r,exitToolIndex:()=>o,setExitToolIndex:_=>o=_,exitToolResponse:()=>s,appendExitToolResponse:_=>s+=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
232
- `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{f.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var su=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u=!1,l="",f=new ReadableStream({async start(d){let p=e.body.getReader(),m=(w,y,g)=>{let _=w.split(`
233
- `);for(let A of _)A.trim()&&y.enqueue(g.encode(A+`
234
- `))},b=(w,y)=>{let{controller:g,encoder:_}=y;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]"){let A=w.slice(6);try{let C=JSON.parse(A);if(C.usage&&(this.logger?.debug({usage:C.usage,hasToolCall:u},"usage"),C.choices[0].finish_reason=u?"tool_calls":"stop"),C.choices?.[0]?.finish_reason==="error"){g.enqueue(_.encode(`data: ${JSON.stringify({error:C.choices?.[0].error})}
230
+ `))};try{for(;;){let{done:m,value:C}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(C,{stream:!0});a+=w;let y=a.split(`
231
+ `);a=y.pop()||"";for(let g of y)if(g.trim())try{h(g,{controller:l,encoder:r,exitToolIndex:()=>o,setExitToolIndex:_=>o=_,exitToolResponse:()=>s,appendExitToolResponse:_=>s+=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
232
+ `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{f.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var su=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u=!1,l="",f=new ReadableStream({async start(d){let h=e.body.getReader(),m=(w,y,g)=>{let _=w.split(`
233
+ `);for(let E of _)E.trim()&&y.enqueue(g.encode(E+`
234
+ `))},C=(w,y)=>{let{controller:g,encoder:_}=y;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]"){let E=w.slice(6);try{let b=JSON.parse(E);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:u},"usage"),b.choices[0].finish_reason=u?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(_.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
235
235
 
236
- `));return}C.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0);let v=C.choices?.[0]?.delta?.reasoning||C.choices?.[0]?.delta?.reasoning_content;if(v){y.appendReasoningContent(v);let P={...C,choices:[{...C.choices?.[0],delta:{...C.choices[0].delta,thinking:{content:v}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content);let K=`data: ${JSON.stringify(P)}
236
+ `));return}b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0);let S=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(S){y.appendReasoningContent(S);let P={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:S}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content);let K=`data: ${JSON.stringify(P)}
237
237
 
238
- `;g.enqueue(_.encode(K));return}if(C.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let P="ccr_think_signature",K=C.choices[0].delta.content,z={...C,choices:[{...C.choices?.[0],delta:{...C.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:P}}}]};z.choices?.[0]?.delta&&delete z.choices[0].delta.reasoning;let Y=`data: ${JSON.stringify(z)}
238
+ `;g.enqueue(_.encode(K));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let P="ccr_think_signature",K=b.choices[0].delta.content,q={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:P}}}]};q.choices?.[0]?.delta&&delete q.choices[0].delta.reasoning;let Y=`data: ${JSON.stringify(q)}
239
239
 
240
- `;g.enqueue(_.encode(Y));let Q={...C,choices:[{...C.choices?.[0],delta:{...C.choices[0].delta,content:K}}]};Q.choices?.[0]?.delta&&(delete Q.choices[0].delta.reasoning,delete Q.choices[0].delta.reasoning_content);let ee=`data: ${JSON.stringify(Q)}
240
+ `;g.enqueue(_.encode(Y));let Q={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:K}}]};Q.choices?.[0]?.delta&&(delete Q.choices[0].delta.reasoning,delete Q.choices[0].delta.reasoning_content);let ee=`data: ${JSON.stringify(Q)}
241
241
 
242
- `;g.enqueue(_.encode(ee));return}C.choices?.[0]?.delta?.reasoning&&delete C.choices[0].delta.reasoning,C.choices?.[0]?.delta?.reasoning_content&&delete C.choices[0].delta.reasoning_content,C.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(C.choices?.[0]?.delta?.tool_calls[0].id,10))&&C.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${qt()}`}),C.choices?.[0]?.delta?.tool_calls?.length&&!u&&(u=!0);let T=C.choices?.[0]?.delta,R=T&&Object.keys(T).length>0,$=C.choices?.[0]?.finish_reason,G=C.usage;if(R||$||G){let P=`data: ${JSON.stringify(C)}
242
+ `;g.enqueue(_.encode(ee));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${pt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!u&&(u=!0);let v=b.choices?.[0]?.delta,R=v&&Object.keys(v).length>0,$=b.choices?.[0]?.finish_reason,H=b.usage;if(R||$||H){let P=`data: ${JSON.stringify(b)}
243
243
 
244
244
  `;g.enqueue(_.encode(P))}}catch{g.enqueue(_.encode(w+`
245
245
  `))}}else g.enqueue(_.encode(w+`
246
- `))};try{for(;;){let{done:w,value:y}=await p.read();if(w){l.trim()&&m(l,d,r);break}if(!y||y.length===0)continue;let g;try{g=n.decode(y,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=l.split(`
247
- `);l=A.pop()||"";for(let C of A)if(C.trim())try{b(C,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:v=>o=v,reasoningContent:()=>s,appendReasoningContent:v=>s+=v,isReasoningComplete:()=>a,setReasoningComplete:v=>a=v})}catch(v){console.error("Error processing line:",C,v),d.enqueue(r.encode(C+`
246
+ `))};try{for(;;){let{done:w,value:y}=await h.read();if(w){l.trim()&&m(l,d,r);break}if(!y||y.length===0)continue;let g;try{g=n.decode(y,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=l.split(`
247
+ `);l=E.pop()||"";for(let b of E)if(b.trim())try{C(b,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>s,appendReasoningContent:S=>s+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",b,S),d.enqueue(r.encode(b+`
248
248
  `))}continue}let _=l.split(`
249
- `);l=_.pop()||"";for(let A of _)if(A.trim())try{b(A,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:C=>o=C,reasoningContent:()=>s,appendReasoningContent:C=>s+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",A,C),d.enqueue(r.encode(A+`
250
- `))}}}catch(w){console.error("Stream error:",w),d.error(w)}finally{try{p.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var iu=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var au=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u="",l=new ReadableStream({async start(f){let d=e.body.getReader(),p=(b,w,y)=>{let g=b.split(`
249
+ `);l=_.pop()||"";for(let E of _)if(E.trim())try{C(E,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",E,b),d.enqueue(r.encode(E+`
250
+ `))}}}catch(w){console.error("Stream error:",w),d.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var iu=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var au=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u="",l=new ReadableStream({async start(f){let d=e.body.getReader(),h=(C,w,y)=>{let g=C.split(`
251
251
  `);for(let _ of g)_.trim()&&w.enqueue(y.encode(_+`
252
- `))},m=(b,w)=>{let{controller:y,encoder:g}=w;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let _=b.slice(6);try{let A=JSON.parse(_);if(A.error)throw new Error(JSON.stringify(A));A.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),A.choices?.[0]?.delta?.tool_calls?.length&&A.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${qt()}`}),A.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof A.choices[0].index=="number"?A.choices[0].index+=1:A.choices[0].index=1);let C=`data: ${JSON.stringify(A)}
252
+ `))},m=(C,w)=>{let{controller:y,encoder:g}=w;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let _=C.slice(6);try{let E=JSON.parse(_);if(E.error)throw new Error(JSON.stringify(E));E.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),E.choices?.[0]?.delta?.tool_calls?.length&&E.choices?.[0]?.delta?.tool_calls.forEach(S=>{S.id=`call_${pt()}`}),E.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof E.choices[0].index=="number"?E.choices[0].index+=1:E.choices[0].index=1);let b=`data: ${JSON.stringify(E)}
253
253
 
254
- `;y.enqueue(g.encode(C))}catch{y.enqueue(g.encode(b+`
255
- `))}}else y.enqueue(g.encode(b+`
256
- `))};try{for(;;){let{done:b,value:w}=await d.read();if(b){u.trim()&&p(u,f,r);break}if(!w||w.length===0)continue;let y;try{y=n.decode(w,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(y.length===0)continue;if(u+=y,u.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=u.split(`
257
- `);u=_.pop()||"";for(let A of _)if(A.trim())try{m(A,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:C=>o=C,reasoningContent:()=>s,appendReasoningContent:C=>s+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",A,C),f.enqueue(r.encode(A+`
254
+ `;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(C+`
255
+ `))}}else y.enqueue(g.encode(C+`
256
+ `))};try{for(;;){let{done:C,value:w}=await d.read();if(C){u.trim()&&h(u,f,r);break}if(!w||w.length===0)continue;let y;try{y=n.decode(w,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(y.length===0)continue;if(u+=y,u.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=u.split(`
257
+ `);u=_.pop()||"";for(let E of _)if(E.trim())try{m(E,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",E,b),f.enqueue(r.encode(E+`
258
258
  `))}continue}let g=u.split(`
259
- `);u=g.pop()||"";for(let _ of g)if(_.trim())try{m(_,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>a,setReasoningComplete:A=>a=A})}catch(A){console.error("Error processing line:",_,A),f.enqueue(r.encode(_+`
260
- `))}}}catch(b){console.error("Stream error:",b),f.error(b)}finally{try{d.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}f.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 uu=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),e}};var i_=xe(fc());var In=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function Z0(t){return/^[0-9A-Fa-f]$/.test(t)}function tr(t){return t>="0"&&t<="9"}function e_(t){return t>=" "}function As(t){return`,:[]/{}()
261
- +`.includes(t)}function Zd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function ef(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var tf=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,nf=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function rf(t){return`,[]/{}
262
- +`.includes(t)}function of(t){return Ss(t)||Hv.test(t)}var Hv=/^[[{\w-]$/;function t_(t){return t===`
263
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function er(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function n_(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function r_(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Ss(t){return sf(t)||cu(t)}function sf(t){return t==='"'||t==="\u201C"||t==="\u201D"}function af(t){return t==='"'}function cu(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function uf(t){return t==="'"}function Ro(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Nt(t,e){let n=t.length;if(!er(t,n-1))return t+e;for(;er(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function o_(t,e,n){return t.substring(0,e)+t.substring(e+n)}function s_(t){return/[,\n][ \t\r]*$/.test(t)}var Wv={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Gv={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
264
- `,r:"\r",t:" "};function cf(t){let e=0,n="";f(["```","[```","{```"]),s()||ee(),f(["```","```]","```}"]);let o=p(",");for(o&&a(),of(t[e])&&s_(n)?(o||(n=Nt(n,",")),_()):o&&(n=Ro(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;Q();function s(){a();let J=y()||g()||A()||v()||T()||$(!1)||G();return a(),J}function a(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ue=u(J);do ue=l(),ue&&(ue=u(J));while(ue);return e>Z}function u(J){let Z=J?er:n_,ue="";for(;;)if(Z(t,e))ue+=t[e],e++;else if(r_(t,e))ue+=" ",e++;else break;return ue.length>0?(n+=ue,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Jv(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
265
- `;)e++;return!0}return!1}function f(J){if(d(J)){if(Zd(t[e]))for(;e<t.length&&ef(t[e]);)e++;return a(),!0}return!1}function d(J){u(!0);for(let Z of J){let ue=e+Z.length;if(t.slice(e,ue)===Z)return e=ue,!0}return!1}function p(J){return t[e]===J?(n+=t[e],e++,!0):!1}function m(J){return t[e]===J?(e++,!0):!1}function b(){return m("\\")}function w(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),m(","),!0):!1}function y(){if(t[e]==="{"){n+="{",e++,a(),m(",")&&a();let J=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(J?(Z=!0,J=!1):(Z=p(","),Z||(n=Nt(n,",")),a()),w(),!(A()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=Ro(n,","):oe();break}a();let je=p(":"),Ce=e>=t.length;je||(of(t[e])||Ce?n=Nt(n,":"):se()),s()||(je||Ce?n+="null":se())}return t[e]==="}"?(n+="}",e++):n=Nt(n,"}"),!0}return!1}function g(){if(t[e]==="["){n+="[",e++,a(),m(",")&&a();let J=!0;for(;e<t.length&&t[e]!=="]";)if(J?J=!1:p(",")||(n=Nt(n,",")),w(),!s()){n=Ro(n,",");break}return t[e]==="]"?(n+="]",e++):n=Nt(n,"]"),!0}return!1}function _(){let J=!0,Z=!0;for(;Z;)J?J=!1:p(",")||(n=Nt(n,",")),Z=s();Z||(n=Ro(n,",")),n=`[
259
+ `);u=g.pop()||"";for(let _ of g)if(_.trim())try{m(_,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",_,E),f.enqueue(r.encode(_+`
260
+ `))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{d.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.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 uu=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),e}};var a_=xe(hc());var In=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function e_(t){return/^[0-9A-Fa-f]$/.test(t)}function tr(t){return t>="0"&&t<="9"}function t_(t){return t>=" "}function As(t){return`,:[]/{}()
261
+ +`.includes(t)}function ef(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function tf(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var nf=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,rf=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function of(t){return`,[]/{}
262
+ +`.includes(t)}function sf(t){return Ss(t)||WT.test(t)}var WT=/^[[{\w-]$/;function n_(t){return t===`
263
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function er(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function r_(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function o_(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Ss(t){return af(t)||cu(t)}function af(t){return t==='"'||t==="\u201C"||t==="\u201D"}function uf(t){return t==='"'}function cu(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function cf(t){return t==="'"}function Ro(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Bt(t,e){let n=t.length;if(!er(t,n-1))return t+e;for(;er(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function s_(t,e,n){return t.substring(0,e)+t.substring(e+n)}function i_(t){return/[,\n][ \t\r]*$/.test(t)}var GT={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},JT={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
264
+ `,r:"\r",t:" "};function lf(t){let e=0,n="";f(["```","[```","{```"]),s()||ee(),f(["```","```]","```}"]);let o=h(",");for(o&&a(),sf(t[e])&&i_(n)?(o||(n=Bt(n,",")),_()):o&&(n=Ro(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;Q();function s(){a();let J=y()||g()||E()||S()||v()||$(!1)||H();return a(),J}function a(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ue=u(J);do ue=l(),ue&&(ue=u(J));while(ue);return e>Z}function u(J){let Z=J?er:r_,ue="";for(;;)if(Z(t,e))ue+=t[e],e++;else if(o_(t,e))ue+=" ",e++;else break;return ue.length>0?(n+=ue,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!VT(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
265
+ `;)e++;return!0}return!1}function f(J){if(d(J)){if(ef(t[e]))for(;e<t.length&&tf(t[e]);)e++;return a(),!0}return!1}function d(J){u(!0);for(let Z of J){let ue=e+Z.length;if(t.slice(e,ue)===Z)return e=ue,!0}return!1}function h(J){return t[e]===J?(n+=t[e],e++,!0):!1}function m(J){return t[e]===J?(e++,!0):!1}function C(){return m("\\")}function w(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),m(","),!0):!1}function y(){if(t[e]==="{"){n+="{",e++,a(),m(",")&&a();let J=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(J?(Z=!0,J=!1):(Z=h(","),Z||(n=Bt(n,",")),a()),w(),!(E()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=Ro(n,","):oe();break}a();let je=h(":"),Ce=e>=t.length;je||(sf(t[e])||Ce?n=Bt(n,":"):se()),s()||(je||Ce?n+="null":se())}return t[e]==="}"?(n+="}",e++):n=Bt(n,"}"),!0}return!1}function g(){if(t[e]==="["){n+="[",e++,a(),m(",")&&a();let J=!0;for(;e<t.length&&t[e]!=="]";)if(J?J=!1:h(",")||(n=Bt(n,",")),w(),!s()){n=Ro(n,",");break}return t[e]==="]"?(n+="]",e++):n=Bt(n,"]"),!0}return!1}function _(){let J=!0,Z=!0;for(;Z;)J?J=!1:h(",")||(n=Bt(n,",")),Z=s();Z||(n=Ro(n,",")),n=`[
266
266
  ${n}
267
- ]`}function A(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ue=t[e]==="\\";if(ue&&(e++,ue=!0),Ss(t[e])){let je=af(t[e])?af:uf(t[e])?uf:cu(t[e])?cu:sf,Ce=e,V=n.length,ae='"';for(e++;;){if(e>=t.length){let te=P(e-1);return!J&&As(t.charAt(te))?(e=Ce,n=n.substring(0,V),A(!0)):(ae=Nt(ae,'"'),n+=ae,!0)}if(e===Z)return ae=Nt(ae,'"'),n+=ae,!0;if(je(t[e])){let te=e,ve=ae.length;if(ae+='"',e++,n+=ae,a(!1),J||e>=t.length||As(t[e])||Ss(t[e])||tr(t[e]))return C(),!0;let Oe=P(te-1),Ue=t.charAt(Oe);if(Ue===",")return e=Ce,n=n.substring(0,V),A(!1,Oe);if(As(Ue))return e=Ce,n=n.substring(0,V),A(!0);n=n.substring(0,V),e=te+1,ae=`${ae.substring(0,ve)}\\${ae.substring(ve)}`}else if(J&&rf(t[e])){if(t[e-1]===":"&&tf.test(t.substring(Ce+1,e+2)))for(;e<t.length&&nf.test(t[e]);)ae+=t[e],e++;return ae=Nt(ae,'"'),n+=ae,C(),!0}else if(t[e]==="\\"){let te=t.charAt(e+1);if(Gv[te]!==void 0)ae+=t.slice(e,e+2),e+=2;else if(te==="u"){let Oe=2;for(;Oe<6&&Z0(t[e+Oe]);)Oe++;Oe===6?(ae+=t.slice(e,e+6),e+=6):e+Oe>=t.length?e=t.length:he()}else ae+=te,e+=2}else{let te=t.charAt(e);te==='"'&&t[e-1]!=="\\"?(ae+=`\\${te}`,e++):t_(te)?(ae+=Wv[te],e++):(e_(te)||Y(te),ae+=te,e++)}ue&&b()}}return!1}function C(){let J=!1;for(a();t[e]==="+";){J=!0,e++,a(),n=Ro(n,'"',!0);let Z=n.length;A()?n=o_(n,Z,1):n=Nt(n,'"')}return J}function v(){let J=e;if(t[e]==="-"){if(e++,K())return z(J),!0;if(!tr(t[e]))return e=J,!1}for(;tr(t[e]);)e++;if(t[e]==="."){if(e++,K())return z(J),!0;if(!tr(t[e]))return e=J,!1;for(;tr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,K())return z(J),!0;if(!tr(t[e]))return e=J,!1;for(;tr(t[e]);)e++}if(!K())return e=J,!1;if(e>J){let Z=t.slice(J,e),ue=/^0\d/.test(Z);return n+=ue?`"${Z}"`:Z,!0}return!1}function T(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(J,Z){return t.slice(e,e+J.length)===J?(n+=Z,e+=J.length,!0):!1}function $(J){let Z=e;if(Zd(t[e])){for(;e<t.length&&ef(t[e]);)e++;let ue=e;for(;er(t,ue);)ue++;if(t[ue]==="(")return e=ue+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!rf(t[e])&&!Ss(t[e])&&(!J||t[e]!==":");)e++;if(t[e-1]===":"&&tf.test(t.substring(Z,e+2)))for(;e<t.length&&nf.test(t[e]);)e++;if(e>Z){for(;er(t,e-1)&&e>0;)e--;let ue=t.slice(Z,e);return n+=ue==="undefined"?"null":JSON.stringify(ue),t[e]==='"'&&e++,!0}}function G(){if(t[e]==="/"){let J=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(J,e)}"`,!0}}function P(J){let Z=J;for(;Z>0&&er(t,Z);)Z--;return Z}function K(){return e>=t.length||As(t[e])||er(t,e)}function z(J){n+=`${t.slice(J,e)}0`}function Y(J){throw new In(`Invalid character ${JSON.stringify(J)}`,e)}function Q(){throw new In(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ee(){throw new In("Unexpected end of json string",t.length)}function oe(){throw new In("Object key expected",e)}function se(){throw new In("Colon expected",e)}function he(){let J=t.slice(e,e+6);throw new In(`Invalid unicode character "${J}"`,e)}}function Jv(t,e){return t[e]==="*"&&t[e+1]==="/"}function lf(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(n){try{let r=i_.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=cf(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var lu=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=lf(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",u=!1,l=!1,f="",d=new ReadableStream({async start(p){let m=e.body.getReader(),b=(g,_,A)=>{let C=g.split(`
268
- `);for(let v of C)v.trim()&&_.enqueue(A.encode(v+`
269
- `))},w=(g,_,A)=>{let C="";try{C=lf(o.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),C=o.arguments||""}let v={role:"assistant",tool_calls:[{function:{name:o.name,arguments:C},id:o.id,index:o.index,type:"function"}]},T={...g,choices:[{...g.choices[0],delta:v}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let R=`data: ${JSON.stringify(T)}
267
+ ]`}function E(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ue=t[e]==="\\";if(ue&&(e++,ue=!0),Ss(t[e])){let je=uf(t[e])?uf:cf(t[e])?cf:cu(t[e])?cu:af,Ce=e,V=n.length,ae='"';for(e++;;){if(e>=t.length){let te=P(e-1);return!J&&As(t.charAt(te))?(e=Ce,n=n.substring(0,V),E(!0)):(ae=Bt(ae,'"'),n+=ae,!0)}if(e===Z)return ae=Bt(ae,'"'),n+=ae,!0;if(je(t[e])){let te=e,Te=ae.length;if(ae+='"',e++,n+=ae,a(!1),J||e>=t.length||As(t[e])||Ss(t[e])||tr(t[e]))return b(),!0;let Oe=P(te-1),Ue=t.charAt(Oe);if(Ue===",")return e=Ce,n=n.substring(0,V),E(!1,Oe);if(As(Ue))return e=Ce,n=n.substring(0,V),E(!0);n=n.substring(0,V),e=te+1,ae=`${ae.substring(0,Te)}\\${ae.substring(Te)}`}else if(J&&of(t[e])){if(t[e-1]===":"&&nf.test(t.substring(Ce+1,e+2)))for(;e<t.length&&rf.test(t[e]);)ae+=t[e],e++;return ae=Bt(ae,'"'),n+=ae,b(),!0}else if(t[e]==="\\"){let te=t.charAt(e+1);if(JT[te]!==void 0)ae+=t.slice(e,e+2),e+=2;else if(te==="u"){let Oe=2;for(;Oe<6&&e_(t[e+Oe]);)Oe++;Oe===6?(ae+=t.slice(e,e+6),e+=6):e+Oe>=t.length?e=t.length:he()}else ae+=te,e+=2}else{let te=t.charAt(e);te==='"'&&t[e-1]!=="\\"?(ae+=`\\${te}`,e++):n_(te)?(ae+=GT[te],e++):(t_(te)||Y(te),ae+=te,e++)}ue&&C()}}return!1}function b(){let J=!1;for(a();t[e]==="+";){J=!0,e++,a(),n=Ro(n,'"',!0);let Z=n.length;E()?n=s_(n,Z,1):n=Bt(n,'"')}return J}function S(){let J=e;if(t[e]==="-"){if(e++,K())return q(J),!0;if(!tr(t[e]))return e=J,!1}for(;tr(t[e]);)e++;if(t[e]==="."){if(e++,K())return q(J),!0;if(!tr(t[e]))return e=J,!1;for(;tr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,K())return q(J),!0;if(!tr(t[e]))return e=J,!1;for(;tr(t[e]);)e++}if(!K())return e=J,!1;if(e>J){let Z=t.slice(J,e),ue=/^0\d/.test(Z);return n+=ue?`"${Z}"`:Z,!0}return!1}function v(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(J,Z){return t.slice(e,e+J.length)===J?(n+=Z,e+=J.length,!0):!1}function $(J){let Z=e;if(ef(t[e])){for(;e<t.length&&tf(t[e]);)e++;let ue=e;for(;er(t,ue);)ue++;if(t[ue]==="(")return e=ue+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!of(t[e])&&!Ss(t[e])&&(!J||t[e]!==":");)e++;if(t[e-1]===":"&&nf.test(t.substring(Z,e+2)))for(;e<t.length&&rf.test(t[e]);)e++;if(e>Z){for(;er(t,e-1)&&e>0;)e--;let ue=t.slice(Z,e);return n+=ue==="undefined"?"null":JSON.stringify(ue),t[e]==='"'&&e++,!0}}function H(){if(t[e]==="/"){let J=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(J,e)}"`,!0}}function P(J){let Z=J;for(;Z>0&&er(t,Z);)Z--;return Z}function K(){return e>=t.length||As(t[e])||er(t,e)}function q(J){n+=`${t.slice(J,e)}0`}function Y(J){throw new In(`Invalid character ${JSON.stringify(J)}`,e)}function Q(){throw new In(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ee(){throw new In("Unexpected end of json string",t.length)}function oe(){throw new In("Object key expected",e)}function se(){throw new In("Colon expected",e)}function he(){let J=t.slice(e,e+6);throw new In(`Invalid unicode character "${J}"`,e)}}function VT(t,e){return t[e]==="*"&&t[e+1]==="/"}function df(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(n){try{let r=a_.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=lf(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var lu=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=df(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",u=!1,l=!1,f="",d=new ReadableStream({async start(h){let m=e.body.getReader(),C=(g,_,E)=>{let b=g.split(`
268
+ `);for(let S of b)S.trim()&&_.enqueue(E.encode(S+`
269
+ `))},w=(g,_,E)=>{let b="";try{b=df(o.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),b=o.arguments||""}let S={role:"assistant",tool_calls:[{function:{name:o.name,arguments:b},id:o.id,index:o.index,type:"function"}]},v={...g,choices:[{...g.choices[0],delta:S}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let R=`data: ${JSON.stringify(v)}
270
270
 
271
- `;_.enqueue(A.encode(R))},y=(g,_)=>{let{controller:A,encoder:C}=_;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let v=g.slice(6);try{let T=JSON.parse(v);if(T.choices?.[0]?.delta?.tool_calls?.length){let $=T.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let G=`data: ${JSON.stringify(T)}
271
+ `;_.enqueue(E.encode(R))},y=(g,_)=>{let{controller:E,encoder:b}=_;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let S=g.slice(6);try{let v=JSON.parse(S);if(v.choices?.[0]?.delta?.tool_calls?.length){let $=v.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let H=`data: ${JSON.stringify(v)}
272
272
 
273
- `;A.enqueue(C.encode(G));return}else if(o.index===$.index){$.function?.arguments&&(o.arguments+=$.function.arguments);return}else{w(T,A,C),o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){w(T,A,C),o={};return}T.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let R=`data: ${JSON.stringify(T)}
273
+ `;E.enqueue(b.encode(H));return}else if(o.index===$.index){$.function?.arguments&&(o.arguments+=$.function.arguments);return}else{w(v,E,b),o={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(v.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){w(v,E,b),o={};return}v.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let R=`data: ${JSON.stringify(v)}
274
274
 
275
- `;A.enqueue(C.encode(R))}catch{A.enqueue(C.encode(g+`
276
- `))}}else A.enqueue(C.encode(g+`
277
- `))};try{for(;;){let{done:g,value:_}=await m.read();if(g){f.trim()&&b(f,p,r);break}if(!_||_.length===0)continue;let A;try{A=n.decode(_,{stream:!0})}catch(v){console.warn("Failed to decode chunk",v);continue}if(A.length===0)continue;if(f+=A,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let v=f.split(`
278
- `);f=v.pop()||"";for(let T of v)if(T.trim())try{y(T,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>u,setReasoningComplete:R=>u=R})}catch(R){console.error("Error processing line:",T,R),p.enqueue(r.encode(T+`
279
- `))}continue}let C=f.split(`
280
- `);f=C.pop()||"";for(let v of C)if(v.trim())try{y(v,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>u,setReasoningComplete:T=>u=T})}catch(T){console.error("Error processing line:",v,T),p.enqueue(r.encode(v+`
281
- `))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{m.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var du=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return n.choices[0]?.message.reasoning_content&&(n.thinking={content:n.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,b,w)=>{let y=m.split(`
282
- `);for(let g of y)g.trim()&&b.enqueue(w.encode(g+`
283
- `))},p=(m,b)=>{let{controller:w,encoder:y}=b;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let g=JSON.parse(m.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(_)}
275
+ `;E.enqueue(b.encode(R))}catch{E.enqueue(b.encode(g+`
276
+ `))}}else E.enqueue(b.encode(g+`
277
+ `))};try{for(;;){let{done:g,value:_}=await m.read();if(g){f.trim()&&C(f,h,r);break}if(!_||_.length===0)continue;let E;try{E=n.decode(_,{stream:!0})}catch(S){console.warn("Failed to decode chunk",S);continue}if(E.length===0)continue;if(f+=E,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let S=f.split(`
278
+ `);f=S.pop()||"";for(let v of S)if(v.trim())try{y(v,{controller:h,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>u,setReasoningComplete:R=>u=R})}catch(R){console.error("Error processing line:",v,R),h.enqueue(r.encode(v+`
279
+ `))}continue}let b=f.split(`
280
+ `);f=b.pop()||"";for(let S of b)if(S.trim())try{y(S,{controller:h,encoder:r,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>u,setReasoningComplete:v=>u=v})}catch(v){console.error("Error processing line:",S,v),h.enqueue(r.encode(S+`
281
+ `))}}}catch(g){console.error("Stream error:",g),h.error(g)}finally{try{m.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}h.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var du=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return n.choices[0]?.message.reasoning_content&&(n.thinking={content:n.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",u=new ReadableStream({async start(l){let f=e.body.getReader(),d=(m,C,w)=>{let y=m.split(`
282
+ `);for(let g of y)g.trim()&&C.enqueue(w.encode(g+`
283
+ `))},h=(m,C)=>{let{controller:w,encoder:y}=C;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let g=JSON.parse(m.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){C.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(_)}
284
284
 
285
- `;w.enqueue(y.encode(A));return}if(g.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let _="ccr_think_signature",A=g.choices[0].delta.content,C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:_}}}]};delete C.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(C)}
285
+ `;w.enqueue(y.encode(E));return}if(g.choices?.[0]?.delta?.content&&C.reasoningContent()&&!C.isReasoningComplete()){C.setReasoningComplete(!0);let _="ccr_think_signature",E=g.choices[0].delta.content,b={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:C.reasoningContent(),signature:_}}}]};delete b.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(b)}
286
286
 
287
- `;w.enqueue(y.encode(v))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){b.isReasoningComplete()&&g.choices[0].index++;let _=`data: ${JSON.stringify(g)}
287
+ `;w.enqueue(y.encode(S))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){C.isReasoningComplete()&&g.choices[0].index++;let _=`data: ${JSON.stringify(g)}
288
288
 
289
289
  `;w.enqueue(y.encode(_))}}catch{w.enqueue(y.encode(m+`
290
290
  `))}else w.enqueue(y.encode(m+`
291
- `))};try{for(;;){let{done:m,value:b}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(b,{stream:!0});a+=w;let y=a.split(`
292
- `);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:_=>o+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
293
- `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{f.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var fu=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 hu=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function a_(t){let e=[];for(let r=0;r<t.messages.length;r++){let o=t.messages[r],s=r===t.messages.length-1,a=o.role==="assistant",u=[];typeof o.content=="string"?u.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.content.forEach(l=>{l.type==="text"?u.push({type:"text",text:l.text||""}):l.type==="image_url"&&u.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&u.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&u.length===0&&o.tool_calls&&u.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:u}))}let n={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&&(n.tools=t.tools.map(r=>({name:r.function.name,description:r.function.description,input_schema:r.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?n.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(n.tool_choice={type:"tool",name:t.tool_choice})),n}function u_(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),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&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function c_(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:{completion_tokens:r.usage.output_tokens,prompt_tokens:r.usage.input_tokens,total_tokens:r.usage.input_tokens+r.usage.output_tokens}};return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=(u,l)=>{if(u.startsWith("data: ")){let f=u.slice(6).trim();if(f){n?.debug({chunkStr:f},`${e} chunk:`);try{let d=JSON.parse(f);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(o.encode(`data: ${JSON.stringify(p)}
291
+ `))};try{for(;;){let{done:m,value:C}=await f.read();if(m){a.trim()&&d(a,l,r);break}let w=n.decode(C,{stream:!0});a+=w;let y=a.split(`
292
+ `);a=y.pop()||"";for(let g of y)if(g.trim())try{h(g,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:_=>o+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(r.encode(g+`
293
+ `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{f.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var fu=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 hu=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function u_(t){let e=[];for(let r=0;r<t.messages.length;r++){let o=t.messages[r],s=r===t.messages.length-1,a=o.role==="assistant",u=[];typeof o.content=="string"?u.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.content.forEach(l=>{l.type==="text"?u.push({type:"text",text:l.text||""}):l.type==="image_url"&&u.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&u.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&u.length===0&&o.tool_calls&&u.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:u}))}let n={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&&(n.tools=t.tools.map(r=>({name:r.function.name,description:r.function.description,input_schema:r.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?n.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(n.tool_choice={type:"tool",name:t.tool_choice})),n}function c_(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),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&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function l_(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:{completion_tokens:r.usage.output_tokens,prompt_tokens:r.usage.input_tokens,total_tokens:r.usage.input_tokens+r.usage.output_tokens}};return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=(u,l)=>{if(u.startsWith("data: ")){let f=u.slice(6).trim();if(f){n?.debug({chunkStr:f},`${e} chunk:`);try{let d=JSON.parse(f);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let h={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(o.encode(`data: ${JSON.stringify(h)}
294
294
 
295
- `))}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(o.encode(`data: ${JSON.stringify(p)}
295
+ `))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let h={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(o.encode(`data: ${JSON.stringify(h)}
296
296
 
297
- `))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},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(o.encode(`data: ${JSON.stringify(p)}
297
+ `))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let h={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},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(o.encode(`data: ${JSON.stringify(h)}
298
298
 
299
- `))}else if(d.type==="message_delta"){let p={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",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(o.encode(`data: ${JSON.stringify(p)}
299
+ `))}else if(d.type==="message_delta"){let h={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",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(o.encode(`data: ${JSON.stringify(h)}
300
300
 
301
301
  `))}else if(d.type==="message_stop")l.enqueue(o.encode(`data: [DONE]
302
302
 
303
- `));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(o.encode(`data: ${JSON.stringify(p)}
303
+ `));else{let h={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(o.encode(`data: ${JSON.stringify(h)}
304
304
 
305
- `))}}catch(d){n?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}},a=new ReadableStream({async start(u){let l=t.body.getReader(),f="";try{for(;;){let{done:d,value:p}=await l.read();if(d){f&&s(f,u);break}f+=r.decode(p,{stream:!0});let m=f.split(`
306
- `);f=m.pop()||"";for(let b of m)s(b,u)}}catch(d){u.error(d)}finally{u.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function Vv(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xe(Xd(),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:
305
+ `))}}catch(d){n?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}},a=new ReadableStream({async start(u){let l=t.body.getReader(),f="";try{for(;;){let{done:d,value:h}=await l.read();if(d){f&&s(f,u);break}f+=r.decode(h,{stream:!0});let m=f.split(`
306
+ `);f=m.pop()||"";for(let C of m)s(C,u)}}catch(d){u.error(d)}finally{u.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function KT(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xe(Zd(),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:
307
307
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
308
308
  2. Run "gcloud auth application-default login"
309
- 3. Use Google Cloud environment with default service account`)}}var pu=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let u=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(u);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 s=await Vv();return{body:a_(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return u_(e)}async transformResponseOut(e){return c_(e,this.name,this.logger)}};var mu=class{name="cerebras";async transformRequestIn(e,n){let r=JSON.parse(JSON.stringify(e));return r.reasoning?delete r.reasoning:r.disable_reasoning=!1,{body:r,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var gu=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var yu=class{name="OpenAI";endPoint="/v1/chat/completions"};var _u=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var bu=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u=!1,l="",f=new ReadableStream({async start(d){let p=e.body.getReader(),m=(w,y,g)=>{let _=w.split(`
310
- `);for(let A of _)A.trim()&&y.enqueue(g.encode(A+`
311
- `))},b=(w,y)=>{let{controller:g,encoder:_}=y;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]"){let A=w.slice(6);try{let C=JSON.parse(A);if(C.usage&&(this.logger?.debug({usage:C.usage,hasToolCall:u},"usage"),C.choices[0].finish_reason=u?"tool_calls":"stop"),C.choices?.[0]?.finish_reason==="error"&&g.enqueue(_.encode(`data: ${JSON.stringify({error:C.choices?.[0].error})}
309
+ 3. Use Google Cloud environment with default service account`)}}var pu=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let u=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(u);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)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 s=await KT();return{body:u_(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return c_(e)}async transformResponseOut(e){return l_(e,this.name,this.logger)}};var mu=class{name="cerebras";async transformRequestIn(e,n){let r=JSON.parse(JSON.stringify(e));return r.reasoning?delete r.reasoning:r.disable_reasoning=!1,{body:r,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var gu=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var yu=class{name="OpenAI";endPoint="/v1/chat/completions"};var _u=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var bu=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u=!1,l="",f=new ReadableStream({async start(d){let h=e.body.getReader(),m=(w,y,g)=>{let _=w.split(`
310
+ `);for(let E of _)E.trim()&&y.enqueue(g.encode(E+`
311
+ `))},C=(w,y)=>{let{controller:g,encoder:_}=y;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]"){let E=w.slice(6);try{let b=JSON.parse(E);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:u},"usage"),b.choices[0].finish_reason=u?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&g.enqueue(_.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
312
312
 
313
- `)),C.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),C.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(C.choices[0].delta.reasoning);let T={...C,choices:[{...C.choices?.[0],delta:{...C.choices[0].delta,thinking:{content:C.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(T)}
313
+ `)),b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let v={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(v)}
314
314
 
315
- `;g.enqueue(_.encode(R));return}if(C.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let R={...C,choices:[{...C.choices?.[0],delta:{...C.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:"ccr_think_signature"}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(R)}
315
+ `;g.enqueue(_.encode(R));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:"ccr_think_signature"}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(R)}
316
316
 
317
- `;g.enqueue(_.encode($))}C.choices?.[0]?.delta?.reasoning&&delete C.choices[0].delta.reasoning,C.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(C.choices?.[0]?.delta?.tool_calls[0].id,10))&&C.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${qt()}`}),C.choices?.[0]?.delta?.tool_calls?.length&&!u&&(u=!0),C.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof C.choices[0].index=="number"?C.choices[0].index+=1:C.choices[0].index=1);let v=`data: ${JSON.stringify(C)}
317
+ `;g.enqueue(_.encode($))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${pt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!u&&(u=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let S=`data: ${JSON.stringify(b)}
318
318
 
319
- `;g.enqueue(_.encode(v))}catch{g.enqueue(_.encode(w+`
319
+ `;g.enqueue(_.encode(S))}catch{g.enqueue(_.encode(w+`
320
320
  `))}}else g.enqueue(_.encode(w+`
321
- `))};try{for(;;){let{done:w,value:y}=await p.read();if(w){l.trim()&&m(l,d,r);break}if(!y||y.length===0)continue;let g;try{g=n.decode(y,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=l.split(`
322
- `);l=A.pop()||"";for(let C of A)if(C.trim())try{b(C,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:v=>o=v,reasoningContent:()=>s,appendReasoningContent:v=>s+=v,isReasoningComplete:()=>a,setReasoningComplete:v=>a=v})}catch(v){console.error("Error processing line:",C,v),d.enqueue(r.encode(C+`
321
+ `))};try{for(;;){let{done:w,value:y}=await h.read();if(w){l.trim()&&m(l,d,r);break}if(!y||y.length===0)continue;let g;try{g=n.decode(y,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=l.split(`
322
+ `);l=E.pop()||"";for(let b of E)if(b.trim())try{C(b,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>s,appendReasoningContent:S=>s+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",b,S),d.enqueue(r.encode(b+`
323
323
  `))}continue}let _=l.split(`
324
- `);l=_.pop()||"";for(let A of _)if(A.trim())try{b(A,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:C=>o=C,reasoningContent:()=>s,appendReasoningContent:C=>s+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",A,C),d.enqueue(r.encode(A+`
325
- `))}}}catch(w){console.error("Stream error:",w),d.error(w)}finally{try{p.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var df=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
324
+ `);l=_.pop()||"";for(let E of _)if(E.trim())try{C(E,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",E,b),d.enqueue(r.encode(E+`
325
+ `))}}}catch(w){console.error("Stream error:",w),d.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ff=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
326
326
 
327
327
  Output format:
328
328
  <reasoning_content>
329
329
  Your detailed thinking process goes here
330
330
  </reasoning_content>
331
- Your final answer must follow after the closing tag above.`,Kv=10,Cu=class{name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<Kv)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
332
- ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:df}):r.content=[{type:"text",text:df},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:df}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,u=new ReadableStream({async start(l){let f=e.body.getReader(),d="",p="SEARCHING",m="",b="",w=(y,g)=>{if(typeof g!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(y)}
331
+ Your final answer must follow after the closing tag above.`,YT=10,Cu=class{name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<YT)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
332
+ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:ff}):r.content=[{type:"text",text:ff},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:ff}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,u=new ReadableStream({async start(l){let f=e.body.getReader(),d="",h="SEARCHING",m="",C="",w=(y,g)=>{if(typeof g!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(y)}
333
333
 
334
- `)));return}let _=m+g;for(m="";_.length>0;)if(p==="SEARCHING"){let A=_.indexOf(n);if(A!==-1)_=_.substring(A+n.length),p="REASONING";else{for(let C=n.length-1;C>0;C--)if(_.endsWith(n.substring(0,C))){m=_.substring(_.length-C);break}_=""}}else if(p==="REASONING"){let A=_.indexOf(r);if(A!==-1){let C=_.substring(0,A);if(C.length>0){let R={...y.choices[0].delta,thinking:{content:C}};delete R.content;let $={...y,choices:[{...y.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify($)}
334
+ `)));return}let _=m+g;for(m="";_.length>0;)if(h==="SEARCHING"){let E=_.indexOf(n);if(E!==-1)_=_.substring(E+n.length),h="REASONING";else{for(let b=n.length-1;b>0;b--)if(_.endsWith(n.substring(0,b))){m=_.substring(_.length-b);break}_=""}}else if(h==="REASONING"){let E=_.indexOf(r);if(E!==-1){let b=_.substring(0,E);if(b.length>0){let R={...y.choices[0].delta,thinking:{content:b}};delete R.content;let $={...y,choices:[{...y.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify($)}
335
335
 
336
- `))}let v={...y.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete v.content;let T={...y,choices:[{...y.choices[0],delta:v,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
336
+ `))}let S={...y.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete S.content;let v={...y,choices:[{...y.choices[0],delta:S,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
337
337
 
338
- `)),o++,_=_.substring(A+r.length),p="FINAL"}else{let C=_;for(let v=r.length-1;v>0;v--)if(_.endsWith(r.substring(0,v))){m=_.substring(_.length-v),C=_.substring(0,_.length-v);break}if(C.length>0){let v={...y.choices[0].delta,thinking:{content:C}};delete v.content;let T={...y,choices:[{...y.choices[0],delta:v,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
338
+ `)),o++,_=_.substring(E+r.length),h="FINAL"}else{let b=_;for(let S=r.length-1;S>0;S--)if(_.endsWith(r.substring(0,S))){m=_.substring(_.length-S),b=_.substring(0,_.length-S);break}if(b.length>0){let S={...y.choices[0].delta,thinking:{content:b}};delete S.content;let v={...y,choices:[{...y.choices[0],delta:S,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
339
339
 
340
- `))}_=""}}else if(p==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))b+=_;else{let C=b+_,v={...y.choices[0].delta,content:C};v.thinking&&delete v.thinking;let T={...y,choices:[{...y.choices[0],delta:v}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
340
+ `))}_=""}}else if(h==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))C+=_;else{let b=C+_,S={...y.choices[0].delta,content:b};S.thinking&&delete S.thinking;let v={...y,choices:[{...y.choices[0],delta:S}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
341
341
 
342
- `)),b=""}o++,_=""}};try{for(;;){let{done:y,value:g}=await f.read();if(y)break;let _=s.decode(g,{stream:!0});d+=_;let A=d.split(`
343
- `);d=A.pop()||"";for(let C of A)if(C.trim()){if(C.trim()==="data: [DONE]"){l.enqueue(a.encode(C+`
342
+ `)),C=""}o++,_=""}};try{for(;;){let{done:y,value:g}=await f.read();if(y)break;let _=s.decode(g,{stream:!0});d+=_;let E=d.split(`
343
+ `);d=E.pop()||"";for(let b of E)if(b.trim()){if(b.trim()==="data: [DONE]"){l.enqueue(a.encode(b+`
344
344
 
345
- `));break}if(C.startsWith("data:"))try{let v=JSON.parse(C.slice(5));w(v,v.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(C+`
346
- `))}else l.enqueue(a.encode(C+`
347
- `))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{f.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(g)}
345
+ `));break}if(b.startsWith("data:"))try{let S=JSON.parse(b.slice(5));w(S,S.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(b+`
346
+ `))}else l.enqueue(a.encode(b+`
347
+ `))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{f.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(h==="REASONING"){let g={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(g)}
348
348
 
349
- `))}l.close()}}});return new Response(u,{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 wu=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content))&&e.messages.forEach(r=>{if(r.role==="assistant"){let o=r.thinking?.content,s=r.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(r.reasoning_content=o,s&&(r.reasoning_content_signature=s)),r.tool_calls&&r.tool_calls.length>0&&(r.reasoning_content||(r.reasoning_content="")),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){let n=e.headers.get("Content-Type");if(n?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a="",u=new ReadableStream({async start(l){let f=e.body.getReader();try{for(;;){let{done:d,value:p}=await f.read();if(d){a.trim()&&l.enqueue(o.encode(a+`
350
- `));break}let m=r.decode(p,{stream:!0});a+=m;let b=a.split(`
351
- `);a=b.pop()||"";for(let w of b)if(w.trim())if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let y=JSON.parse(w.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){s+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(g)}
349
+ `))}l.close()}}});return new Response(u,{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 wu=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content))&&e.messages.forEach(r=>{if(r.role==="assistant"){let o=r.thinking?.content,s=r.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(r.reasoning_content=o,s&&(r.reasoning_content_signature=s)),r.tool_calls&&r.tool_calls.length>0&&(r.reasoning_content||(r.reasoning_content="")),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){let n=e.headers.get("Content-Type");if(n?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a="",u=new ReadableStream({async start(l){let f=e.body.getReader();try{for(;;){let{done:d,value:h}=await f.read();if(d){a.trim()&&l.enqueue(o.encode(a+`
350
+ `));break}let m=r.decode(h,{stream:!0});a+=m;let C=a.split(`
351
+ `);a=C.pop()||"";for(let w of C)if(w.trim())if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let y=JSON.parse(w.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){s+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(g)}
352
352
 
353
353
  `));continue}if(y.choices?.[0]?.delta?.content&&s&&!y.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),_={...y,choices:[{...y.choices[0],delta:{content:null,thinking:{content:s,signature:g}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(_)}
354
354
 
@@ -356,18 +356,36 @@ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return
356
356
 
357
357
  `))}catch{l.enqueue(o.encode(w+`
358
358
  `))}else l.enqueue(o.encode(w+`
359
- `))}}catch(d){l.error(d)}finally{try{f.releaseLock()}catch{}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":n||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(n?.includes("application/json")){let r=await e.json();return r.choices?.[0]?.message?.reasoning_content&&(r.choices[0].message.thinking={content:r.choices[0].message.reasoning_content},delete r.choices[0].message.reasoning_content),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var l_={AnthropicTransformer:Ni,GeminiTransformer:ji,VertexGeminiTransformer:nu,VertexClaudeTransformer:pu,DeepseekTransformer:ru,TooluseTransformer:ou,OpenrouterTransformer:su,OpenAITransformer:yu,MaxTokenTransformer:iu,GroqTransformer:au,CleancacheTransformer:uu,EnhanceToolTransformer:lu,ReasoningTransformer:du,SamplingTransformer:fu,MaxCompletionTokens:hu,CerebrasTransformer:mu,StreamOptionsTransformer:gu,CustomParamsTransformer:_u,VercelTransformer:bu,OpenAIResponsesTransformer:Kr,ForceReasoningTransformer:Cu,KimiTransformer:wu};var Rr=class{constructor(e,n){this.configService=e;this.logger=n}transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&n.endPoint&&e.push({name:r,transformer:n})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=require(require.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
359
+ `))}}catch(d){l.error(d)}finally{try{f.releaseLock()}catch{}l.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":n||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(n?.includes("application/json")){let r=await e.json();return r.choices?.[0]?.message?.reasoning_content&&(r.choices[0].message.thinking={content:r.choices[0].message.reasoning_content},delete r.choices[0].message.reasoning_content),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var Eu=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return n.choices?.[0]?.message?.reasoning_content&&(n.choices[0].message.thinking={content:n.choices[0].message.reasoning_content},delete n.choices[0].message.reasoning_content),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,u=!1,l="",f=new ReadableStream({async start(d){let h=e.body.getReader(),m=(w,y,g)=>{let _=w.split(`
360
+ `);for(let E of _)E.trim()&&y.enqueue(g.encode(E+`
361
+ `))},C=(w,y)=>{let{controller:g,encoder:_}=y;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let E=JSON.parse(w.slice(6));if(E.usage&&(E.choices[0].finish_reason=u?"tool_calls":"stop"),E.choices?.[0]?.finish_reason==="error"){g.enqueue(_.encode(`data: ${JSON.stringify({error:E.choices?.[0]?.error})}
362
+
363
+ `));return}E.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0);let b=E.choices?.[0]?.delta?.reasoning||E.choices?.[0]?.delta?.reasoning_content;if(b){y.appendReasoningContent(b);let H={...E,choices:[{...E.choices?.[0],delta:{...E.choices[0].delta,thinking:{content:b}}}]};H.choices?.[0]?.delta&&(delete H.choices[0].delta.reasoning,delete H.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(H)}
364
+
365
+ `));return}if(E.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let H="ccr_think_signature",P=E.choices[0].delta.content,K={...E,choices:[{...E.choices?.[0],delta:{...E.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:H}}}]};K.choices?.[0]?.delta&&(delete K.choices[0].delta.reasoning,delete K.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(K)}
366
+
367
+ `));let q={...E,choices:[{...E.choices?.[0],delta:{...E.choices[0].delta,content:P}}]};q.choices?.[0]?.delta&&(delete q.choices[0].delta.reasoning,delete q.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(q)}
368
+
369
+ `));return}E.choices?.[0]?.delta?.reasoning&&delete E.choices[0].delta.reasoning,E.choices?.[0]?.delta?.reasoning_content&&delete E.choices[0].delta.reasoning_content,E.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(E.choices?.[0]?.delta?.tool_calls[0].id,10))&&E.choices?.[0]?.delta?.tool_calls.forEach(H=>{H.id=`call_${pt()}`}),E.choices?.[0]?.delta?.tool_calls?.length&&!u&&(u=!0);let S=E.choices?.[0]?.delta,v=S&&Object.keys(S).length>0,R=E.choices?.[0]?.finish_reason,$=E.usage;(v||R||$)&&g.enqueue(_.encode(`data: ${JSON.stringify(E)}
370
+
371
+ `))}catch{g.enqueue(_.encode(w+`
372
+ `))}else g.enqueue(_.encode(w+`
373
+ `))};try{for(;;){let{done:w,value:y}=await h.read();if(w){l.trim()&&m(l,d,r);break}if(!y||y.length===0)continue;let g;try{g=n.decode(y,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=l.split(`
374
+ `);l=E.pop()||"";for(let b of E)if(b.trim())try{C(b,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>s,appendReasoningContent:S=>s+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",b,S),d.enqueue(r.encode(b+`
375
+ `))}continue}let _=l.split(`
376
+ `);l=_.pop()||"";for(let E of _)if(E.trim())try{C(E,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",E,b),d.enqueue(r.encode(E+`
377
+ `))}}}catch(w){console.error("Stream error:",w),d.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var d_={AnthropicTransformer:Ni,GeminiTransformer:ji,VertexGeminiTransformer:nu,VertexClaudeTransformer:pu,DeepseekTransformer:ru,TooluseTransformer:ou,OpenrouterTransformer:su,OpenAITransformer:yu,MaxTokenTransformer:iu,GroqTransformer:au,CleancacheTransformer:uu,EnhanceToolTransformer:lu,ReasoningTransformer:du,SamplingTransformer:fu,MaxCompletionTokens:hu,CerebrasTransformer:mu,StreamOptionsTransformer:gu,CustomParamsTransformer:_u,VercelTransformer:bu,OpenAIResponsesTransformer:Kr,ForceReasoningTransformer:Cu,KimiTransformer:wu,OpenCodeTransformer:Eu};var Rr=class{constructor(e,n){this.configService=e;this.logger=n}transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&n.endPoint&&e.push({name:r,transformer:n})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=require(require.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
360
378
  error: ${n.message}
361
379
  stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
362
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(l_).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};var d_=require("tiktoken"),vs=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,d_.get_encoding)(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 n=this.encoding;if(!n)throw new Error("Encoding not initialized");let r=0,{messages:o,system:s,tools:a}=e;return Array.isArray(o)&&o.forEach(u=>{typeof u.content=="string"?r+=n.encode(u.content).length:Array.isArray(u.content)&&u.content.forEach(l=>{if(l.type==="text")r+=n.encode(l.text).length;else if(l.type==="tool_use")r+=n.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let f=typeof l.content=="string"?l.content:JSON.stringify(l.content);r+=n.encode(f).length}})}),typeof s=="string"?r+=n.encode(s).length:Array.isArray(s)&&s.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?r+=n.encode(u.text).length:Array.isArray(u.text)&&u.text.forEach(l=>{r+=n.encode(l||"").length}))}),a&&a.forEach(u=>{u.description&&(r+=n.encode(u.name+u.description).length),u.input_schema&&(r+=n.encode(JSON.stringify(u.input_schema)).length)}),r}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};var xs=require("path"),T_=require("os"),xo=require("fs"),Os=require("fs");var Yv=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,a=null,u=o;for(;u<n&&(s=s[t[u]]);)s.end&&(a=s.end),++u;a?(o>r&&e.push(t.slice(r,o)),e.push(a),o+=a.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},Qv=Yv,Xv=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}},Zv=Xv,__=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),eT=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),tT=eT(__),f_=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",nT=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|[${f_}])]+`,` ?[^\\s${f_}]+`]]),Ts="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",hF=new RegExp(`^[${Ts}]+$`,"gu"),hf=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"),Eu=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");for(let[r,o]of nT)n=n.replaceAll(r,o);return new RegExp(n,"gu")}else if(t.String!==void 0){let n=rT(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},rT=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),oT=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},sT=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,iT=t=>Number.isInteger(t)||typeof t=="bigint",aT=t=>{let e=0;for(let n of t)++e;return e},uT=t=>b_(t.toLowerCase()),Bt=(...t)=>Array.prototype.concat.apply([],t),pf=t=>new Map(Object.entries(t)),cT=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},b_=t=>t.replace(new RegExp("\\p{M}","gu"),""),h_=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},lT=t=>t.match(/\S+/g)||[],dT=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Ds=dT,fT=class extends Ds{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Nn=fT,hT=class extends Nn{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);sT(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
363
- `: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 n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}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}},pT=hT,mT=class extends Nn{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}},gT=mT,yT=class extends Nn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>C_(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},_T=yT,bT=class extends Nn{normalize(t){let e=Eu(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},CT=bT,wT=class extends Nn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},ku=wT,ET=class extends ku{constructor(){super(...arguments),this.form="NFC"}},kT=ET,AT=class extends ku{constructor(){super(...arguments),this.form="NFD"}},ST=AT,vT=class extends ku{constructor(){super(...arguments),this.form="NFKC"}},TT=vT,DT=class extends ku{constructor(){super(...arguments),this.form="NFKD"}},RT=DT,xT=class extends Nn{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}},OT=xT,PT=class extends Nn{normalize(t){return b_(t)}},FT=PT,IT=class extends Nn{normalize(t){return t.toLowerCase()}},NT=IT,BT=class extends Nn{normalize(t){return t=this.config.prepend+t,t}},MT=BT;function LT(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new pT(t);case"Precompiled":return new gT(t);case"Sequence":return new _T(t);case"Replace":return new CT(t);case"NFC":return new kT(t);case"NFD":return new ST(t);case"NFKC":return new TT(t);case"NFKD":return new RT(t);case"Strip":return new OT(t);case"StripAccents":return new FT(t);case"Lowercase":return new NT(t);case"Prepend":return new MT(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var C_=LT,jT=class extends Ds{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},dn=jT,UT=class extends dn{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=__,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(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},$T=UT,qT=class extends dn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},zT=qT,HT=class extends dn{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:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},WT=HT,GT=class extends dn{constructor(t){super(),this.config=t,this.pattern=Eu(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):cT(t,this.pattern)}},JT=GT,VT=class extends dn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ts}]+|[${Ts}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},KT=VT,YT=class extends dn{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)||[]}},QT=YT,XT=class extends dn{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ts}]+|[${Ts}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},ZT=XT,eD=class extends dn{constructor(t){super(),this.config=t,this.pattern=Eu(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},tD=eD,nD=class extends dn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>w_(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},rD=nD,oD=class extends dn{pre_tokenize_text(t){return lT(t)}},sD=oD;function iD(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new ZT;case"Sequence":return new rD(t);case"Whitespace":return new zT;case"WhitespaceSplit":return new sD;case"Metaspace":return new WT(t);case"ByteLevel":return new $T(t);case"Split":return new JT(t);case"Punctuation":return new KT(t);case"Digits":return new QT(t);case"Replace":return new tD(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var w_=iD,aD=class extends Ds{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=oT(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)}},Au=aD,uD=class extends Au{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=pf(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,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let u=r.length,l=null;for(;s<u;){let f=r.slice(s,u).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--u}if(l===null){o=!0;break}a.push(l),s=u}o?e.push(this.unk_token):e.push(...a)}return e}},p_=uD,m_=class E_{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new E_(!1,new Map)}},cD=class{constructor(){this.root=m_.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=m_.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},lD=cD,ff=class k_{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new k_(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},dD=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new ff(this.bos_token_id??0,0,0,0,0),o=new ff(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new ff(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,u=null;for(let l of this.end_nodes[e]){let f=l.backtrace_score+s.score;(u===null||f>a)&&(u=l.clone(),a=f)}if(u!==null)s.prev=u,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}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)}},fD=dD;function hD(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var pD=class extends Au{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),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=hD(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new lD,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),u=this.trie.common_prefix_search(a);for(let l of u){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],p=aT(l);t.insert(r,p,d,f),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new fD(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},g_=pD,mD=class{constructor(t=(n,r)=>n>r,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 n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}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 n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_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}},gD=mD,yD=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()}},_D=yD,bD=class extends Au{constructor(t){super(t),this.tokens_to_ids=pf(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[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),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 _D(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 n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new gD((u,l)=>u.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let u=1;u<n.length;++u){let l={bias:u/n.length,token:n[u],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let u=o.pop();if(u.deleted||!u.next||u.next.deleted)continue;if(u.deleted=!0,u.next.deleted=!0,u.prev){let f={...u.prev};u.prev.deleted=!0,u.prev=f,f.prev?f.prev.next=f:s=f}let l={token:u.token+u.next.token,bias:u.bias,prev:u.prev,next:u.next.next};l.prev?(l.prev.next=l,this.add_node(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let u=s;u!==null;u=u.next)r.push(u.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},y_=bD,CD=class extends Au{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=pf(e.target_lang?n[e.target_lang]:n),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[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},wD=CD;function ED(t,e){switch(t.type){case"WordPiece":return new p_(t);case"Unigram":return new g_(t,e.eos_token);case"BPE":return new y_(t);default:if(t.vocab)return Array.isArray(t.vocab)?new g_(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new y_(t):new p_(t):new wD(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 kD=ED,AD=class extends Ds{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Rs=AD,SD=class extends Rs{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Bt(o,t),s=Bt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Bt(o,e),s=Bt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},vD=SD,TD=class extends Rs{post_process(t,e=null){return{tokens:e?Bt(t,e):t}}},DD=TD,RD=class extends Rs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Bt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=Bt(t,o,e,s),r=Bt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},xD=RD,OD=class extends Rs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Bt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=Bt(t,o,e,s),r=Bt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},PD=OD,FD=class extends Rs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>A_(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},ID=FD;function ND(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new vD(t);case"ByteLevel":return new DD(t);case"BertProcessing":return new xD(t);case"RobertaProcessing":return new PD(t);case"Sequence":return new ID(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var A_=ND,BD=class extends Ds{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("")}},fn=BD,MD=class extends fn{constructor(t){super(t),this.byte_decoder=tT,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(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},LD=MD,jD=class extends fn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=hf(e)),e})}},UD=jD,$D=class extends fn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},qD=$D,zD=class extends fn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},HD=zD,WD=class extends fn{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 r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=hf(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},GD=WD,JD=class extends fn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>S_(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},VD=JD,KD=class extends fn{decode_chain(t){let e=Eu(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},YD=KD,QD=class extends fn{decode_chain(t){return[t.join("")]}},XD=QD,ZD=class extends fn{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 n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},eR=ZD,tR=class extends fn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},nR=tR;function rR(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new LD(t);case"WordPiece":return new UD(t);case"Metaspace":return new qD(t);case"BPEDecoder":return new HD(t);case"CTC":return new GD(t);case"Sequence":return new VD(t);case"Replace":return new YD(t);case"Fuse":return new XD(t);case"Strip":return new eR(t);case"ByteFallback":return new nR(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var S_=rR,oR=class{constructor(t,e){let n=h_(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=h_(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=C_(this.tokenizer.normalizer),this.pre_tokenizer=w_(this.tokenizer.pre_tokenizer),this.model=kD(this.tokenizer.model,this.config),this.post_processor=A_(this.tokenizer.post_processor),this.decoder=S_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new Zv(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 Qv(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),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:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),u={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(u.token_type_ids=s),u}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!iT(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=hf(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=uT(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:Bt(r??[],o??[])}}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}},v_=oR;var Su=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,xs.join)((0,T_.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,xs.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,xs.join)(e,"tokenizer.json"),tokenizerConfig:(0,xs.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,xo.existsSync)(e)||(0,xo.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,xo.existsSync)(e.tokenizerJson)||!(0,xo.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Os.promises.readFile(e.tokenizerJson,"utf-8"),Os.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={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 r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[u,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Os.promises.writeFile(e.tokenizerJson,JSON.stringify(u,null,2)),Os.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:u,tokenizerConfig:l}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new v_(n.tokenizerJson,n.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 n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}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 n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let u of a.content)u.type==="text"&&u.text?n.push(u.text):u.type==="tool_use"&&u.input?n.push(JSON.stringify(u.input)):u.type==="tool_result"&&n.push(typeof u.content=="string"?u.content:JSON.stringify(u.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let u of a.text)u&&n.push(u)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var vu=class{type="api";name;config;logger;options;constructor(e,n,r={}){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=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.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 n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let u=await a.json();return this.extractTokenCount(u)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}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(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var xr=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}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 n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new vs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Su(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new vu(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 r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),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)}`}}};Wn();var hn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let u={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");u.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,u);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},mf=class extends hn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>ye(l?.total_balance)!==void 0);if(!a)return null;let u=ye(a.total_balance);return u===void 0?null:{totalBalance:u,currency:typeof a.currency=="string"?a.currency:void 0}}},gf=class extends hn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},u=ye(s.limit),l=ye(s.limit_remaining),f=ye(s.usage),d=ye(s.usage_daily);return u!==void 0&&(a.totalBalance=u),l!==void 0&&(a.remainingBalance=l),f!==void 0&&(a.usedBalance=f),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},yf=class extends hn{async queryQuota(e,n,r){let o=hR(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let u={},l=ye(a.totalBalance),f=ye(a.balance);return l!==void 0&&(u.totalBalance=l),f!==void 0&&(u.remainingBalance=f),l!==void 0&&f!==void 0&&(u.usedBalance=Math.max(0,l-f)),this.hasQuotaData(u)?u:null}},_f=class extends hn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let u=await a.json(),l=Array.isArray(u?.data?.limits)?u.data.limits:[],f=null,d=null,p=null;for(let b of l)b.type==="TOKENS_LIMIT"?b.unit===3?f=b:b.unit===6?d=b:f||(f=b):b.type==="TIME_LIMIT"&&(p=b);let m={};if(f){let b=ye(f.currentValue),w=ye(f.usage),y=ye(f.remaining),g=ye(f.percentage);b!==void 0?m.usedDailyBalance=b:g!==void 0&&(m.usedDailyBalance=g,m.limitDaily=100),w!==void 0?m.limitDaily=w:b!==void 0&&y!==void 0&&(m.limitDaily=b+y),f.nextResetTime&&(m.resetTime=new Date(f.nextResetTime).toISOString())}if(d){let b=ye(d.currentValue),w=ye(d.usage),y=ye(d.remaining),g=ye(d.percentage);b!==void 0?m.usedBalance=b:g!==void 0&&(m.usedBalance=g,m.totalBalance=100),w!==void 0?m.totalBalance=w:b!==void 0&&y!==void 0&&(m.totalBalance=b+y),d.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}if(p){if(m.usedDailyBalance===void 0){let b=ye(p.currentValue);b!==void 0&&(m.usedDailyBalance=b)}if(m.limitDaily===void 0){let b=ye(p.usage),w=ye(p.currentValue),y=ye(p.remaining);b!==void 0?m.limitDaily=b:w!==void 0&&y!==void 0&&(m.limitDaily=w+y)}p.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},bf=class extends hn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:u}=await import("undici");o.dispatcher=new u(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let u=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!u.ok)return null;let f=(await u.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(f)||f.length===0)return null;let d=f[0]?.codingPlanQuotaInfo;if(!d)return null;let p={},m=ye(d.per5HourUsedQuota),b=ye(d.per5HourTotalQuota);m!==void 0&&(p.usedDailyBalance=m),b!==void 0&&(p.limitDaily=b);let w=ye(d.perWeekUsedQuota),y=ye(d.perWeekTotalQuota);return w!==void 0&&(p.usedBalance=w),y!==void 0&&(p.totalBalance=y),this.hasQuotaData(p)?p:null}catch{return null}}},Cf=class extends hn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(D_(e.quotaToken,"atp-auth-token")||D_(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let u=await a.json();if(u?.succeed===!1||u?.failed===!0)return null;let l=pR(u,e.apiKey),f=l?.codingPlanUsageDTO||l?.usage||l;if(!f||typeof f!="object")return null;let d={},p=ye(f.rp5hUsage),m=ye(f.rp5hLimit);p!==void 0&&(d.usedDailyBalance=p),m!==void 0&&(d.limitDaily=m);let b=ye(f.rpwUsage),w=ye(f.rpwLimit);return b!==void 0&&(d.usedBalance=b),w!==void 0&&(d.totalBalance=w),d.remainingBalance===void 0&&w!==void 0&&b!==void 0&&(d.remainingBalance=Math.max(0,w-b)),this.hasQuotaData(d)?d:null}catch{return null}}},wf=class extends hn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let u=await a.json(),l={},f=Array.isArray(u?.limits)?u.limits:[];if(f.length>0&&f[0]?.detail){let p=f[0].detail,m=ye(p.limit),b=ye(p.remaining),w=p.resetTime;m!==void 0&&b!==void 0&&(l.usedDailyBalance=Math.max(0,m-b),l.limitDaily=m),w&&(l.resetTime=new Date(w).toISOString())}let d=u?.usage;if(d){let p=ye(d.limit),m=ye(d.remaining),b=ye(d.used),w=d.resetTime;p!==void 0&&(l.totalBalance=p,b!==void 0?l.usedBalance=b:m!==void 0&&(l.usedBalance=Math.max(0,p-m),l.remainingBalance=m)),w&&(l.resetTime7d=new Date(w).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Ef=class extends hn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=Af(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let u=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let v of u)if(l=await this.fetchJson(v,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let v=l.base_resp.status_code;if(v!==void 0&&v!==0)return null}let f=Array.isArray(l?.model_remains)?l.model_remains:[];if(f.length===0)return null;let d=f[0],p={},m=ye(d.current_interval_total_count),b=ye(d.current_interval_usage_count),w=ye(d.current_interval_remaining_percent),y=ye(d.end_time);m!==void 0&&b!==void 0&&m>0?(p.usedDailyBalance=Math.max(0,m-b),p.limitDaily=m):w!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-w)),y&&(p.resetTime=new Date(y).toISOString());let g=ye(d.current_weekly_total_count),_=ye(d.current_weekly_usage_count),A=ye(d.current_weekly_remaining_percent),C=ye(d.weekly_end_time);return g!==void 0&&_!==void 0&&g>0?(p.usedBalance=Math.max(0,g-_),p.remainingBalance=_,p.totalBalance=g):A!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-A),p.remainingBalance=A),C&&!p.resetTime&&(p.resetTime=new Date(C).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},sR=new mf,iR=new gf,aR=new yf,uR=new _f,cR=new bf,lR=new Cf,dR=new wf,fR=new Ef;function Tu(t){let e=Af(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?dR:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?fR:e==="deepseek.com"||e.endsWith(".deepseek.com")?sR:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?iR:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?aR:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?uR:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?cR:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?lR:null:null}function hR(t){let e=Af(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function pR(t,e){let n=kf(t);if(n.length===0)return null;let r=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return n.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,u=String(a?.apiKey||a?.api_key||"").trim();return u&&r.some(l=>l.includes(u)||u.includes(l))})||n[0]}function kf(t){return!t||typeof t!="object"?[]:!Array.isArray(t)&&t.codingPlanUsageDTO?[t]:Array.isArray(t)?t.flatMap(e=>kf(e)):Object.values(t).flatMap(e=>kf(e))}function D_(t,e){let n=t.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return n?decodeURIComponent(n[1]):void 0}function Af(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function ye(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let n=Number(e);return Number.isFinite(n)?n:void 0}var mR="x-claude-code-router-source",gR="x-claude-code-router-version";function R_(t){return{[mR]:t,[gR]:Ci}}var yR={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function _R(t){return t===!0||t==="true"||t===1||t==="1"}function bR(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function CR(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function wR(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Sf(t,e,n){let r=CR(t.baseUrl);if(!r)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:u}=await import("undici");o.dispatcher=new u(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Wo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}async function ER(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl,a=t.baseUrl.includes("/messages")||o.includes("claude");try{let u={"Content-Type":"application/json",...R_("scheduled-wakeup")};a?(u["x-api-key"]=t.apiKey,u["anthropic-version"]="2023-06-01"):u.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:u,body:JSON.stringify({model:o,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let f=await fetch(s,l);if(f.ok)return{success:!0};let d=await f.text().catch(()=>"");return{success:!1,error:`HTTP ${f.status}: ${d.slice(0,200)||"Unknown error"}`}}catch(u){return{success:!1,error:u?.message||u?.toString()||"Unknown wake-up error"}}}async function kR(t,e,n,r,o){let s=t.baseUrl,a=t.baseUrl.includes("/messages")||e.includes("claude");try{let u={"Content-Type":"application/json",...R_("rate-limit-probe")};a?(u["x-api-key"]=t.apiKey,u["anthropic-version"]="2023-06-01"):u.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:u,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let f=await fetch(s,l);if(f.ok)return{success:!0};let d=await f.text().catch(()=>"");return{success:!1,error:`HTTP ${f.status}: ${d.slice(0,200)||"Unknown error"}`}}catch(u){return{success:!1,error:u?.message||u?.toString()||"Unknown ping error"}}}var Ps=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={...yR,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Je();if(e.length===0)return;let o=[];for(let a of e){let u=Tu(a.baseUrl),l=Array.isArray(a.models)?a.models:[];u&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:u.queryQuota(a,this.config.probeTimeoutMs,n).then(f=>{if(f){Si(a.name,f),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,p=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||p){let m=d?`Quota exhausted: 5h limit reached (${f.usedDailyBalance}/${f.limitDaily})`:`Quota exhausted: 7d balance depleted (${f.usedBalance}/${f.totalBalance})`;for(let b of l){if(r.getState(a.name,b)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${b}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,b,m)}this.logger?.warn?.(`${m} for ${a.name}, marked as unhealthy`)}else for(let m of l){let b=r.getState(a.name,m);b&&b.status==="open"&&b.lastError?.includes("Quota exhausted")&&(r.recover(a.name,m),this.logger?.info?.(`Quota recovered for ${a.name} (${m}), marked as healthy`))}}})}),wR(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:Sf(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let u=s[a];if(u.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${u.reason}`)}}}async runHealthProbe(){let e=Je(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>Sf(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],u=o[s],l=Array.isArray(a.models)?a.models:[];if(u.status==="fulfilled"){let f=u.value;if(f.success){let d=0;for(let p of l){let m=e.getState(a.name,p);if(m&&m.status==="open"){let b=m.lastError?.includes("Quota exhausted"),w=m.rateLimitUntil||m.lastError&&(m.lastError.includes("429")||m.lastError.toLowerCase().includes("rate limit")||m.lastError.toLowerCase().includes("rate_limit")||m.lastError.toLowerCase().includes("too many requests")||m.lastError.toLowerCase().includes("\u9650\u6D41"));if(b){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${p}) because quota is exhausted`);continue}if(w||m.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${p})`);continue}}e.recordSuccess(a.name,p),d++}d>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let d of l)e.recordFailure(a.name,d,f.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${f.error}`)}}else{for(let f of l)e.recordFailure(a.name,f,u.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${u.reason}`)}}}async runRateLimitProbe(){let e=Je(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[u,...l]=a.split(","),f=l.join(",");if(!u||!f)continue;let d=e.getState(u,f);if(!d||!d.rateLimitUntil)continue;if(Date.now()>=d.rateLimitUntil){e.recover(u,f),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let p=r.find(m=>m?.name===u&&m.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${u} not found or disabled for rate-limit probe`);continue}try{let m=await kR(p,f,s,o,this.logger);if(m.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(u,f);else if(m.error&&(m.error.includes("429")||m.error.toLowerCase().includes("rate limit")||m.error.toLowerCase().includes("rate_limit")||m.error.toLowerCase().includes("too many requests")||m.error.toLowerCase().includes("\u9650\u6D41"))){let b=Date.now();d.rateLimitUntil&&d.rateLimitUntil>b?d.rateLimitUntil+=120*1e3:d.rateLimitUntil=b+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${m.error?.slice(0,100)}`)}catch(m){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${m?.message||m}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=bR(n),a=this.getHttpsProxy?.(),u=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let f=l.wakeupTime||u,[d,p]=f.split(":"),m=parseInt(d,10),b=parseInt(p,10);if(isNaN(m)||isNaN(b))continue;let w=r>m||r===m&&o>=b,y=(m*60+b)*6e4-(r*60+o)*6e4,g=y>0&&y<=300*1e3;(w||g)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${f}`),ER(l,3e4,a,this.logger).then(_=>{_.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${_.error}`)}).catch(_=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${_}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?_R(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(u=>u.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await Sf(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let u of a)Je().recordSuccess(r.name,u);else for(let u of a)Je().recordFailure(r.name,u,s.error);return s.success}},nr=null;function vf(t,e,n,r,o){return nr||(nr=new Ps(t,e,n,r,o)),nr}function Du(t,e,n,r,o){let s=vf(t,e,n,r,o);return s.start(),s}function Ru(){nr&&nr.stop()}function x_(){nr&&(nr.stop(),nr=null)}Wn();var Tf=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}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,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Df=new Tf;var U_=xe(N_(),1);var Or=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
380
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(d_).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};var f_=require("tiktoken"),Ts=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,f_.get_encoding)(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 n=this.encoding;if(!n)throw new Error("Encoding not initialized");let r=0,{messages:o,system:s,tools:a}=e;return Array.isArray(o)&&o.forEach(u=>{typeof u.content=="string"?r+=n.encode(u.content).length:Array.isArray(u.content)&&u.content.forEach(l=>{if(l.type==="text")r+=n.encode(l.text).length;else if(l.type==="tool_use")r+=n.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let f=typeof l.content=="string"?l.content:JSON.stringify(l.content);r+=n.encode(f).length}})}),typeof s=="string"?r+=n.encode(s).length:Array.isArray(s)&&s.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?r+=n.encode(u.text).length:Array.isArray(u.text)&&u.text.forEach(l=>{r+=n.encode(l||"").length}))}),a&&a.forEach(u=>{u.description&&(r+=n.encode(u.name+u.description).length),u.input_schema&&(r+=n.encode(JSON.stringify(u.input_schema)).length)}),r}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};var xs=require("path"),D_=require("os"),xo=require("fs"),Os=require("fs");var QT=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,a=null,u=o;for(;u<n&&(s=s[t[u]]);)s.end&&(a=s.end),++u;a?(o>r&&e.push(t.slice(r,o)),e.push(a),o+=a.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},XT=QT,ZT=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}},ev=ZT,b_=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),tv=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),nv=tv(b_),h_=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",rv=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|[${h_}])]+`,` ?[^\\s${h_}]+`]]),vs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",yF=new RegExp(`^[${vs}]+$`,"gu"),pf=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"),ku=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");for(let[r,o]of rv)n=n.replaceAll(r,o);return new RegExp(n,"gu")}else if(t.String!==void 0){let n=ov(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},ov=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sv=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},iv=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,av=t=>Number.isInteger(t)||typeof t=="bigint",uv=t=>{let e=0;for(let n of t)++e;return e},cv=t=>C_(t.toLowerCase()),Mt=(...t)=>Array.prototype.concat.apply([],t),mf=t=>new Map(Object.entries(t)),lv=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},C_=t=>t.replace(new RegExp("\\p{M}","gu"),""),p_=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},dv=t=>t.match(/\S+/g)||[],fv=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Ds=fv,hv=class extends Ds{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Nn=hv,pv=class extends Nn{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);iv(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
381
+ `: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 n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}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}},mv=pv,gv=class extends Nn{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}},yv=gv,_v=class extends Nn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>w_(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},bv=_v,Cv=class extends Nn{normalize(t){let e=ku(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},wv=Cv,Ev=class extends Nn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Au=Ev,kv=class extends Au{constructor(){super(...arguments),this.form="NFC"}},Av=kv,Sv=class extends Au{constructor(){super(...arguments),this.form="NFD"}},Tv=Sv,vv=class extends Au{constructor(){super(...arguments),this.form="NFKC"}},Dv=vv,Rv=class extends Au{constructor(){super(...arguments),this.form="NFKD"}},xv=Rv,Ov=class extends Nn{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}},Pv=Ov,Fv=class extends Nn{normalize(t){return C_(t)}},Iv=Fv,Nv=class extends Nn{normalize(t){return t.toLowerCase()}},Bv=Nv,Mv=class extends Nn{normalize(t){return t=this.config.prepend+t,t}},Lv=Mv;function jv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new mv(t);case"Precompiled":return new yv(t);case"Sequence":return new bv(t);case"Replace":return new wv(t);case"NFC":return new Av(t);case"NFD":return new Tv(t);case"NFKC":return new Dv(t);case"NFKD":return new xv(t);case"Strip":return new Pv(t);case"StripAccents":return new Iv(t);case"Lowercase":return new Bv(t);case"Prepend":return new Lv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var w_=jv,Uv=class extends Ds{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},dn=Uv,$v=class extends dn{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=b_,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(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},qv=$v,zv=class extends dn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Hv=zv,Wv=class extends dn{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:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},Gv=Wv,Jv=class extends dn{constructor(t){super(),this.config=t,this.pattern=ku(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):lv(t,this.pattern)}},Vv=Jv,Kv=class extends dn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${vs}]+|[${vs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Yv=Kv,Qv=class extends dn{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)||[]}},Xv=Qv,Zv=class extends dn{constructor(){super(),this.pattern=new RegExp(`[^\\s${vs}]+|[${vs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},eD=Zv,tD=class extends dn{constructor(t){super(),this.config=t,this.pattern=ku(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},nD=tD,rD=class extends dn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>E_(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},oD=rD,sD=class extends dn{pre_tokenize_text(t){return dv(t)}},iD=sD;function aD(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new eD;case"Sequence":return new oD(t);case"Whitespace":return new Hv;case"WhitespaceSplit":return new iD;case"Metaspace":return new Gv(t);case"ByteLevel":return new qv(t);case"Split":return new Vv(t);case"Punctuation":return new Yv(t);case"Digits":return new Xv(t);case"Replace":return new nD(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var E_=aD,uD=class extends Ds{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=sv(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)}},Su=uD,cD=class extends Su{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=mf(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,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let u=r.length,l=null;for(;s<u;){let f=r.slice(s,u).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--u}if(l===null){o=!0;break}a.push(l),s=u}o?e.push(this.unk_token):e.push(...a)}return e}},m_=cD,g_=class k_{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new k_(!1,new Map)}},lD=class{constructor(){this.root=g_.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=g_.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},dD=lD,hf=class A_{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new A_(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},fD=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new hf(this.bos_token_id??0,0,0,0,0),o=new hf(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new hf(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,u=null;for(let l of this.end_nodes[e]){let f=l.backtrace_score+s.score;(u===null||f>a)&&(u=l.clone(),a=f)}if(u!==null)s.prev=u,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}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)}},hD=fD;function pD(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var mD=class extends Su{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),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=pD(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new dD,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),u=this.trie.common_prefix_search(a);for(let l of u){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],h=uv(l);t.insert(r,h,d,f),!o&&h===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new hD(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},y_=mD,gD=class{constructor(t=(n,r)=>n>r,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 n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}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 n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_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}},yD=gD,_D=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()}},bD=_D,CD=class extends Su{constructor(t){super(t),this.tokens_to_ids=mf(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[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),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 bD(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 n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new yD((u,l)=>u.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let u=1;u<n.length;++u){let l={bias:u/n.length,token:n[u],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let u=o.pop();if(u.deleted||!u.next||u.next.deleted)continue;if(u.deleted=!0,u.next.deleted=!0,u.prev){let f={...u.prev};u.prev.deleted=!0,u.prev=f,f.prev?f.prev.next=f:s=f}let l={token:u.token+u.next.token,bias:u.bias,prev:u.prev,next:u.next.next};l.prev?(l.prev.next=l,this.add_node(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let u=s;u!==null;u=u.next)r.push(u.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},__=CD,wD=class extends Su{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=mf(e.target_lang?n[e.target_lang]:n),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[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},ED=wD;function kD(t,e){switch(t.type){case"WordPiece":return new m_(t);case"Unigram":return new y_(t,e.eos_token);case"BPE":return new __(t);default:if(t.vocab)return Array.isArray(t.vocab)?new y_(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new __(t):new m_(t):new ED(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 AD=kD,SD=class extends Ds{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Rs=SD,TD=class extends Rs{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Mt(o,t),s=Mt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Mt(o,e),s=Mt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},vD=TD,DD=class extends Rs{post_process(t,e=null){return{tokens:e?Mt(t,e):t}}},RD=DD,xD=class extends Rs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Mt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=Mt(t,o,e,s),r=Mt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},OD=xD,PD=class extends Rs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Mt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=Mt(t,o,e,s),r=Mt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},FD=PD,ID=class extends Rs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>S_(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},ND=ID;function BD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new vD(t);case"ByteLevel":return new RD(t);case"BertProcessing":return new OD(t);case"RobertaProcessing":return new FD(t);case"Sequence":return new ND(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var S_=BD,MD=class extends Ds{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("")}},fn=MD,LD=class extends fn{constructor(t){super(t),this.byte_decoder=nv,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(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},jD=LD,UD=class extends fn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=pf(e)),e})}},$D=UD,qD=class extends fn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},zD=qD,HD=class extends fn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},WD=HD,GD=class extends fn{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 r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=pf(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},JD=GD,VD=class extends fn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>T_(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},KD=VD,YD=class extends fn{decode_chain(t){let e=ku(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},QD=YD,XD=class extends fn{decode_chain(t){return[t.join("")]}},ZD=XD,eR=class extends fn{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 n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},tR=eR,nR=class extends fn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},rR=nR;function oR(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new jD(t);case"WordPiece":return new $D(t);case"Metaspace":return new zD(t);case"BPEDecoder":return new WD(t);case"CTC":return new JD(t);case"Sequence":return new KD(t);case"Replace":return new QD(t);case"Fuse":return new ZD(t);case"Strip":return new tR(t);case"ByteFallback":return new rR(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var T_=oR,sR=class{constructor(t,e){let n=p_(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=p_(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=w_(this.tokenizer.normalizer),this.pre_tokenizer=E_(this.tokenizer.pre_tokenizer),this.model=AD(this.tokenizer.model,this.config),this.post_processor=S_(this.tokenizer.post_processor),this.decoder=T_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new ev(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 XT(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),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:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),u={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(u.token_type_ids=s),u}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!av(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=pf(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=cv(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:Mt(r??[],o??[])}}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}},v_=sR;var Tu=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,xs.join)((0,D_.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,xs.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,xs.join)(e,"tokenizer.json"),tokenizerConfig:(0,xs.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,xo.existsSync)(e)||(0,xo.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,xo.existsSync)(e.tokenizerJson)||!(0,xo.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Os.promises.readFile(e.tokenizerJson,"utf-8"),Os.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={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 r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[u,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Os.promises.writeFile(e.tokenizerJson,JSON.stringify(u,null,2)),Os.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:u,tokenizerConfig:l}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new v_(n.tokenizerJson,n.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 n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}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 n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let u of a.content)u.type==="text"&&u.text?n.push(u.text):u.type==="tool_use"&&u.input?n.push(JSON.stringify(u.input)):u.type==="tool_result"&&n.push(typeof u.content=="string"?u.content:JSON.stringify(u.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let u of a.text)u&&n.push(u)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var vu=class{type="api";name;config;logger;options;constructor(e,n,r={}){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=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.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 n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let u=await a.json();return this.extractTokenCount(u)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}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(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var xr=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new Ts("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 n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new Ts(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Tu(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new vu(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 r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),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)}`}}};Wn();var hn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let u={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");u.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,u);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},gf=class extends hn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>ye(l?.total_balance)!==void 0);if(!a)return null;let u=ye(a.total_balance);return u===void 0?null:{totalBalance:u,currency:typeof a.currency=="string"?a.currency:void 0}}},yf=class extends hn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},u=ye(s.limit),l=ye(s.limit_remaining),f=ye(s.usage),d=ye(s.usage_daily);return u!==void 0&&(a.totalBalance=u),l!==void 0&&(a.remainingBalance=l),f!==void 0&&(a.usedBalance=f),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},_f=class extends hn{async queryQuota(e,n,r){let o=pR(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let u={},l=ye(a.totalBalance),f=ye(a.balance);return l!==void 0&&(u.totalBalance=l),f!==void 0&&(u.remainingBalance=f),l!==void 0&&f!==void 0&&(u.usedBalance=Math.max(0,l-f)),this.hasQuotaData(u)?u:null}},bf=class extends hn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let u=await a.json(),l=Array.isArray(u?.data?.limits)?u.data.limits:[],f=null,d=null,h=null;for(let C of l)C.type==="TOKENS_LIMIT"?C.unit===3?f=C:C.unit===6?d=C:f||(f=C):C.type==="TIME_LIMIT"&&(h=C);let m={};if(f){let C=ye(f.currentValue),w=ye(f.usage),y=ye(f.remaining),g=ye(f.percentage);C!==void 0?m.usedDailyBalance=C:g!==void 0&&(m.usedDailyBalance=g,m.limitDaily=100),w!==void 0?m.limitDaily=w:C!==void 0&&y!==void 0&&(m.limitDaily=C+y),f.nextResetTime&&(m.resetTime=new Date(f.nextResetTime).toISOString())}if(d){let C=ye(d.currentValue),w=ye(d.usage),y=ye(d.remaining),g=ye(d.percentage);C!==void 0?m.usedBalance=C:g!==void 0&&(m.usedBalance=g,m.totalBalance=100),w!==void 0?m.totalBalance=w:C!==void 0&&y!==void 0&&(m.totalBalance=C+y),d.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}if(h){if(m.usedDailyBalance===void 0){let C=ye(h.currentValue);C!==void 0&&(m.usedDailyBalance=C)}if(m.limitDaily===void 0){let C=ye(h.usage),w=ye(h.currentValue),y=ye(h.remaining);C!==void 0?m.limitDaily=C:w!==void 0&&y!==void 0&&(m.limitDaily=w+y)}h.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(h.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},Cf=class extends hn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:u}=await import("undici");o.dispatcher=new u(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let u=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!u.ok)return null;let f=(await u.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(f)||f.length===0)return null;let d=f[0]?.codingPlanQuotaInfo;if(!d)return null;let h={},m=ye(d.per5HourUsedQuota),C=ye(d.per5HourTotalQuota);m!==void 0&&(h.usedDailyBalance=m),C!==void 0&&(h.limitDaily=C);let w=ye(d.perWeekUsedQuota),y=ye(d.perWeekTotalQuota);return w!==void 0&&(h.usedBalance=w),y!==void 0&&(h.totalBalance=y),this.hasQuotaData(h)?h:null}catch{return null}}},wf=class extends hn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(R_(e.quotaToken,"atp-auth-token")||R_(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let u=await a.json();if(u?.succeed===!1||u?.failed===!0)return null;let l=mR(u,e.apiKey),f=l?.codingPlanUsageDTO||l?.usage||l;if(!f||typeof f!="object")return null;let d={},h=ye(f.rp5hUsage),m=ye(f.rp5hLimit);h!==void 0&&(d.usedDailyBalance=h),m!==void 0&&(d.limitDaily=m);let C=ye(f.rpwUsage),w=ye(f.rpwLimit);return C!==void 0&&(d.usedBalance=C),w!==void 0&&(d.totalBalance=w),d.remainingBalance===void 0&&w!==void 0&&C!==void 0&&(d.remainingBalance=Math.max(0,w-C)),this.hasQuotaData(d)?d:null}catch{return null}}},Ef=class extends hn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let u=await a.json(),l={},f=Array.isArray(u?.limits)?u.limits:[];if(f.length>0&&f[0]?.detail){let h=f[0].detail,m=ye(h.limit),C=ye(h.remaining),w=h.resetTime;m!==void 0&&C!==void 0&&(l.usedDailyBalance=Math.max(0,m-C),l.limitDaily=m),w&&(l.resetTime=new Date(w).toISOString())}let d=u?.usage;if(d){let h=ye(d.limit),m=ye(d.remaining),C=ye(d.used),w=d.resetTime;h!==void 0&&(l.totalBalance=h,C!==void 0?l.usedBalance=C:m!==void 0&&(l.usedBalance=Math.max(0,h-m),l.remainingBalance=m)),w&&(l.resetTime7d=new Date(w).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},kf=class extends hn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=Sf(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let u=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let S of u)if(l=await this.fetchJson(S,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let S=l.base_resp.status_code;if(S!==void 0&&S!==0)return null}let f=Array.isArray(l?.model_remains)?l.model_remains:[];if(f.length===0)return null;let d=f[0],h={},m=ye(d.current_interval_total_count),C=ye(d.current_interval_usage_count),w=ye(d.current_interval_remaining_percent),y=ye(d.end_time);m!==void 0&&C!==void 0&&m>0?(h.usedDailyBalance=Math.max(0,m-C),h.limitDaily=m):w!==void 0&&(h.limitDaily=100,h.usedDailyBalance=Math.max(0,100-w)),y&&(h.resetTime=new Date(y).toISOString());let g=ye(d.current_weekly_total_count),_=ye(d.current_weekly_usage_count),E=ye(d.current_weekly_remaining_percent),b=ye(d.weekly_end_time);return g!==void 0&&_!==void 0&&g>0?(h.usedBalance=Math.max(0,g-_),h.remainingBalance=_,h.totalBalance=g):E!==void 0&&(h.totalBalance=100,h.usedBalance=Math.max(0,100-E),h.remainingBalance=E),b&&!h.resetTime&&(h.resetTime=new Date(b).toISOString()),this.hasQuotaData(h)?h:null}catch{return null}}},iR=new gf,aR=new yf,uR=new _f,cR=new bf,lR=new Cf,dR=new wf,fR=new Ef,hR=new kf;function Du(t){let e=Sf(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?fR:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?hR:e==="deepseek.com"||e.endsWith(".deepseek.com")?iR:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?aR:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?uR:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?cR:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?lR:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?dR:null:null}function pR(t){let e=Sf(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function mR(t,e){let n=Af(t);if(n.length===0)return null;let r=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return n.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,u=String(a?.apiKey||a?.api_key||"").trim();return u&&r.some(l=>l.includes(u)||u.includes(l))})||n[0]}function Af(t){return!t||typeof t!="object"?[]:!Array.isArray(t)&&t.codingPlanUsageDTO?[t]:Array.isArray(t)?t.flatMap(e=>Af(e)):Object.values(t).flatMap(e=>Af(e))}function R_(t,e){let n=t.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return n?decodeURIComponent(n[1]):void 0}function Sf(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function ye(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let n=Number(e);return Number.isFinite(n)?n:void 0}var gR="x-claude-code-router-source",yR="x-claude-code-router-version";function x_(t){return{[gR]:t,[yR]:Ci}}var _R={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function bR(t){return t===!0||t==="true"||t===1||t==="1"}function CR(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function wR(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function ER(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Tf(t,e,n){let r=wR(t.baseUrl);if(!r)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:u}=await import("undici");o.dispatcher=new u(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Wo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}async function kR(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl,a=t.baseUrl.includes("/messages")||o.includes("claude");try{let u={"Content-Type":"application/json",...x_("scheduled-wakeup")};a?(u["x-api-key"]=t.apiKey,u["anthropic-version"]="2023-06-01"):u.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:u,body:JSON.stringify({model:o,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:h}=await import("undici");l.dispatcher=new h(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let f=await fetch(s,l);if(f.ok)return{success:!0};let d=await f.text().catch(()=>"");return{success:!1,error:`HTTP ${f.status}: ${d.slice(0,200)||"Unknown error"}`}}catch(u){return{success:!1,error:u?.message||u?.toString()||"Unknown wake-up error"}}}async function AR(t,e,n,r,o){let s=t.baseUrl,a=t.baseUrl.includes("/messages")||e.includes("claude");try{let u={"Content-Type":"application/json",...x_("rate-limit-probe")};a?(u["x-api-key"]=t.apiKey,u["anthropic-version"]="2023-06-01"):u.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:u,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:h}=await import("undici");l.dispatcher=new h(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let f=await fetch(s,l);if(f.ok)return{success:!0};let d=await f.text().catch(()=>"");return{success:!1,error:`HTTP ${f.status}: ${d.slice(0,200)||"Unknown error"}`}}catch(u){return{success:!1,error:u?.message||u?.toString()||"Unknown ping error"}}}var Ps=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={..._R,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Je();if(e.length===0)return;let o=[];for(let a of e){let u=Du(a.baseUrl),l=Array.isArray(a.models)?a.models:[];u&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:u.queryQuota(a,this.config.probeTimeoutMs,n).then(f=>{if(f){Si(a.name,f),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,h=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||h){let m=d?`Quota exhausted: 5h limit reached (${f.usedDailyBalance}/${f.limitDaily})`:`Quota exhausted: 7d balance depleted (${f.usedBalance}/${f.totalBalance})`;for(let C of l){if(r.getState(a.name,C)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${C}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,C,m)}this.logger?.warn?.(`${m} for ${a.name}, marked as unhealthy`)}else for(let m of l){let C=r.getState(a.name,m);C&&C.status==="open"&&C.lastError?.includes("Quota exhausted")&&(r.recover(a.name,m),this.logger?.info?.(`Quota recovered for ${a.name} (${m}), marked as healthy`))}}})}),ER(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:Tf(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let u=s[a];if(u.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${u.reason}`)}}}async runHealthProbe(){let e=Je(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>Tf(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],u=o[s],l=Array.isArray(a.models)?a.models:[];if(u.status==="fulfilled"){let f=u.value;if(f.success){let d=0;for(let h of l){let m=e.getState(a.name,h);if(m&&m.status==="open"){let C=m.lastError?.includes("Quota exhausted"),w=m.rateLimitUntil||m.lastError&&(m.lastError.includes("429")||m.lastError.toLowerCase().includes("rate limit")||m.lastError.toLowerCase().includes("rate_limit")||m.lastError.toLowerCase().includes("too many requests")||m.lastError.toLowerCase().includes("\u9650\u6D41"));if(C){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${h}) because quota is exhausted`);continue}if(w||m.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${h})`);continue}}e.recordSuccess(a.name,h),d++}d>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let d of l)e.recordFailure(a.name,d,f.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${f.error}`)}}else{for(let f of l)e.recordFailure(a.name,f,u.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${u.reason}`)}}}async runRateLimitProbe(){let e=Je(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[u,...l]=a.split(","),f=l.join(",");if(!u||!f)continue;let d=e.getState(u,f);if(!d||!d.rateLimitUntil)continue;if(Date.now()>=d.rateLimitUntil){e.recover(u,f),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let h=r.find(m=>m?.name===u&&m.enabled!==!1);if(!h){this.logger?.warn?.(`Provider ${u} not found or disabled for rate-limit probe`);continue}try{let m=await AR(h,f,s,o,this.logger);if(m.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(u,f);else if(m.error&&(m.error.includes("429")||m.error.toLowerCase().includes("rate limit")||m.error.toLowerCase().includes("rate_limit")||m.error.toLowerCase().includes("too many requests")||m.error.toLowerCase().includes("\u9650\u6D41"))){let C=Date.now();d.rateLimitUntil&&d.rateLimitUntil>C?d.rateLimitUntil+=120*1e3:d.rateLimitUntil=C+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${m.error?.slice(0,100)}`)}catch(m){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${m?.message||m}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=CR(n),a=this.getHttpsProxy?.(),u=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let f=l.wakeupTime||u,[d,h]=f.split(":"),m=parseInt(d,10),C=parseInt(h,10);if(isNaN(m)||isNaN(C))continue;let w=r>m||r===m&&o>=C,y=(m*60+C)*6e4-(r*60+o)*6e4,g=y>0&&y<=300*1e3;(w||g)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${f}`),kR(l,3e4,a,this.logger).then(_=>{_.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${_.error}`)}).catch(_=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${_}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?bR(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(u=>u.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await Tf(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let u of a)Je().recordSuccess(r.name,u);else for(let u of a)Je().recordFailure(r.name,u,s.error);return s.success}},nr=null;function vf(t,e,n,r,o){return nr||(nr=new Ps(t,e,n,r,o)),nr}function Ru(t,e,n,r,o){let s=vf(t,e,n,r,o);return s.start(),s}function xu(){nr&&nr.stop()}function O_(){nr&&(nr.stop(),nr=null)}Wn();var Df=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}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,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Rf=new Df;var $_=xe(B_(),1);var Or=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
364
382
  `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,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 Fs=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
365
383
  `),e.id&&(r+=`id: ${e.id}
366
384
  `),e.retry&&(r+=`retry: ${e.retry}
367
385
  `),e.data&&(e.data.type==="done"?r+=`data: [DONE]
368
386
  `:r+=`data: ${JSON.stringify(e.data)}
369
387
  `),r+=`
370
- `,n.enqueue(r)}})}};var Of=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};Pf();Ff();Nf();M_();var Ms=new Map,Mf=new Map,RR=1,Lf={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,U_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)Po.registerHandlers(n.outputHandlers);else{let a=[];for(let u of r)u==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):u==="temp-file"?a.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");a.length>0&&Po.registerHandlers(a)}n.outputOptions&&Po.setDefaultOptions(n.outputOptions);let o=async a=>{let u=t.tokenizerService;if(!u)return t.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,f=a.model,d=`${l}:${f}`;if(Mf.has(d))return Mf.get(d);let p=u.getTokenizerConfigForModel(l,f);if(!p)return t.log?.debug(`No tokenizer config for ${l}:${f}, using fallback`),null;try{let m=await u.getTokenizer(p);return Mf.set(d,m),t.log?.info(`Created tokenizer for ${l}:${f} - ${m.name}`),m}catch(m){return t.log?.warn(`Failed to create tokenizer for ${l}:${f}: ${m.message}`),null}},s=a=>{let u=new URL(`http://127.0.0.1${a}`).pathname;return u.endsWith("/v1/messages")||u.endsWith("/v1/responses")};t.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),t.addHook("onSend",async(a,u,l)=>{let f=a.requestStartTime;if(!f)return;let d=a.id||Date.now().toString(),p;try{p=Qr(a.body?.metadata?.user_id)}catch{}if(!p){let g=a.headers?.["x-request-id"],_=Array.isArray(g)?g[0]:g;p=a.sessionId||(typeof _=="string"?_:void 0)||d}let m=await o(a);if(l instanceof ReadableStream){Ms.set(d,{requestId:d,sessionId:p,startTime:f,lastTokenTime:f,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[g,_]=l.tee();return(async()=>{let C=null,v=async T=>{let R=Ms.get(d);if(!R)return;let $=performance.now();if(T){let G=R.firstTokenTime?R.firstTokenTime-R.startTime:0,P=R.lastTokenTime-R.startTime;R.tokensPerSecond=L_(R.tokenCount,P,G)}else{let G=$-1e3;R.tokenTimestamps=R.tokenTimestamps.filter(P=>P>G),R.tokensPerSecond=R.tokenTimestamps.length}await j_(R,r,n.outputOptions,T).catch(G=>{t.log?.warn(`Failed to output streaming stats: ${G.message}`)})};try{let R=_.pipeThrough(new TextDecoderStream).pipeThrough(new Or).getReader();for(C=setInterval(async()=>{Ms.get(d)&&await v(!1)},1e3);;){let{done:$,value:G}=await R.read();if($)break;let P=G,K=Ms.get(d);if(!K)continue;let z=performance.now(),Y=P.event||P.data?.type,Q=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||Y==="response.output_text.delta"||Y==="response.function_call_arguments.delta"||Y==="response.reasoning_summary_text.delta";!K.firstTokenTime&&Q&&(K.firstTokenTime=z,K.timeToFirstToken=Math.round(z-K.startTime));let ee="";if(P.event==="content_block_delta"&&P.data?.delta){let oe=P.data.delta.type;oe==="text_delta"?ee=P.data.delta.text||"":oe==="input_json_delta"?ee=P.data.delta.partial_json||"":oe==="thinking_delta"&&(ee=P.data.delta.thinking||"")}if((Y==="response.output_text.delta"||Y==="response.function_call_arguments.delta"||Y==="response.reasoning_summary_text.delta")&&(ee=typeof P.data?.delta=="string"?P.data.delta:""),ee){let oe=m&&m.encodeText?m.encodeText(ee).length:Ls(ee);K.tokenCount+=oe,K.lastTokenTime=z;for(let se=0;se<oe;se++)K.tokenTimestamps.push(z)}(P.event==="message_stop"||Y==="response.completed"||Y==="response.failed")&&(C&&(clearInterval(C),C=null),await v(!0),Ms.delete(d))}}catch(T){C&&clearInterval(C),T.name!=="AbortError"&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${T.message}`)}})().catch(C=>{console.log(C),t.log?.warn(`Background stats processing failed: ${C.message}`)}),g}let b=performance.now(),w=0,y=!1;if(l&&typeof l=="string")try{let g=JSON.parse(l);if(typeof g.usage?.output_tokens=="number")w=g.usage.output_tokens,y=!0;else{let _=g.content??g.message?.content;if(_!==void 0)if(y=!0,m)Array.isArray(_)?w=_.reduce((A,C)=>{if(C.type==="text"){let v=C.text||"";return A+(m.encodeText?m.encodeText(v).length:Ls(v))}return A},0):typeof _=="string"&&(w=m.encodeText?m.encodeText(_).length:Ls(_));else{let A=Array.isArray(_)?_.map(C=>C.text).join(""):typeof _=="string"?_:"";w=Ls(A)}}}catch{}if(y){let g=Math.round(b-f),_=b-f,A={requestId:d,sessionId:p,startTime:f,lastTokenTime:b,tokenCount:w,tokensPerSecond:L_(w,_),timeToFirstToken:g,stream:!1,tokenTimestamps:[]};await j_(A,r,n.outputOptions,!0)}return l})})};function L_(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,RR);return Math.round(t/r)}function Ls(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function j_(t,e,n,r=!1){let o=r?"[Token Speed Final]":"[Token Speed]",s={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()},a={prefix:o,metadata:{sessionId:t.sessionId},...n};for(let u of e)try{await Po.outputToType(u,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${u}:`,l)}}Wn();Wn();function xR(t={}){let e=(0,$_.default)({bodyLimit:52428800,...t});return e.setErrorHandler(np),e.register(q_.default),e}var jf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=xR({...r,logger:r.logger??!0}),this.configService=new hr(e),this.transformerService=new Rr(this.configService,this.app.log),this.tokenizerService=new xr(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new yr(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async u=>{u.decorate("configService",this.configService),u.decorate("transformerService",this.transformerService),u.decorate("providerService",this.providerService),u.decorate("tokenizerService",this.tokenizerService),u.decorate("recordUsage",this.recordUsage||(()=>{})),u.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await eo(l,f,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Oc(u)});return}if(!n)throw new Error("options is required");let r=new hr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new Rr(r,this.app.log);await o.initialize();let s=new yr(r,o,this.app.log),a=new xr(r,this.app.log);await a.initialize(),await this.app.register(async u=>{u.decorate("configService",r),u.decorate("transformerService",o),u.decorate("providerService",s),u.decorate("tokenizerService",a),u.decorate("recordUsage",this.recordUsage||(()=>{})),u.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await eo(l,f,{configService:r,tokenizerService:a})}),await Oc(u)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let u=r.body;r.log.info({data:u,type:"request body"}),u.stream||(u.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let u=a.model.split(","),l=a.model;if(u.length>1){let[f,...d]=u;l=d.join(","),a.model=l,r.provider=f}r.model=l;return}catch(a){return r.log.error({error:a},"Error in modelProviderMiddleware:"),o.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{ki()}catch{}try{Ti()}catch{}try{Ei()}catch{}try{let r={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Du(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{Ru()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},OR=jf;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,normalizeSessionId,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
388
+ `,n.enqueue(r)}})}};var Pf=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};Ff();If();Bf();L_();var Ms=new Map,Lf=new Map,xR=1,jf={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,$_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)Po.registerHandlers(n.outputHandlers);else{let a=[];for(let u of r)u==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):u==="temp-file"?a.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");a.length>0&&Po.registerHandlers(a)}n.outputOptions&&Po.setDefaultOptions(n.outputOptions);let o=async a=>{let u=t.tokenizerService;if(!u)return t.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,f=a.model,d=`${l}:${f}`;if(Lf.has(d))return Lf.get(d);let h=u.getTokenizerConfigForModel(l,f);if(!h)return t.log?.debug(`No tokenizer config for ${l}:${f}, using fallback`),null;try{let m=await u.getTokenizer(h);return Lf.set(d,m),t.log?.info(`Created tokenizer for ${l}:${f} - ${m.name}`),m}catch(m){return t.log?.warn(`Failed to create tokenizer for ${l}:${f}: ${m.message}`),null}},s=a=>{let u=new URL(`http://127.0.0.1${a}`).pathname;return u.endsWith("/v1/messages")||u.endsWith("/v1/responses")};t.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),t.addHook("onSend",async(a,u,l)=>{let f=a.requestStartTime;if(!f)return;let d=a.id||Date.now().toString(),h;try{h=Qr(a.body?.metadata?.user_id)}catch{}if(!h){let g=a.headers?.["x-request-id"],_=Array.isArray(g)?g[0]:g;h=a.sessionId||(typeof _=="string"?_:void 0)||d}let m=await o(a);if(l instanceof ReadableStream){Ms.set(d,{requestId:d,sessionId:h,startTime:f,lastTokenTime:f,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[g,_]=l.tee();return(async()=>{let b=null,S=async v=>{let R=Ms.get(d);if(!R)return;let $=performance.now();if(v){let H=R.firstTokenTime?R.firstTokenTime-R.startTime:0,P=R.lastTokenTime-R.startTime;R.tokensPerSecond=j_(R.tokenCount,P,H)}else{let H=$-1e3;R.tokenTimestamps=R.tokenTimestamps.filter(P=>P>H),R.tokensPerSecond=R.tokenTimestamps.length}await U_(R,r,n.outputOptions,v).catch(H=>{t.log?.warn(`Failed to output streaming stats: ${H.message}`)})};try{let R=_.pipeThrough(new TextDecoderStream).pipeThrough(new Or).getReader();for(b=setInterval(async()=>{Ms.get(d)&&await S(!1)},1e3);;){let{done:$,value:H}=await R.read();if($)break;let P=H,K=Ms.get(d);if(!K)continue;let q=performance.now(),Y=P.event||P.data?.type,Q=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||Y==="response.output_text.delta"||Y==="response.function_call_arguments.delta"||Y==="response.reasoning_summary_text.delta";!K.firstTokenTime&&Q&&(K.firstTokenTime=q,K.timeToFirstToken=Math.round(q-K.startTime));let ee="";if(P.event==="content_block_delta"&&P.data?.delta){let oe=P.data.delta.type;oe==="text_delta"?ee=P.data.delta.text||"":oe==="input_json_delta"?ee=P.data.delta.partial_json||"":oe==="thinking_delta"&&(ee=P.data.delta.thinking||"")}if((Y==="response.output_text.delta"||Y==="response.function_call_arguments.delta"||Y==="response.reasoning_summary_text.delta")&&(ee=typeof P.data?.delta=="string"?P.data.delta:""),ee){let oe=m&&m.encodeText?m.encodeText(ee).length:Ls(ee);K.tokenCount+=oe,K.lastTokenTime=q;for(let se=0;se<oe;se++)K.tokenTimestamps.push(q)}(P.event==="message_stop"||Y==="response.completed"||Y==="response.failed")&&(b&&(clearInterval(b),b=null),await S(!0),Ms.delete(d))}}catch(v){b&&clearInterval(b),v.name!=="AbortError"&&v.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${v.message}`)}})().catch(b=>{console.log(b),t.log?.warn(`Background stats processing failed: ${b.message}`)}),g}let C=performance.now(),w=0,y=!1;if(l&&typeof l=="string")try{let g=JSON.parse(l);if(typeof g.usage?.output_tokens=="number")w=g.usage.output_tokens,y=!0;else{let _=g.content??g.message?.content;if(_!==void 0)if(y=!0,m)Array.isArray(_)?w=_.reduce((E,b)=>{if(b.type==="text"){let S=b.text||"";return E+(m.encodeText?m.encodeText(S).length:Ls(S))}return E},0):typeof _=="string"&&(w=m.encodeText?m.encodeText(_).length:Ls(_));else{let E=Array.isArray(_)?_.map(b=>b.text).join(""):typeof _=="string"?_:"";w=Ls(E)}}}catch{}if(y){let g=Math.round(C-f),_=C-f,E={requestId:d,sessionId:h,startTime:f,lastTokenTime:C,tokenCount:w,tokensPerSecond:j_(w,_),timeToFirstToken:g,stream:!1,tokenTimestamps:[]};await U_(E,r,n.outputOptions,!0)}return l})})};function j_(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,xR);return Math.round(t/r)}function Ls(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function U_(t,e,n,r=!1){let o=r?"[Token Speed Final]":"[Token Speed]",s={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()},a={prefix:o,metadata:{sessionId:t.sessionId},...n};for(let u of e)try{await Po.outputToType(u,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${u}:`,l)}}Wn();Wn();function OR(t={}){let e=(0,q_.default)({bodyLimit:52428800,...t});return e.setErrorHandler(rp),e.register(z_.default),e}var Uf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=OR({...r,logger:r.logger??!0}),this.configService=new hr(e),this.transformerService=new Rr(this.configService,this.app.log),this.tokenizerService=new xr(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new yr(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async u=>{u.decorate("configService",this.configService),u.decorate("transformerService",this.transformerService),u.decorate("providerService",this.providerService),u.decorate("tokenizerService",this.tokenizerService),u.decorate("recordUsage",this.recordUsage||(()=>{})),u.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await eo(l,f,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Pc(u)});return}if(!n)throw new Error("options is required");let r=new hr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new Rr(r,this.app.log);await o.initialize();let s=new yr(r,o,this.app.log),a=new xr(r,this.app.log);await a.initialize(),await this.app.register(async u=>{u.decorate("configService",r),u.decorate("transformerService",o),u.decorate("providerService",s),u.decorate("tokenizerService",a),u.decorate("recordUsage",this.recordUsage||(()=>{})),u.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await eo(l,f,{configService:r,tokenizerService:a})}),await Pc(u)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let u=r.body;r.log.info({data:u,type:"request body"}),u.stream||(u.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let u=a.model.split(","),l=a.model;if(u.length>1){let[f,...d]=u;l=d.join(","),a.model=l,r.provider=f}r.model=l;return}catch(a){return r.log.error({error:a},"Error in modelProviderMiddleware:"),o.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{ki()}catch{}try{vi()}catch{}try{Ei()}catch{}try{let r={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Ru(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{xu()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},PR=Uf;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,normalizeSessionId,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
371
389
  /*! Bundled license information:
372
390
 
373
391
  web-streams-polyfill/dist/ponyfill.es2018.js: