index.cjs 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __commonJS = (cb, mod) => function __require() {
  9. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  10. };
  11. var __export = (target, all) => {
  12. for (var name in all)
  13. __defProp(target, name, { get: all[name], enumerable: true });
  14. };
  15. var __copyProps = (to, from, except, desc) => {
  16. if (from && typeof from === "object" || typeof from === "function") {
  17. for (let key of __getOwnPropNames(from))
  18. if (!__hasOwnProp.call(to, key) && key !== except)
  19. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  20. }
  21. return to;
  22. };
  23. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  24. // If the importer is in node compatibility mode or this is not an ESM
  25. // file that has been converted to a CommonJS file using a Babel-
  26. // compatible transform (i.e. "__esModule" has not been set), then set
  27. // "default" to the CommonJS "module.exports" for node compatibility.
  28. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  29. mod
  30. ));
  31. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  32. // node_modules/ms/index.js
  33. var require_ms = __commonJS({
  34. "node_modules/ms/index.js"(exports2, module2) {
  35. var s = 1e3;
  36. var m = s * 60;
  37. var h = m * 60;
  38. var d = h * 24;
  39. var w = d * 7;
  40. var y = d * 365.25;
  41. module2.exports = function(val, options) {
  42. options = options || {};
  43. var type = typeof val;
  44. if (type === "string" && val.length > 0) {
  45. return parse(val);
  46. } else if (type === "number" && isFinite(val)) {
  47. return options.long ? fmtLong(val) : fmtShort(val);
  48. }
  49. throw new Error(
  50. "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
  51. );
  52. };
  53. function parse(str) {
  54. str = String(str);
  55. if (str.length > 100) {
  56. return;
  57. }
  58. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  59. str
  60. );
  61. if (!match) {
  62. return;
  63. }
  64. var n = parseFloat(match[1]);
  65. var type = (match[2] || "ms").toLowerCase();
  66. switch (type) {
  67. case "years":
  68. case "year":
  69. case "yrs":
  70. case "yr":
  71. case "y":
  72. return n * y;
  73. case "weeks":
  74. case "week":
  75. case "w":
  76. return n * w;
  77. case "days":
  78. case "day":
  79. case "d":
  80. return n * d;
  81. case "hours":
  82. case "hour":
  83. case "hrs":
  84. case "hr":
  85. case "h":
  86. return n * h;
  87. case "minutes":
  88. case "minute":
  89. case "mins":
  90. case "min":
  91. case "m":
  92. return n * m;
  93. case "seconds":
  94. case "second":
  95. case "secs":
  96. case "sec":
  97. case "s":
  98. return n * s;
  99. case "milliseconds":
  100. case "millisecond":
  101. case "msecs":
  102. case "msec":
  103. case "ms":
  104. return n;
  105. default:
  106. return void 0;
  107. }
  108. }
  109. function fmtShort(ms) {
  110. var msAbs = Math.abs(ms);
  111. if (msAbs >= d) {
  112. return Math.round(ms / d) + "d";
  113. }
  114. if (msAbs >= h) {
  115. return Math.round(ms / h) + "h";
  116. }
  117. if (msAbs >= m) {
  118. return Math.round(ms / m) + "m";
  119. }
  120. if (msAbs >= s) {
  121. return Math.round(ms / s) + "s";
  122. }
  123. return ms + "ms";
  124. }
  125. function fmtLong(ms) {
  126. var msAbs = Math.abs(ms);
  127. if (msAbs >= d) {
  128. return plural(ms, msAbs, d, "day");
  129. }
  130. if (msAbs >= h) {
  131. return plural(ms, msAbs, h, "hour");
  132. }
  133. if (msAbs >= m) {
  134. return plural(ms, msAbs, m, "minute");
  135. }
  136. if (msAbs >= s) {
  137. return plural(ms, msAbs, s, "second");
  138. }
  139. return ms + " ms";
  140. }
  141. function plural(ms, msAbs, n, name) {
  142. var isPlural = msAbs >= n * 1.5;
  143. return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
  144. }
  145. }
  146. });
  147. // node_modules/debug/src/common.js
  148. var require_common = __commonJS({
  149. "node_modules/debug/src/common.js"(exports2, module2) {
  150. function setup(env) {
  151. createDebug.debug = createDebug;
  152. createDebug.default = createDebug;
  153. createDebug.coerce = coerce;
  154. createDebug.disable = disable;
  155. createDebug.enable = enable;
  156. createDebug.enabled = enabled;
  157. createDebug.humanize = require_ms();
  158. createDebug.destroy = destroy;
  159. Object.keys(env).forEach((key) => {
  160. createDebug[key] = env[key];
  161. });
  162. createDebug.names = [];
  163. createDebug.skips = [];
  164. createDebug.formatters = {};
  165. function selectColor(namespace) {
  166. let hash = 0;
  167. for (let i = 0; i < namespace.length; i++) {
  168. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  169. hash |= 0;
  170. }
  171. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  172. }
  173. createDebug.selectColor = selectColor;
  174. function createDebug(namespace) {
  175. let prevTime;
  176. let enableOverride = null;
  177. let namespacesCache;
  178. let enabledCache;
  179. function debug3(...args) {
  180. if (!debug3.enabled) {
  181. return;
  182. }
  183. const self = debug3;
  184. const curr = Number(/* @__PURE__ */ new Date());
  185. const ms = curr - (prevTime || curr);
  186. self.diff = ms;
  187. self.prev = prevTime;
  188. self.curr = curr;
  189. prevTime = curr;
  190. args[0] = createDebug.coerce(args[0]);
  191. if (typeof args[0] !== "string") {
  192. args.unshift("%O");
  193. }
  194. let index = 0;
  195. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => {
  196. if (match === "%%") {
  197. return "%";
  198. }
  199. index++;
  200. const formatter = createDebug.formatters[format2];
  201. if (typeof formatter === "function") {
  202. const val = args[index];
  203. match = formatter.call(self, val);
  204. args.splice(index, 1);
  205. index--;
  206. }
  207. return match;
  208. });
  209. createDebug.formatArgs.call(self, args);
  210. const logFn = self.log || createDebug.log;
  211. logFn.apply(self, args);
  212. }
  213. debug3.namespace = namespace;
  214. debug3.useColors = createDebug.useColors();
  215. debug3.color = createDebug.selectColor(namespace);
  216. debug3.extend = extend;
  217. debug3.destroy = createDebug.destroy;
  218. Object.defineProperty(debug3, "enabled", {
  219. enumerable: true,
  220. configurable: false,
  221. get: () => {
  222. if (enableOverride !== null) {
  223. return enableOverride;
  224. }
  225. if (namespacesCache !== createDebug.namespaces) {
  226. namespacesCache = createDebug.namespaces;
  227. enabledCache = createDebug.enabled(namespace);
  228. }
  229. return enabledCache;
  230. },
  231. set: (v) => {
  232. enableOverride = v;
  233. }
  234. });
  235. if (typeof createDebug.init === "function") {
  236. createDebug.init(debug3);
  237. }
  238. return debug3;
  239. }
  240. function extend(namespace, delimiter) {
  241. const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
  242. newDebug.log = this.log;
  243. return newDebug;
  244. }
  245. function enable(namespaces) {
  246. createDebug.save(namespaces);
  247. createDebug.namespaces = namespaces;
  248. createDebug.names = [];
  249. createDebug.skips = [];
  250. let i;
  251. const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
  252. const len = split.length;
  253. for (i = 0; i < len; i++) {
  254. if (!split[i]) {
  255. continue;
  256. }
  257. namespaces = split[i].replace(/\*/g, ".*?");
  258. if (namespaces[0] === "-") {
  259. createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
  260. } else {
  261. createDebug.names.push(new RegExp("^" + namespaces + "$"));
  262. }
  263. }
  264. }
  265. function disable() {
  266. const namespaces = [
  267. ...createDebug.names.map(toNamespace),
  268. ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
  269. ].join(",");
  270. createDebug.enable("");
  271. return namespaces;
  272. }
  273. function enabled(name) {
  274. if (name[name.length - 1] === "*") {
  275. return true;
  276. }
  277. let i;
  278. let len;
  279. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  280. if (createDebug.skips[i].test(name)) {
  281. return false;
  282. }
  283. }
  284. for (i = 0, len = createDebug.names.length; i < len; i++) {
  285. if (createDebug.names[i].test(name)) {
  286. return true;
  287. }
  288. }
  289. return false;
  290. }
  291. function toNamespace(regexp) {
  292. return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
  293. }
  294. function coerce(val) {
  295. if (val instanceof Error) {
  296. return val.stack || val.message;
  297. }
  298. return val;
  299. }
  300. function destroy() {
  301. console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
  302. }
  303. createDebug.enable(createDebug.load());
  304. return createDebug;
  305. }
  306. module2.exports = setup;
  307. }
  308. });
  309. // node_modules/debug/src/browser.js
  310. var require_browser = __commonJS({
  311. "node_modules/debug/src/browser.js"(exports2, module2) {
  312. exports2.formatArgs = formatArgs;
  313. exports2.save = save;
  314. exports2.load = load;
  315. exports2.useColors = useColors;
  316. exports2.storage = localstorage();
  317. exports2.destroy = /* @__PURE__ */ (() => {
  318. let warned = false;
  319. return () => {
  320. if (!warned) {
  321. warned = true;
  322. console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
  323. }
  324. };
  325. })();
  326. exports2.colors = [
  327. "#0000CC",
  328. "#0000FF",
  329. "#0033CC",
  330. "#0033FF",
  331. "#0066CC",
  332. "#0066FF",
  333. "#0099CC",
  334. "#0099FF",
  335. "#00CC00",
  336. "#00CC33",
  337. "#00CC66",
  338. "#00CC99",
  339. "#00CCCC",
  340. "#00CCFF",
  341. "#3300CC",
  342. "#3300FF",
  343. "#3333CC",
  344. "#3333FF",
  345. "#3366CC",
  346. "#3366FF",
  347. "#3399CC",
  348. "#3399FF",
  349. "#33CC00",
  350. "#33CC33",
  351. "#33CC66",
  352. "#33CC99",
  353. "#33CCCC",
  354. "#33CCFF",
  355. "#6600CC",
  356. "#6600FF",
  357. "#6633CC",
  358. "#6633FF",
  359. "#66CC00",
  360. "#66CC33",
  361. "#9900CC",
  362. "#9900FF",
  363. "#9933CC",
  364. "#9933FF",
  365. "#99CC00",
  366. "#99CC33",
  367. "#CC0000",
  368. "#CC0033",
  369. "#CC0066",
  370. "#CC0099",
  371. "#CC00CC",
  372. "#CC00FF",
  373. "#CC3300",
  374. "#CC3333",
  375. "#CC3366",
  376. "#CC3399",
  377. "#CC33CC",
  378. "#CC33FF",
  379. "#CC6600",
  380. "#CC6633",
  381. "#CC9900",
  382. "#CC9933",
  383. "#CCCC00",
  384. "#CCCC33",
  385. "#FF0000",
  386. "#FF0033",
  387. "#FF0066",
  388. "#FF0099",
  389. "#FF00CC",
  390. "#FF00FF",
  391. "#FF3300",
  392. "#FF3333",
  393. "#FF3366",
  394. "#FF3399",
  395. "#FF33CC",
  396. "#FF33FF",
  397. "#FF6600",
  398. "#FF6633",
  399. "#FF9900",
  400. "#FF9933",
  401. "#FFCC00",
  402. "#FFCC33"
  403. ];
  404. function useColors() {
  405. if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
  406. return true;
  407. }
  408. if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  409. return false;
  410. }
  411. let m;
  412. return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  413. typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  414. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  415. typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  416. typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  417. }
  418. function formatArgs(args) {
  419. args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
  420. if (!this.useColors) {
  421. return;
  422. }
  423. const c = "color: " + this.color;
  424. args.splice(1, 0, c, "color: inherit");
  425. let index = 0;
  426. let lastC = 0;
  427. args[0].replace(/%[a-zA-Z%]/g, (match) => {
  428. if (match === "%%") {
  429. return;
  430. }
  431. index++;
  432. if (match === "%c") {
  433. lastC = index;
  434. }
  435. });
  436. args.splice(lastC, 0, c);
  437. }
  438. exports2.log = console.debug || console.log || (() => {
  439. });
  440. function save(namespaces) {
  441. try {
  442. if (namespaces) {
  443. exports2.storage.setItem("debug", namespaces);
  444. } else {
  445. exports2.storage.removeItem("debug");
  446. }
  447. } catch (error) {
  448. }
  449. }
  450. function load() {
  451. let r;
  452. try {
  453. r = exports2.storage.getItem("debug");
  454. } catch (error) {
  455. }
  456. if (!r && typeof process !== "undefined" && "env" in process) {
  457. r = process.env.DEBUG;
  458. }
  459. return r;
  460. }
  461. function localstorage() {
  462. try {
  463. return localStorage;
  464. } catch (error) {
  465. }
  466. }
  467. module2.exports = require_common()(exports2);
  468. var { formatters } = module2.exports;
  469. formatters.j = function(v) {
  470. try {
  471. return JSON.stringify(v);
  472. } catch (error) {
  473. return "[UnexpectedJSONParseError]: " + error.message;
  474. }
  475. };
  476. }
  477. });
  478. // node_modules/has-flag/index.js
  479. var require_has_flag = __commonJS({
  480. "node_modules/has-flag/index.js"(exports2, module2) {
  481. "use strict";
  482. module2.exports = (flag, argv = process.argv) => {
  483. const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  484. const position = argv.indexOf(prefix + flag);
  485. const terminatorPosition = argv.indexOf("--");
  486. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  487. };
  488. }
  489. });
  490. // node_modules/supports-color/index.js
  491. var require_supports_color = __commonJS({
  492. "node_modules/supports-color/index.js"(exports2, module2) {
  493. "use strict";
  494. var os = require("os");
  495. var tty = require("tty");
  496. var hasFlag = require_has_flag();
  497. var { env } = process;
  498. var forceColor;
  499. if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  500. forceColor = 0;
  501. } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  502. forceColor = 1;
  503. }
  504. if ("FORCE_COLOR" in env) {
  505. if (env.FORCE_COLOR === "true") {
  506. forceColor = 1;
  507. } else if (env.FORCE_COLOR === "false") {
  508. forceColor = 0;
  509. } else {
  510. forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
  511. }
  512. }
  513. function translateLevel(level) {
  514. if (level === 0) {
  515. return false;
  516. }
  517. return {
  518. level,
  519. hasBasic: true,
  520. has256: level >= 2,
  521. has16m: level >= 3
  522. };
  523. }
  524. function supportsColor(haveStream, streamIsTTY) {
  525. if (forceColor === 0) {
  526. return 0;
  527. }
  528. if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
  529. return 3;
  530. }
  531. if (hasFlag("color=256")) {
  532. return 2;
  533. }
  534. if (haveStream && !streamIsTTY && forceColor === void 0) {
  535. return 0;
  536. }
  537. const min = forceColor || 0;
  538. if (env.TERM === "dumb") {
  539. return min;
  540. }
  541. if (process.platform === "win32") {
  542. const osRelease = os.release().split(".");
  543. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  544. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  545. }
  546. return 1;
  547. }
  548. if ("CI" in env) {
  549. if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
  550. return 1;
  551. }
  552. return min;
  553. }
  554. if ("TEAMCITY_VERSION" in env) {
  555. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  556. }
  557. if (env.COLORTERM === "truecolor") {
  558. return 3;
  559. }
  560. if ("TERM_PROGRAM" in env) {
  561. const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  562. switch (env.TERM_PROGRAM) {
  563. case "iTerm.app":
  564. return version >= 3 ? 3 : 2;
  565. case "Apple_Terminal":
  566. return 2;
  567. }
  568. }
  569. if (/-256(color)?$/i.test(env.TERM)) {
  570. return 2;
  571. }
  572. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  573. return 1;
  574. }
  575. if ("COLORTERM" in env) {
  576. return 1;
  577. }
  578. return min;
  579. }
  580. function getSupportLevel(stream) {
  581. const level = supportsColor(stream, stream && stream.isTTY);
  582. return translateLevel(level);
  583. }
  584. module2.exports = {
  585. supportsColor: getSupportLevel,
  586. stdout: translateLevel(supportsColor(true, tty.isatty(1))),
  587. stderr: translateLevel(supportsColor(true, tty.isatty(2)))
  588. };
  589. }
  590. });
  591. // node_modules/debug/src/node.js
  592. var require_node = __commonJS({
  593. "node_modules/debug/src/node.js"(exports2, module2) {
  594. var tty = require("tty");
  595. var util = require("util");
  596. exports2.init = init;
  597. exports2.log = log;
  598. exports2.formatArgs = formatArgs;
  599. exports2.save = save;
  600. exports2.load = load;
  601. exports2.useColors = useColors;
  602. exports2.destroy = util.deprecate(
  603. () => {
  604. },
  605. "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
  606. );
  607. exports2.colors = [6, 2, 3, 4, 5, 1];
  608. try {
  609. const supportsColor = require_supports_color();
  610. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  611. exports2.colors = [
  612. 20,
  613. 21,
  614. 26,
  615. 27,
  616. 32,
  617. 33,
  618. 38,
  619. 39,
  620. 40,
  621. 41,
  622. 42,
  623. 43,
  624. 44,
  625. 45,
  626. 56,
  627. 57,
  628. 62,
  629. 63,
  630. 68,
  631. 69,
  632. 74,
  633. 75,
  634. 76,
  635. 77,
  636. 78,
  637. 79,
  638. 80,
  639. 81,
  640. 92,
  641. 93,
  642. 98,
  643. 99,
  644. 112,
  645. 113,
  646. 128,
  647. 129,
  648. 134,
  649. 135,
  650. 148,
  651. 149,
  652. 160,
  653. 161,
  654. 162,
  655. 163,
  656. 164,
  657. 165,
  658. 166,
  659. 167,
  660. 168,
  661. 169,
  662. 170,
  663. 171,
  664. 172,
  665. 173,
  666. 178,
  667. 179,
  668. 184,
  669. 185,
  670. 196,
  671. 197,
  672. 198,
  673. 199,
  674. 200,
  675. 201,
  676. 202,
  677. 203,
  678. 204,
  679. 205,
  680. 206,
  681. 207,
  682. 208,
  683. 209,
  684. 214,
  685. 215,
  686. 220,
  687. 221
  688. ];
  689. }
  690. } catch (error) {
  691. }
  692. exports2.inspectOpts = Object.keys(process.env).filter((key) => {
  693. return /^debug_/i.test(key);
  694. }).reduce((obj, key) => {
  695. const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
  696. return k.toUpperCase();
  697. });
  698. let val = process.env[key];
  699. if (/^(yes|on|true|enabled)$/i.test(val)) {
  700. val = true;
  701. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  702. val = false;
  703. } else if (val === "null") {
  704. val = null;
  705. } else {
  706. val = Number(val);
  707. }
  708. obj[prop] = val;
  709. return obj;
  710. }, {});
  711. function useColors() {
  712. return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
  713. }
  714. function formatArgs(args) {
  715. const { namespace: name, useColors: useColors2 } = this;
  716. if (useColors2) {
  717. const c = this.color;
  718. const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
  719. const prefix = ` ${colorCode};1m${name} \x1B[0m`;
  720. args[0] = prefix + args[0].split("\n").join("\n" + prefix);
  721. args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
  722. } else {
  723. args[0] = getDate() + name + " " + args[0];
  724. }
  725. }
  726. function getDate() {
  727. if (exports2.inspectOpts.hideDate) {
  728. return "";
  729. }
  730. return (/* @__PURE__ */ new Date()).toISOString() + " ";
  731. }
  732. function log(...args) {
  733. return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
  734. }
  735. function save(namespaces) {
  736. if (namespaces) {
  737. process.env.DEBUG = namespaces;
  738. } else {
  739. delete process.env.DEBUG;
  740. }
  741. }
  742. function load() {
  743. return process.env.DEBUG;
  744. }
  745. function init(debug3) {
  746. debug3.inspectOpts = {};
  747. const keys = Object.keys(exports2.inspectOpts);
  748. for (let i = 0; i < keys.length; i++) {
  749. debug3.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
  750. }
  751. }
  752. module2.exports = require_common()(exports2);
  753. var { formatters } = module2.exports;
  754. formatters.o = function(v) {
  755. this.inspectOpts.colors = this.useColors;
  756. return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
  757. };
  758. formatters.O = function(v) {
  759. this.inspectOpts.colors = this.useColors;
  760. return util.inspect(v, this.inspectOpts);
  761. };
  762. }
  763. });
  764. // node_modules/debug/src/index.js
  765. var require_src = __commonJS({
  766. "node_modules/debug/src/index.js"(exports2, module2) {
  767. if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
  768. module2.exports = require_browser();
  769. } else {
  770. module2.exports = require_node();
  771. }
  772. }
  773. });
  774. // node_modules/depd/index.js
  775. var require_depd = __commonJS({
  776. "node_modules/depd/index.js"(exports2, module2) {
  777. var relative = require("path").relative;
  778. module2.exports = depd;
  779. var basePath = process.cwd();
  780. function containsNamespace(str, namespace) {
  781. var vals = str.split(/[ ,]+/);
  782. var ns = String(namespace).toLowerCase();
  783. for (var i = 0; i < vals.length; i++) {
  784. var val = vals[i];
  785. if (val && (val === "*" || val.toLowerCase() === ns)) {
  786. return true;
  787. }
  788. }
  789. return false;
  790. }
  791. function convertDataDescriptorToAccessor(obj, prop, message) {
  792. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  793. var value = descriptor.value;
  794. descriptor.get = function getter() {
  795. return value;
  796. };
  797. if (descriptor.writable) {
  798. descriptor.set = function setter(val) {
  799. return value = val;
  800. };
  801. }
  802. delete descriptor.value;
  803. delete descriptor.writable;
  804. Object.defineProperty(obj, prop, descriptor);
  805. return descriptor;
  806. }
  807. function createArgumentsString(arity) {
  808. var str = "";
  809. for (var i = 0; i < arity; i++) {
  810. str += ", arg" + i;
  811. }
  812. return str.substr(2);
  813. }
  814. function createStackString(stack) {
  815. var str = this.name + ": " + this.namespace;
  816. if (this.message) {
  817. str += " deprecated " + this.message;
  818. }
  819. for (var i = 0; i < stack.length; i++) {
  820. str += "\n at " + stack[i].toString();
  821. }
  822. return str;
  823. }
  824. function depd(namespace) {
  825. if (!namespace) {
  826. throw new TypeError("argument namespace is required");
  827. }
  828. var stack = getStack();
  829. var site = callSiteLocation(stack[1]);
  830. var file = site[0];
  831. function deprecate(message) {
  832. log.call(deprecate, message);
  833. }
  834. deprecate._file = file;
  835. deprecate._ignored = isignored(namespace);
  836. deprecate._namespace = namespace;
  837. deprecate._traced = istraced(namespace);
  838. deprecate._warned = /* @__PURE__ */ Object.create(null);
  839. deprecate.function = wrapfunction;
  840. deprecate.property = wrapproperty;
  841. return deprecate;
  842. }
  843. function eehaslisteners(emitter, type) {
  844. var count = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
  845. return count > 0;
  846. }
  847. function isignored(namespace) {
  848. if (process.noDeprecation) {
  849. return true;
  850. }
  851. var str = process.env.NO_DEPRECATION || "";
  852. return containsNamespace(str, namespace);
  853. }
  854. function istraced(namespace) {
  855. if (process.traceDeprecation) {
  856. return true;
  857. }
  858. var str = process.env.TRACE_DEPRECATION || "";
  859. return containsNamespace(str, namespace);
  860. }
  861. function log(message, site) {
  862. var haslisteners = eehaslisteners(process, "deprecation");
  863. if (!haslisteners && this._ignored) {
  864. return;
  865. }
  866. var caller;
  867. var callFile;
  868. var callSite;
  869. var depSite;
  870. var i = 0;
  871. var seen = false;
  872. var stack = getStack();
  873. var file = this._file;
  874. if (site) {
  875. depSite = site;
  876. callSite = callSiteLocation(stack[1]);
  877. callSite.name = depSite.name;
  878. file = callSite[0];
  879. } else {
  880. i = 2;
  881. depSite = callSiteLocation(stack[i]);
  882. callSite = depSite;
  883. }
  884. for (; i < stack.length; i++) {
  885. caller = callSiteLocation(stack[i]);
  886. callFile = caller[0];
  887. if (callFile === file) {
  888. seen = true;
  889. } else if (callFile === this._file) {
  890. file = this._file;
  891. } else if (seen) {
  892. break;
  893. }
  894. }
  895. var key = caller ? depSite.join(":") + "__" + caller.join(":") : void 0;
  896. if (key !== void 0 && key in this._warned) {
  897. return;
  898. }
  899. this._warned[key] = true;
  900. var msg = message;
  901. if (!msg) {
  902. msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite);
  903. }
  904. if (haslisteners) {
  905. var err = DeprecationError(this._namespace, msg, stack.slice(i));
  906. process.emit("deprecation", err);
  907. return;
  908. }
  909. var format2 = process.stderr.isTTY ? formatColor : formatPlain;
  910. var output = format2.call(this, msg, caller, stack.slice(i));
  911. process.stderr.write(output + "\n", "utf8");
  912. }
  913. function callSiteLocation(callSite) {
  914. var file = callSite.getFileName() || "<anonymous>";
  915. var line = callSite.getLineNumber();
  916. var colm = callSite.getColumnNumber();
  917. if (callSite.isEval()) {
  918. file = callSite.getEvalOrigin() + ", " + file;
  919. }
  920. var site = [file, line, colm];
  921. site.callSite = callSite;
  922. site.name = callSite.getFunctionName();
  923. return site;
  924. }
  925. function defaultMessage(site) {
  926. var callSite = site.callSite;
  927. var funcName = site.name;
  928. if (!funcName) {
  929. funcName = "<anonymous@" + formatLocation(site) + ">";
  930. }
  931. var context = callSite.getThis();
  932. var typeName = context && callSite.getTypeName();
  933. if (typeName === "Object") {
  934. typeName = void 0;
  935. }
  936. if (typeName === "Function") {
  937. typeName = context.name || typeName;
  938. }
  939. return typeName && callSite.getMethodName() ? typeName + "." + funcName : funcName;
  940. }
  941. function formatPlain(msg, caller, stack) {
  942. var timestamp = (/* @__PURE__ */ new Date()).toUTCString();
  943. var formatted = timestamp + " " + this._namespace + " deprecated " + msg;
  944. if (this._traced) {
  945. for (var i = 0; i < stack.length; i++) {
  946. formatted += "\n at " + stack[i].toString();
  947. }
  948. return formatted;
  949. }
  950. if (caller) {
  951. formatted += " at " + formatLocation(caller);
  952. }
  953. return formatted;
  954. }
  955. function formatColor(msg, caller, stack) {
  956. var formatted = "\x1B[36;1m" + this._namespace + "\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m" + msg + "\x1B[39m";
  957. if (this._traced) {
  958. for (var i = 0; i < stack.length; i++) {
  959. formatted += "\n \x1B[36mat " + stack[i].toString() + "\x1B[39m";
  960. }
  961. return formatted;
  962. }
  963. if (caller) {
  964. formatted += " \x1B[36m" + formatLocation(caller) + "\x1B[39m";
  965. }
  966. return formatted;
  967. }
  968. function formatLocation(callSite) {
  969. return relative(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2];
  970. }
  971. function getStack() {
  972. var limit = Error.stackTraceLimit;
  973. var obj = {};
  974. var prep = Error.prepareStackTrace;
  975. Error.prepareStackTrace = prepareObjectStackTrace;
  976. Error.stackTraceLimit = Math.max(10, limit);
  977. Error.captureStackTrace(obj);
  978. var stack = obj.stack.slice(1);
  979. Error.prepareStackTrace = prep;
  980. Error.stackTraceLimit = limit;
  981. return stack;
  982. }
  983. function prepareObjectStackTrace(obj, stack) {
  984. return stack;
  985. }
  986. function wrapfunction(fn, message) {
  987. if (typeof fn !== "function") {
  988. throw new TypeError("argument fn must be a function");
  989. }
  990. var args = createArgumentsString(fn.length);
  991. var stack = getStack();
  992. var site = callSiteLocation(stack[1]);
  993. site.name = fn.name;
  994. var deprecatedfn = new Function(
  995. "fn",
  996. "log",
  997. "deprecate",
  998. "message",
  999. "site",
  1000. '"use strict"\nreturn function (' + args + ") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}"
  1001. )(fn, log, this, message, site);
  1002. return deprecatedfn;
  1003. }
  1004. function wrapproperty(obj, prop, message) {
  1005. if (!obj || typeof obj !== "object" && typeof obj !== "function") {
  1006. throw new TypeError("argument obj must be object");
  1007. }
  1008. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  1009. if (!descriptor) {
  1010. throw new TypeError("must call property on owner object");
  1011. }
  1012. if (!descriptor.configurable) {
  1013. throw new TypeError("property must be configurable");
  1014. }
  1015. var deprecate = this;
  1016. var stack = getStack();
  1017. var site = callSiteLocation(stack[1]);
  1018. site.name = prop;
  1019. if ("value" in descriptor) {
  1020. descriptor = convertDataDescriptorToAccessor(obj, prop, message);
  1021. }
  1022. var get = descriptor.get;
  1023. var set = descriptor.set;
  1024. if (typeof get === "function") {
  1025. descriptor.get = function getter() {
  1026. log.call(deprecate, message, site);
  1027. return get.apply(this, arguments);
  1028. };
  1029. }
  1030. if (typeof set === "function") {
  1031. descriptor.set = function setter() {
  1032. log.call(deprecate, message, site);
  1033. return set.apply(this, arguments);
  1034. };
  1035. }
  1036. Object.defineProperty(obj, prop, descriptor);
  1037. }
  1038. function DeprecationError(namespace, message, stack) {
  1039. var error = new Error();
  1040. var stackString;
  1041. Object.defineProperty(error, "constructor", {
  1042. value: DeprecationError
  1043. });
  1044. Object.defineProperty(error, "message", {
  1045. configurable: true,
  1046. enumerable: false,
  1047. value: message,
  1048. writable: true
  1049. });
  1050. Object.defineProperty(error, "name", {
  1051. enumerable: false,
  1052. configurable: true,
  1053. value: "DeprecationError",
  1054. writable: true
  1055. });
  1056. Object.defineProperty(error, "namespace", {
  1057. configurable: true,
  1058. enumerable: false,
  1059. value: namespace,
  1060. writable: true
  1061. });
  1062. Object.defineProperty(error, "stack", {
  1063. configurable: true,
  1064. enumerable: false,
  1065. get: function() {
  1066. if (stackString !== void 0) {
  1067. return stackString;
  1068. }
  1069. return stackString = createStackString.call(this, stack);
  1070. },
  1071. set: function setter(val) {
  1072. stackString = val;
  1073. }
  1074. });
  1075. return error;
  1076. }
  1077. }
  1078. });
  1079. // node_modules/setprototypeof/index.js
  1080. var require_setprototypeof = __commonJS({
  1081. "node_modules/setprototypeof/index.js"(exports2, module2) {
  1082. "use strict";
  1083. module2.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);
  1084. function setProtoOf(obj, proto) {
  1085. obj.__proto__ = proto;
  1086. return obj;
  1087. }
  1088. function mixinProperties(obj, proto) {
  1089. for (var prop in proto) {
  1090. if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
  1091. obj[prop] = proto[prop];
  1092. }
  1093. }
  1094. return obj;
  1095. }
  1096. }
  1097. });
  1098. // node_modules/statuses/codes.json
  1099. var require_codes = __commonJS({
  1100. "node_modules/statuses/codes.json"(exports2, module2) {
  1101. module2.exports = {
  1102. "100": "Continue",
  1103. "101": "Switching Protocols",
  1104. "102": "Processing",
  1105. "103": "Early Hints",
  1106. "200": "OK",
  1107. "201": "Created",
  1108. "202": "Accepted",
  1109. "203": "Non-Authoritative Information",
  1110. "204": "No Content",
  1111. "205": "Reset Content",
  1112. "206": "Partial Content",
  1113. "207": "Multi-Status",
  1114. "208": "Already Reported",
  1115. "226": "IM Used",
  1116. "300": "Multiple Choices",
  1117. "301": "Moved Permanently",
  1118. "302": "Found",
  1119. "303": "See Other",
  1120. "304": "Not Modified",
  1121. "305": "Use Proxy",
  1122. "307": "Temporary Redirect",
  1123. "308": "Permanent Redirect",
  1124. "400": "Bad Request",
  1125. "401": "Unauthorized",
  1126. "402": "Payment Required",
  1127. "403": "Forbidden",
  1128. "404": "Not Found",
  1129. "405": "Method Not Allowed",
  1130. "406": "Not Acceptable",
  1131. "407": "Proxy Authentication Required",
  1132. "408": "Request Timeout",
  1133. "409": "Conflict",
  1134. "410": "Gone",
  1135. "411": "Length Required",
  1136. "412": "Precondition Failed",
  1137. "413": "Payload Too Large",
  1138. "414": "URI Too Long",
  1139. "415": "Unsupported Media Type",
  1140. "416": "Range Not Satisfiable",
  1141. "417": "Expectation Failed",
  1142. "418": "I'm a Teapot",
  1143. "421": "Misdirected Request",
  1144. "422": "Unprocessable Entity",
  1145. "423": "Locked",
  1146. "424": "Failed Dependency",
  1147. "425": "Too Early",
  1148. "426": "Upgrade Required",
  1149. "428": "Precondition Required",
  1150. "429": "Too Many Requests",
  1151. "431": "Request Header Fields Too Large",
  1152. "451": "Unavailable For Legal Reasons",
  1153. "500": "Internal Server Error",
  1154. "501": "Not Implemented",
  1155. "502": "Bad Gateway",
  1156. "503": "Service Unavailable",
  1157. "504": "Gateway Timeout",
  1158. "505": "HTTP Version Not Supported",
  1159. "506": "Variant Also Negotiates",
  1160. "507": "Insufficient Storage",
  1161. "508": "Loop Detected",
  1162. "509": "Bandwidth Limit Exceeded",
  1163. "510": "Not Extended",
  1164. "511": "Network Authentication Required"
  1165. };
  1166. }
  1167. });
  1168. // node_modules/statuses/index.js
  1169. var require_statuses = __commonJS({
  1170. "node_modules/statuses/index.js"(exports2, module2) {
  1171. "use strict";
  1172. var codes = require_codes();
  1173. module2.exports = status;
  1174. status.message = codes;
  1175. status.code = createMessageToStatusCodeMap(codes);
  1176. status.codes = createStatusCodeList(codes);
  1177. status.redirect = {
  1178. 300: true,
  1179. 301: true,
  1180. 302: true,
  1181. 303: true,
  1182. 305: true,
  1183. 307: true,
  1184. 308: true
  1185. };
  1186. status.empty = {
  1187. 204: true,
  1188. 205: true,
  1189. 304: true
  1190. };
  1191. status.retry = {
  1192. 502: true,
  1193. 503: true,
  1194. 504: true
  1195. };
  1196. function createMessageToStatusCodeMap(codes2) {
  1197. var map = {};
  1198. Object.keys(codes2).forEach(function forEachCode(code) {
  1199. var message = codes2[code];
  1200. var status2 = Number(code);
  1201. map[message.toLowerCase()] = status2;
  1202. });
  1203. return map;
  1204. }
  1205. function createStatusCodeList(codes2) {
  1206. return Object.keys(codes2).map(function mapCode(code) {
  1207. return Number(code);
  1208. });
  1209. }
  1210. function getStatusCode(message) {
  1211. var msg = message.toLowerCase();
  1212. if (!Object.prototype.hasOwnProperty.call(status.code, msg)) {
  1213. throw new Error('invalid status message: "' + message + '"');
  1214. }
  1215. return status.code[msg];
  1216. }
  1217. function getStatusMessage2(code) {
  1218. if (!Object.prototype.hasOwnProperty.call(status.message, code)) {
  1219. throw new Error("invalid status code: " + code);
  1220. }
  1221. return status.message[code];
  1222. }
  1223. function status(code) {
  1224. if (typeof code === "number") {
  1225. return getStatusMessage2(code);
  1226. }
  1227. if (typeof code !== "string") {
  1228. throw new TypeError("code must be a number or string");
  1229. }
  1230. var n = parseInt(code, 10);
  1231. if (!isNaN(n)) {
  1232. return getStatusMessage2(n);
  1233. }
  1234. return getStatusCode(code);
  1235. }
  1236. }
  1237. });
  1238. // node_modules/inherits/inherits_browser.js
  1239. var require_inherits_browser = __commonJS({
  1240. "node_modules/inherits/inherits_browser.js"(exports2, module2) {
  1241. if (typeof Object.create === "function") {
  1242. module2.exports = function inherits(ctor, superCtor) {
  1243. if (superCtor) {
  1244. ctor.super_ = superCtor;
  1245. ctor.prototype = Object.create(superCtor.prototype, {
  1246. constructor: {
  1247. value: ctor,
  1248. enumerable: false,
  1249. writable: true,
  1250. configurable: true
  1251. }
  1252. });
  1253. }
  1254. };
  1255. } else {
  1256. module2.exports = function inherits(ctor, superCtor) {
  1257. if (superCtor) {
  1258. ctor.super_ = superCtor;
  1259. var TempCtor = function() {
  1260. };
  1261. TempCtor.prototype = superCtor.prototype;
  1262. ctor.prototype = new TempCtor();
  1263. ctor.prototype.constructor = ctor;
  1264. }
  1265. };
  1266. }
  1267. }
  1268. });
  1269. // node_modules/inherits/inherits.js
  1270. var require_inherits = __commonJS({
  1271. "node_modules/inherits/inherits.js"(exports2, module2) {
  1272. try {
  1273. util = require("util");
  1274. if (typeof util.inherits !== "function") throw "";
  1275. module2.exports = util.inherits;
  1276. } catch (e) {
  1277. module2.exports = require_inherits_browser();
  1278. }
  1279. var util;
  1280. }
  1281. });
  1282. // node_modules/toidentifier/index.js
  1283. var require_toidentifier = __commonJS({
  1284. "node_modules/toidentifier/index.js"(exports2, module2) {
  1285. "use strict";
  1286. module2.exports = toIdentifier;
  1287. function toIdentifier(str) {
  1288. return str.split(" ").map(function(token) {
  1289. return token.slice(0, 1).toUpperCase() + token.slice(1);
  1290. }).join("").replace(/[^ _0-9a-z]/gi, "");
  1291. }
  1292. }
  1293. });
  1294. // node_modules/http-errors/index.js
  1295. var require_http_errors = __commonJS({
  1296. "node_modules/http-errors/index.js"(exports2, module2) {
  1297. "use strict";
  1298. var deprecate = require_depd()("http-errors");
  1299. var setPrototypeOf = require_setprototypeof();
  1300. var statuses = require_statuses();
  1301. var inherits = require_inherits();
  1302. var toIdentifier = require_toidentifier();
  1303. module2.exports = createError2;
  1304. module2.exports.HttpError = createHttpErrorConstructor();
  1305. module2.exports.isHttpError = createIsHttpErrorFunction(module2.exports.HttpError);
  1306. populateConstructorExports(module2.exports, statuses.codes, module2.exports.HttpError);
  1307. function codeClass(status) {
  1308. return Number(String(status).charAt(0) + "00");
  1309. }
  1310. function createError2() {
  1311. var err;
  1312. var msg;
  1313. var status = 500;
  1314. var props = {};
  1315. for (var i = 0; i < arguments.length; i++) {
  1316. var arg = arguments[i];
  1317. var type = typeof arg;
  1318. if (type === "object" && arg instanceof Error) {
  1319. err = arg;
  1320. status = err.status || err.statusCode || status;
  1321. } else if (type === "number" && i === 0) {
  1322. status = arg;
  1323. } else if (type === "string") {
  1324. msg = arg;
  1325. } else if (type === "object") {
  1326. props = arg;
  1327. } else {
  1328. throw new TypeError("argument #" + (i + 1) + " unsupported type " + type);
  1329. }
  1330. }
  1331. if (typeof status === "number" && (status < 400 || status >= 600)) {
  1332. deprecate("non-error status code; use only 4xx or 5xx status codes");
  1333. }
  1334. if (typeof status !== "number" || !statuses.message[status] && (status < 400 || status >= 600)) {
  1335. status = 500;
  1336. }
  1337. var HttpError = createError2[status] || createError2[codeClass(status)];
  1338. if (!err) {
  1339. err = HttpError ? new HttpError(msg) : new Error(msg || statuses.message[status]);
  1340. Error.captureStackTrace(err, createError2);
  1341. }
  1342. if (!HttpError || !(err instanceof HttpError) || err.status !== status) {
  1343. err.expose = status < 500;
  1344. err.status = err.statusCode = status;
  1345. }
  1346. for (var key in props) {
  1347. if (key !== "status" && key !== "statusCode") {
  1348. err[key] = props[key];
  1349. }
  1350. }
  1351. return err;
  1352. }
  1353. function createHttpErrorConstructor() {
  1354. function HttpError() {
  1355. throw new TypeError("cannot construct abstract class");
  1356. }
  1357. inherits(HttpError, Error);
  1358. return HttpError;
  1359. }
  1360. function createClientErrorConstructor(HttpError, name, code) {
  1361. var className = toClassName(name);
  1362. function ClientError(message) {
  1363. var msg = message != null ? message : statuses.message[code];
  1364. var err = new Error(msg);
  1365. Error.captureStackTrace(err, ClientError);
  1366. setPrototypeOf(err, ClientError.prototype);
  1367. Object.defineProperty(err, "message", {
  1368. enumerable: true,
  1369. configurable: true,
  1370. value: msg,
  1371. writable: true
  1372. });
  1373. Object.defineProperty(err, "name", {
  1374. enumerable: false,
  1375. configurable: true,
  1376. value: className,
  1377. writable: true
  1378. });
  1379. return err;
  1380. }
  1381. inherits(ClientError, HttpError);
  1382. nameFunc(ClientError, className);
  1383. ClientError.prototype.status = code;
  1384. ClientError.prototype.statusCode = code;
  1385. ClientError.prototype.expose = true;
  1386. return ClientError;
  1387. }
  1388. function createIsHttpErrorFunction(HttpError) {
  1389. return function isHttpError(val) {
  1390. if (!val || typeof val !== "object") {
  1391. return false;
  1392. }
  1393. if (val instanceof HttpError) {
  1394. return true;
  1395. }
  1396. return val instanceof Error && typeof val.expose === "boolean" && typeof val.statusCode === "number" && val.status === val.statusCode;
  1397. };
  1398. }
  1399. function createServerErrorConstructor(HttpError, name, code) {
  1400. var className = toClassName(name);
  1401. function ServerError(message) {
  1402. var msg = message != null ? message : statuses.message[code];
  1403. var err = new Error(msg);
  1404. Error.captureStackTrace(err, ServerError);
  1405. setPrototypeOf(err, ServerError.prototype);
  1406. Object.defineProperty(err, "message", {
  1407. enumerable: true,
  1408. configurable: true,
  1409. value: msg,
  1410. writable: true
  1411. });
  1412. Object.defineProperty(err, "name", {
  1413. enumerable: false,
  1414. configurable: true,
  1415. value: className,
  1416. writable: true
  1417. });
  1418. return err;
  1419. }
  1420. inherits(ServerError, HttpError);
  1421. nameFunc(ServerError, className);
  1422. ServerError.prototype.status = code;
  1423. ServerError.prototype.statusCode = code;
  1424. ServerError.prototype.expose = false;
  1425. return ServerError;
  1426. }
  1427. function nameFunc(func, name) {
  1428. var desc = Object.getOwnPropertyDescriptor(func, "name");
  1429. if (desc && desc.configurable) {
  1430. desc.value = name;
  1431. Object.defineProperty(func, "name", desc);
  1432. }
  1433. }
  1434. function populateConstructorExports(exports3, codes, HttpError) {
  1435. codes.forEach(function forEachCode(code) {
  1436. var CodeError;
  1437. var name = toIdentifier(statuses.message[code]);
  1438. switch (codeClass(code)) {
  1439. case 400:
  1440. CodeError = createClientErrorConstructor(HttpError, name, code);
  1441. break;
  1442. case 500:
  1443. CodeError = createServerErrorConstructor(HttpError, name, code);
  1444. break;
  1445. }
  1446. if (CodeError) {
  1447. exports3[code] = CodeError;
  1448. exports3[name] = CodeError;
  1449. }
  1450. });
  1451. }
  1452. function toClassName(name) {
  1453. return name.substr(-5) !== "Error" ? name + "Error" : name;
  1454. }
  1455. }
  1456. });
  1457. // node_modules/path-to-regexp/dist/index.js
  1458. var require_dist = __commonJS({
  1459. "node_modules/path-to-regexp/dist/index.js"(exports2) {
  1460. "use strict";
  1461. Object.defineProperty(exports2, "__esModule", { value: true });
  1462. exports2.TokenData = void 0;
  1463. exports2.parse = parse;
  1464. exports2.compile = compile;
  1465. exports2.match = match;
  1466. exports2.pathToRegexp = pathToRegexp2;
  1467. exports2.stringify = stringify;
  1468. var DEFAULT_DELIMITER = "/";
  1469. var NOOP_VALUE = (value) => value;
  1470. var ID_START = /^[$_\p{ID_Start}]$/u;
  1471. var ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u;
  1472. var DEBUG_URL = "https://git.new/pathToRegexpError";
  1473. var SIMPLE_TOKENS = {
  1474. // Groups.
  1475. "{": "{",
  1476. "}": "}",
  1477. // Reserved.
  1478. "(": "(",
  1479. ")": ")",
  1480. "[": "[",
  1481. "]": "]",
  1482. "+": "+",
  1483. "?": "?",
  1484. "!": "!"
  1485. };
  1486. function escapeText(str) {
  1487. return str.replace(/[{}()\[\]+?!:*]/g, "\\$&");
  1488. }
  1489. function escape(str) {
  1490. return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&");
  1491. }
  1492. function* lexer(str) {
  1493. const chars = [...str];
  1494. let i = 0;
  1495. function name() {
  1496. let value = "";
  1497. if (ID_START.test(chars[++i])) {
  1498. value += chars[i];
  1499. while (ID_CONTINUE.test(chars[++i])) {
  1500. value += chars[i];
  1501. }
  1502. } else if (chars[i] === '"') {
  1503. let pos = i;
  1504. while (i < chars.length) {
  1505. if (chars[++i] === '"') {
  1506. i++;
  1507. pos = 0;
  1508. break;
  1509. }
  1510. if (chars[i] === "\\") {
  1511. value += chars[++i];
  1512. } else {
  1513. value += chars[i];
  1514. }
  1515. }
  1516. if (pos) {
  1517. throw new TypeError(`Unterminated quote at ${pos}: ${DEBUG_URL}`);
  1518. }
  1519. }
  1520. if (!value) {
  1521. throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);
  1522. }
  1523. return value;
  1524. }
  1525. while (i < chars.length) {
  1526. const value = chars[i];
  1527. const type = SIMPLE_TOKENS[value];
  1528. if (type) {
  1529. yield { type, index: i++, value };
  1530. } else if (value === "\\") {
  1531. yield { type: "ESCAPED", index: i++, value: chars[i++] };
  1532. } else if (value === ":") {
  1533. const value2 = name();
  1534. yield { type: "PARAM", index: i, value: value2 };
  1535. } else if (value === "*") {
  1536. const value2 = name();
  1537. yield { type: "WILDCARD", index: i, value: value2 };
  1538. } else {
  1539. yield { type: "CHAR", index: i, value: chars[i++] };
  1540. }
  1541. }
  1542. return { type: "END", index: i, value: "" };
  1543. }
  1544. var Iter = class {
  1545. constructor(tokens) {
  1546. this.tokens = tokens;
  1547. }
  1548. peek() {
  1549. if (!this._peek) {
  1550. const next = this.tokens.next();
  1551. this._peek = next.value;
  1552. }
  1553. return this._peek;
  1554. }
  1555. tryConsume(type) {
  1556. const token = this.peek();
  1557. if (token.type !== type)
  1558. return;
  1559. this._peek = void 0;
  1560. return token.value;
  1561. }
  1562. consume(type) {
  1563. const value = this.tryConsume(type);
  1564. if (value !== void 0)
  1565. return value;
  1566. const { type: nextType, index } = this.peek();
  1567. throw new TypeError(`Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL}`);
  1568. }
  1569. text() {
  1570. let result = "";
  1571. let value;
  1572. while (value = this.tryConsume("CHAR") || this.tryConsume("ESCAPED")) {
  1573. result += value;
  1574. }
  1575. return result;
  1576. }
  1577. };
  1578. var TokenData = class {
  1579. constructor(tokens) {
  1580. this.tokens = tokens;
  1581. }
  1582. };
  1583. exports2.TokenData = TokenData;
  1584. function parse(str, options = {}) {
  1585. const { encodePath = NOOP_VALUE } = options;
  1586. const it = new Iter(lexer(str));
  1587. function consume(endType) {
  1588. const tokens2 = [];
  1589. while (true) {
  1590. const path = it.text();
  1591. if (path)
  1592. tokens2.push({ type: "text", value: encodePath(path) });
  1593. const param = it.tryConsume("PARAM");
  1594. if (param) {
  1595. tokens2.push({
  1596. type: "param",
  1597. name: param
  1598. });
  1599. continue;
  1600. }
  1601. const wildcard = it.tryConsume("WILDCARD");
  1602. if (wildcard) {
  1603. tokens2.push({
  1604. type: "wildcard",
  1605. name: wildcard
  1606. });
  1607. continue;
  1608. }
  1609. const open = it.tryConsume("{");
  1610. if (open) {
  1611. tokens2.push({
  1612. type: "group",
  1613. tokens: consume("}")
  1614. });
  1615. continue;
  1616. }
  1617. it.consume(endType);
  1618. return tokens2;
  1619. }
  1620. }
  1621. const tokens = consume("END");
  1622. return new TokenData(tokens);
  1623. }
  1624. function compile(path, options = {}) {
  1625. const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
  1626. const data = path instanceof TokenData ? path : parse(path, options);
  1627. const fn = tokensToFunction(data.tokens, delimiter, encode);
  1628. return function path2(data2 = {}) {
  1629. const [path3, ...missing] = fn(data2);
  1630. if (missing.length) {
  1631. throw new TypeError(`Missing parameters: ${missing.join(", ")}`);
  1632. }
  1633. return path3;
  1634. };
  1635. }
  1636. function tokensToFunction(tokens, delimiter, encode) {
  1637. const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode));
  1638. return (data) => {
  1639. const result = [""];
  1640. for (const encoder of encoders) {
  1641. const [value, ...extras] = encoder(data);
  1642. result[0] += value;
  1643. result.push(...extras);
  1644. }
  1645. return result;
  1646. };
  1647. }
  1648. function tokenToFunction(token, delimiter, encode) {
  1649. if (token.type === "text")
  1650. return () => [token.value];
  1651. if (token.type === "group") {
  1652. const fn = tokensToFunction(token.tokens, delimiter, encode);
  1653. return (data) => {
  1654. const [value, ...missing] = fn(data);
  1655. if (!missing.length)
  1656. return [value];
  1657. return [""];
  1658. };
  1659. }
  1660. const encodeValue = encode || NOOP_VALUE;
  1661. if (token.type === "wildcard" && encode !== false) {
  1662. return (data) => {
  1663. const value = data[token.name];
  1664. if (value == null)
  1665. return ["", token.name];
  1666. if (!Array.isArray(value) || value.length === 0) {
  1667. throw new TypeError(`Expected "${token.name}" to be a non-empty array`);
  1668. }
  1669. return [
  1670. value.map((value2, index) => {
  1671. if (typeof value2 !== "string") {
  1672. throw new TypeError(`Expected "${token.name}/${index}" to be a string`);
  1673. }
  1674. return encodeValue(value2);
  1675. }).join(delimiter)
  1676. ];
  1677. };
  1678. }
  1679. return (data) => {
  1680. const value = data[token.name];
  1681. if (value == null)
  1682. return ["", token.name];
  1683. if (typeof value !== "string") {
  1684. throw new TypeError(`Expected "${token.name}" to be a string`);
  1685. }
  1686. return [encodeValue(value)];
  1687. };
  1688. }
  1689. function match(path, options = {}) {
  1690. const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
  1691. const { regexp, keys } = pathToRegexp2(path, options);
  1692. const decoders = keys.map((key) => {
  1693. if (decode === false)
  1694. return NOOP_VALUE;
  1695. if (key.type === "param")
  1696. return decode;
  1697. return (value) => value.split(delimiter).map(decode);
  1698. });
  1699. return function match2(input) {
  1700. const m = regexp.exec(input);
  1701. if (!m)
  1702. return false;
  1703. const path2 = m[0];
  1704. const params = /* @__PURE__ */ Object.create(null);
  1705. for (let i = 1; i < m.length; i++) {
  1706. if (m[i] === void 0)
  1707. continue;
  1708. const key = keys[i - 1];
  1709. const decoder = decoders[i - 1];
  1710. params[key.name] = decoder(m[i]);
  1711. }
  1712. return { path: path2, params };
  1713. };
  1714. }
  1715. function pathToRegexp2(path, options = {}) {
  1716. const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true } = options;
  1717. const keys = [];
  1718. const sources = [];
  1719. const flags = sensitive ? "" : "i";
  1720. const paths = Array.isArray(path) ? path : [path];
  1721. const items = paths.map((path2) => path2 instanceof TokenData ? path2 : parse(path2, options));
  1722. for (const { tokens } of items) {
  1723. for (const seq of flatten(tokens, 0, [])) {
  1724. const regexp2 = sequenceToRegExp(seq, delimiter, keys);
  1725. sources.push(regexp2);
  1726. }
  1727. }
  1728. let pattern = `^(?:${sources.join("|")})`;
  1729. if (trailing)
  1730. pattern += `(?:${escape(delimiter)}$)?`;
  1731. pattern += end ? "$" : `(?=${escape(delimiter)}|$)`;
  1732. const regexp = new RegExp(pattern, flags);
  1733. return { regexp, keys };
  1734. }
  1735. function* flatten(tokens, index, init) {
  1736. if (index === tokens.length) {
  1737. return yield init;
  1738. }
  1739. const token = tokens[index];
  1740. if (token.type === "group") {
  1741. const fork = init.slice();
  1742. for (const seq of flatten(token.tokens, 0, fork)) {
  1743. yield* flatten(tokens, index + 1, seq);
  1744. }
  1745. } else {
  1746. init.push(token);
  1747. }
  1748. yield* flatten(tokens, index + 1, init);
  1749. }
  1750. function sequenceToRegExp(tokens, delimiter, keys) {
  1751. let result = "";
  1752. let backtrack = "";
  1753. let isSafeSegmentParam = true;
  1754. for (let i = 0; i < tokens.length; i++) {
  1755. const token = tokens[i];
  1756. if (token.type === "text") {
  1757. result += escape(token.value);
  1758. backtrack += token.value;
  1759. isSafeSegmentParam || (isSafeSegmentParam = token.value.includes(delimiter));
  1760. continue;
  1761. }
  1762. if (token.type === "param" || token.type === "wildcard") {
  1763. if (!isSafeSegmentParam && !backtrack) {
  1764. throw new TypeError(`Missing text after "${token.name}": ${DEBUG_URL}`);
  1765. }
  1766. if (token.type === "param") {
  1767. result += `(${negate(delimiter, isSafeSegmentParam ? "" : backtrack)}+)`;
  1768. } else {
  1769. result += `([\\s\\S]+)`;
  1770. }
  1771. keys.push(token);
  1772. backtrack = "";
  1773. isSafeSegmentParam = false;
  1774. continue;
  1775. }
  1776. }
  1777. return result;
  1778. }
  1779. function negate(delimiter, backtrack) {
  1780. if (backtrack.length < 2) {
  1781. if (delimiter.length < 2)
  1782. return `[^${escape(delimiter + backtrack)}]`;
  1783. return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`;
  1784. }
  1785. if (delimiter.length < 2) {
  1786. return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`;
  1787. }
  1788. return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\s\\S])`;
  1789. }
  1790. function stringify(data) {
  1791. return data.tokens.map(function stringifyToken(token, index, tokens) {
  1792. if (token.type === "text")
  1793. return escapeText(token.value);
  1794. if (token.type === "group") {
  1795. return `{${token.tokens.map(stringifyToken).join("")}}`;
  1796. }
  1797. const isSafe = isNameSafe(token.name) && isNextNameSafe(tokens[index + 1]);
  1798. const key = isSafe ? token.name : JSON.stringify(token.name);
  1799. if (token.type === "param")
  1800. return `:${key}`;
  1801. if (token.type === "wildcard")
  1802. return `*${key}`;
  1803. throw new TypeError(`Unexpected token: ${token}`);
  1804. }).join("");
  1805. }
  1806. function isNameSafe(name) {
  1807. const [first, ...rest] = name;
  1808. if (!ID_START.test(first))
  1809. return false;
  1810. return rest.every((char) => ID_CONTINUE.test(char));
  1811. }
  1812. function isNextNameSafe(token) {
  1813. if ((token === null || token === void 0 ? void 0 : token.type) !== "text")
  1814. return true;
  1815. return !ID_CONTINUE.test(token.value[0]);
  1816. }
  1817. }
  1818. });
  1819. // src/index.js
  1820. var src_exports = {};
  1821. __export(src_exports, {
  1822. BUFFER_ENCODING_LIST: () => BUFFER_ENCODING_LIST,
  1823. BodyParser: () => BodyParser,
  1824. CookieParser: () => CookieParser,
  1825. DataSender: () => DataSender,
  1826. EXPOSED_ERROR_PROPERTIES: () => EXPOSED_ERROR_PROPERTIES,
  1827. ErrorSender: () => ErrorSender,
  1828. HookInvoker: () => HookInvoker,
  1829. HookName: () => HookName,
  1830. HookRegistry: () => HookRegistry,
  1831. HttpMethod: () => HttpMethod,
  1832. METHODS_WITH_BODY: () => METHODS_WITH_BODY,
  1833. QueryParser: () => QueryParser,
  1834. RequestContext: () => RequestContext,
  1835. RequestParser: () => RequestParser,
  1836. Route: () => Route,
  1837. RouteRegistry: () => RouteRegistry,
  1838. RouterOptions: () => RouterOptions,
  1839. TrieRouter: () => TrieRouter,
  1840. UNPARSABLE_MEDIA_TYPES: () => UNPARSABLE_MEDIA_TYPES,
  1841. createCookieString: () => createCookieString,
  1842. createDebugger: () => createDebugger,
  1843. createError: () => createError,
  1844. createRequestMock: () => createRequestMock,
  1845. createResponseMock: () => createResponseMock,
  1846. fetchRequestBody: () => fetchRequestBody,
  1847. getRequestPathname: () => getRequestPathname,
  1848. isPromise: () => isPromise,
  1849. isReadableStream: () => isReadableStream,
  1850. isResponseSent: () => isResponseSent,
  1851. isWritableStream: () => isWritableStream,
  1852. parseContentType: () => parseContentType,
  1853. parseCookie: () => parseCookie,
  1854. parseJsonBody: () => parseJsonBody,
  1855. toCamelCase: () => toCamelCase
  1856. });
  1857. module.exports = __toCommonJS(src_exports);
  1858. // node_modules/@e22m4u/js-format/src/utils/is-class.js
  1859. function isClass(value) {
  1860. if (!value) return false;
  1861. return typeof value === "function" && /^class\s/.test(Function.prototype.toString.call(value));
  1862. }
  1863. // node_modules/@e22m4u/js-format/src/value-to-string.js
  1864. var BASE_CTOR_NAMES = [
  1865. "String",
  1866. "Number",
  1867. "Boolean",
  1868. "Object",
  1869. "Array",
  1870. "Function",
  1871. "Symbol",
  1872. "Map",
  1873. "Set",
  1874. "Date"
  1875. ];
  1876. function valueToString(input) {
  1877. if (input == null) return String(input);
  1878. if (typeof input === "string") return `"${input}"`;
  1879. if (typeof input === "number" || typeof input === "boolean")
  1880. return String(input);
  1881. if (isClass(input)) return input.name ? input.name : "Class";
  1882. if (input.constructor && input.constructor.name)
  1883. return BASE_CTOR_NAMES.includes(input.constructor.name) ? input.constructor.name : `${input.constructor.name} (instance)`;
  1884. if (typeof input === "object" && input.constructor == null) return "Object";
  1885. return String(input);
  1886. }
  1887. // node_modules/@e22m4u/js-format/src/array-to-list.js
  1888. var SEPARATOR = ", ";
  1889. function arrayToList(input) {
  1890. if (Array.isArray(input) && input.length)
  1891. return input.map(valueToString).join(SEPARATOR);
  1892. return valueToString(input);
  1893. }
  1894. // node_modules/@e22m4u/js-format/src/format.js
  1895. function format(pattern) {
  1896. if (pattern instanceof Date) {
  1897. pattern = pattern.toISOString();
  1898. } else if (typeof pattern !== "string") {
  1899. pattern = String(pattern);
  1900. }
  1901. const re = /(%?)(%([sdjvl]))/g;
  1902. const args = Array.prototype.slice.call(arguments, 1);
  1903. if (args.length) {
  1904. pattern = pattern.replace(re, function(match, escaped, ptn, flag) {
  1905. let arg = args.shift();
  1906. switch (flag) {
  1907. case "s":
  1908. arg = String(arg);
  1909. break;
  1910. case "d":
  1911. arg = Number(arg);
  1912. break;
  1913. case "j":
  1914. arg = JSON.stringify(arg);
  1915. break;
  1916. case "v":
  1917. arg = valueToString(arg);
  1918. break;
  1919. case "l":
  1920. arg = arrayToList(arg);
  1921. break;
  1922. }
  1923. if (!escaped) return arg;
  1924. args.unshift(arg);
  1925. return match;
  1926. });
  1927. }
  1928. if (args.length) pattern += " " + args.join(" ");
  1929. pattern = pattern.replace(/%{2}/g, "%");
  1930. return "" + pattern;
  1931. }
  1932. // node_modules/@e22m4u/js-format/src/errorf.js
  1933. var Errorf = class extends Error {
  1934. /**
  1935. * Constructor.
  1936. *
  1937. * @param {string|undefined} pattern
  1938. * @param {any} args
  1939. */
  1940. constructor(pattern = void 0, ...args) {
  1941. const message = pattern != null ? format(pattern, ...args) : void 0;
  1942. super(message);
  1943. }
  1944. };
  1945. // src/utils/is-promise.js
  1946. function isPromise(value) {
  1947. if (!value) return false;
  1948. if (typeof value !== "object") return false;
  1949. return typeof value.then === "function";
  1950. }
  1951. // src/utils/parse-cookie.js
  1952. function parseCookie(input) {
  1953. if (typeof input !== "string")
  1954. throw new Errorf(
  1955. 'The first parameter of "parseCookie" should be a String, but %v given.',
  1956. input
  1957. );
  1958. return input.split(";").filter((v) => v !== "").map((v) => v.split("=")).reduce((cookies, tuple) => {
  1959. const key = decodeURIComponent(tuple[0]).trim();
  1960. cookies[key] = decodeURIComponent(tuple[1]).trim();
  1961. return cookies;
  1962. }, {});
  1963. }
  1964. // src/utils/create-error.js
  1965. function createError(errorCtor, message, ...args) {
  1966. if (typeof errorCtor !== "function")
  1967. throw new Errorf(
  1968. 'The first argument of "createError" should be a constructor, but %v given.',
  1969. errorCtor
  1970. );
  1971. if (message != null && typeof message !== "string")
  1972. throw new Errorf(
  1973. 'The second argument of "createError" should be a String, but %v given.',
  1974. message
  1975. );
  1976. if (message == null) return new errorCtor();
  1977. const interpolatedMessage = format(message, ...args);
  1978. return new errorCtor(interpolatedMessage);
  1979. }
  1980. // src/utils/to-camel-case.js
  1981. function toCamelCase(input) {
  1982. if (typeof input !== "string")
  1983. throw new Errorf(
  1984. 'The first argument of "toCamelCase" should be a String, but %v given.',
  1985. input
  1986. );
  1987. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  1988. }
  1989. // src/utils/create-debugger.js
  1990. var import_debug = __toESM(require_src(), 1);
  1991. function createDebugger(name) {
  1992. if (typeof name !== "string")
  1993. throw new Errorf(
  1994. 'The first argument of "createDebugger" should be a String, but %v given.',
  1995. name
  1996. );
  1997. const debug3 = (0, import_debug.default)(`jsTrieRouter:${name}`);
  1998. return function(message, ...args) {
  1999. const interpolatedMessage = format(message, ...args);
  2000. return debug3(interpolatedMessage);
  2001. };
  2002. }
  2003. // src/utils/is-response-sent.js
  2004. function isResponseSent(res) {
  2005. if (!res || typeof res !== "object" || Array.isArray(res) || typeof res.headersSent !== "boolean") {
  2006. throw new Errorf(
  2007. 'The first argument of "isResponseSent" should be an instance of ServerResponse, but %v given.',
  2008. res
  2009. );
  2010. }
  2011. return res.headersSent;
  2012. }
  2013. // src/utils/is-readable-stream.js
  2014. function isReadableStream(value) {
  2015. if (!value || typeof value !== "object") return false;
  2016. return typeof value.pipe === "function";
  2017. }
  2018. // src/utils/parse-content-type.js
  2019. function parseContentType(input) {
  2020. if (typeof input !== "string")
  2021. throw new Errorf(
  2022. 'The parameter "input" of "parseContentType" should be a String, but %v given.',
  2023. input
  2024. );
  2025. const res = { mediaType: void 0, charset: void 0, boundary: void 0 };
  2026. const re = /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  2027. const matches = re.exec(input);
  2028. if (matches && matches[1]) {
  2029. res.mediaType = matches[1];
  2030. if (matches[2]) res.charset = matches[2];
  2031. if (matches[3]) res.boundary = matches[3];
  2032. }
  2033. return res;
  2034. }
  2035. // src/utils/is-writable-stream.js
  2036. function isWritableStream(value) {
  2037. if (!value || typeof value !== "object") return false;
  2038. return typeof value.end === "function";
  2039. }
  2040. // src/utils/fetch-request-body.js
  2041. var import_http_errors = __toESM(require_http_errors(), 1);
  2042. var import_http = require("http");
  2043. var BUFFER_ENCODING_LIST = [
  2044. "ascii",
  2045. "utf8",
  2046. "utf-8",
  2047. "utf16le",
  2048. "utf-16le",
  2049. "ucs2",
  2050. "ucs-2",
  2051. "base64",
  2052. "base64url",
  2053. "latin1",
  2054. "binary",
  2055. "hex"
  2056. ];
  2057. function fetchRequestBody(req, bodyBytesLimit = 0) {
  2058. if (!(req instanceof import_http.IncomingMessage))
  2059. throw new Errorf(
  2060. 'The first parameter of "fetchRequestBody" should be an IncomingMessage instance, but %v given.',
  2061. req
  2062. );
  2063. if (typeof bodyBytesLimit !== "number")
  2064. throw new Errorf(
  2065. 'The parameter "bodyBytesLimit" of "fetchRequestBody" should be a number, but %v given.',
  2066. bodyBytesLimit
  2067. );
  2068. return new Promise((resolve, reject) => {
  2069. const contentLength = parseInt(req.headers["content-length"] || "0", 10);
  2070. if (bodyBytesLimit && contentLength && contentLength > bodyBytesLimit)
  2071. throw createError(
  2072. import_http_errors.default.PayloadTooLarge,
  2073. "Request body limit is %s bytes, but %s bytes given.",
  2074. bodyBytesLimit,
  2075. contentLength
  2076. );
  2077. let encoding = "utf-8";
  2078. const contentType = req.headers["content-type"] || "";
  2079. if (contentType) {
  2080. const parsedContentType = parseContentType(contentType);
  2081. if (parsedContentType && parsedContentType.charset) {
  2082. encoding = parsedContentType.charset.toLowerCase();
  2083. if (!BUFFER_ENCODING_LIST.includes(encoding))
  2084. throw createError(
  2085. import_http_errors.default.UnsupportedMediaType,
  2086. "Request encoding %v is not supported.",
  2087. encoding
  2088. );
  2089. }
  2090. }
  2091. const data = [];
  2092. let receivedLength = 0;
  2093. const onData = (chunk) => {
  2094. receivedLength += chunk.length;
  2095. if (bodyBytesLimit && receivedLength > bodyBytesLimit) {
  2096. req.removeAllListeners();
  2097. const error = createError(
  2098. import_http_errors.default.PayloadTooLarge,
  2099. "Request body limit is %v bytes, but %v bytes given.",
  2100. bodyBytesLimit,
  2101. receivedLength
  2102. );
  2103. reject(error);
  2104. return;
  2105. }
  2106. data.push(chunk);
  2107. };
  2108. const onEnd = () => {
  2109. req.removeAllListeners();
  2110. if (contentLength && contentLength !== receivedLength) {
  2111. const error = createError(
  2112. import_http_errors.default.BadRequest,
  2113. 'Received bytes do not match the "content-length" header.'
  2114. );
  2115. reject(error);
  2116. return;
  2117. }
  2118. const buffer = Buffer.concat(data);
  2119. const body = Buffer.from(buffer, encoding).toString();
  2120. resolve(body || void 0);
  2121. };
  2122. const onError = (error) => {
  2123. req.removeAllListeners();
  2124. reject((0, import_http_errors.default)(400, error));
  2125. };
  2126. req.on("data", onData);
  2127. req.on("end", onEnd);
  2128. req.on("error", onError);
  2129. req.resume();
  2130. });
  2131. }
  2132. // src/utils/create-request-mock.js
  2133. var import_net = require("net");
  2134. var import_tls = require("tls");
  2135. var import_http2 = require("http");
  2136. var import_querystring = __toESM(require("querystring"), 1);
  2137. // src/utils/create-cookie-string.js
  2138. function createCookieString(data) {
  2139. if (!data || typeof data !== "object" || Array.isArray(data))
  2140. throw new Errorf(
  2141. 'The first parameter of "createCookieString" should be an Object, but %v given.',
  2142. data
  2143. );
  2144. let cookies = "";
  2145. for (const key in data) {
  2146. if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
  2147. const val = data[key];
  2148. if (val == null) continue;
  2149. cookies += `${key}=${val}; `;
  2150. }
  2151. return cookies.trim();
  2152. }
  2153. // src/utils/create-request-mock.js
  2154. function createRequestMock(patch) {
  2155. if (patch != null && typeof patch !== "object" || Array.isArray(patch)) {
  2156. throw new Errorf(
  2157. 'The first parameter of "createRequestMock" should be an Object, but %v given.',
  2158. patch
  2159. );
  2160. }
  2161. patch = patch || {};
  2162. if (patch.host != null && typeof patch.host !== "string")
  2163. throw new Errorf(
  2164. 'The parameter "host" of "createRequestMock" should be a String, but %v given.',
  2165. patch.host
  2166. );
  2167. if (patch.method != null && typeof patch.method !== "string")
  2168. throw new Errorf(
  2169. 'The parameter "method" of "createRequestMock" should be a String, but %v given.',
  2170. patch.method
  2171. );
  2172. if (patch.secure != null && typeof patch.secure !== "boolean")
  2173. throw new Errorf(
  2174. 'The parameter "secure" of "createRequestMock" should be a Boolean, but %v given.',
  2175. patch.secure
  2176. );
  2177. if (patch.path != null && typeof patch.path !== "string")
  2178. throw new Errorf(
  2179. 'The parameter "path" of "createRequestMock" should be a String, but %v given.',
  2180. patch.path
  2181. );
  2182. if (patch.query != null && typeof patch.query !== "object" && typeof patch.query !== "string" || Array.isArray(patch.query)) {
  2183. throw new Errorf(
  2184. 'The parameter "query" of "createRequestMock" should be a String or Object, but %v given.',
  2185. patch.query
  2186. );
  2187. }
  2188. if (patch.cookie != null && typeof patch.cookie !== "string" && typeof patch.cookie !== "object" || Array.isArray(patch.cookie)) {
  2189. throw new Errorf(
  2190. 'The parameter "cookie" of "createRequestMock" should be a String or Object, but %v given.',
  2191. patch.cookie
  2192. );
  2193. }
  2194. if (patch.headers != null && typeof patch.headers !== "object" || Array.isArray(patch.headers)) {
  2195. throw new Errorf(
  2196. 'The parameter "headers" of "createRequestMock" should be an Object, but %v given.',
  2197. patch.headers
  2198. );
  2199. }
  2200. if (patch.stream != null && !isReadableStream(patch.stream))
  2201. throw new Errorf(
  2202. 'The parameter "stream" of "createRequestMock" should be a Stream, but %v given.',
  2203. patch.stream
  2204. );
  2205. if (patch.encoding != null) {
  2206. if (typeof patch.encoding !== "string")
  2207. throw new Errorf(
  2208. 'The parameter "encoding" of "createRequestMock" should be a String, but %v given.',
  2209. patch.encoding
  2210. );
  2211. if (!BUFFER_ENCODING_LIST.includes(patch.encoding))
  2212. throw new Errorf("Buffer encoding %v is not supported.", patch.encoding);
  2213. }
  2214. if (patch.stream) {
  2215. if (patch.secure != null)
  2216. throw new Errorf(
  2217. 'The "createRequestMock" does not allow specifying the "stream" and "secure" options simultaneously.'
  2218. );
  2219. if (patch.body != null)
  2220. throw new Errorf(
  2221. 'The "createRequestMock" does not allow specifying the "stream" and "body" options simultaneously.'
  2222. );
  2223. if (patch.encoding != null)
  2224. throw new Errorf(
  2225. 'The "createRequestMock" does not allow specifying the "stream" and "encoding" options simultaneously.'
  2226. );
  2227. }
  2228. const req = patch.stream || createRequestStream(patch.secure, patch.body, patch.encoding);
  2229. req.url = createRequestUrl(patch.path || "/", patch.query);
  2230. req.headers = createRequestHeaders(
  2231. patch.host,
  2232. patch.secure,
  2233. patch.body,
  2234. patch.cookie,
  2235. patch.encoding,
  2236. patch.headers
  2237. );
  2238. req.method = (patch.method || "get").toUpperCase();
  2239. return req;
  2240. }
  2241. function createRequestStream(secure, body, encoding) {
  2242. if (encoding != null && typeof encoding !== "string")
  2243. throw new Errorf(
  2244. 'The parameter "encoding" of "createRequestStream" should be a String, but %v given.',
  2245. encoding
  2246. );
  2247. encoding = encoding || "utf-8";
  2248. let socket = new import_net.Socket();
  2249. if (secure) socket = new import_tls.TLSSocket(socket);
  2250. const req = new import_http2.IncomingMessage(socket);
  2251. if (body != null) {
  2252. if (typeof body === "string") {
  2253. req.push(body, encoding);
  2254. } else if (Buffer.isBuffer(body)) {
  2255. req.push(body);
  2256. } else {
  2257. req.push(JSON.stringify(body));
  2258. }
  2259. }
  2260. req.push(null);
  2261. return req;
  2262. }
  2263. function createRequestUrl(path, query) {
  2264. if (typeof path !== "string")
  2265. throw new Errorf(
  2266. 'The parameter "path" of "createRequestUrl" should be a String, but %v given.',
  2267. path
  2268. );
  2269. if (query != null && typeof query !== "string" && typeof query !== "object" || Array.isArray(query)) {
  2270. throw new Errorf(
  2271. 'The parameter "query" of "createRequestUrl" should be a String or Object, but %v given.',
  2272. query
  2273. );
  2274. }
  2275. let url = ("/" + path).replace("//", "/");
  2276. if (typeof query === "object") {
  2277. const qs = import_querystring.default.stringify(query);
  2278. if (qs) url += `?${qs}`;
  2279. } else if (typeof query === "string") {
  2280. url += `?${query.replace(/^\?/, "")}`;
  2281. }
  2282. return url;
  2283. }
  2284. function createRequestHeaders(host, secure, body, cookie, encoding, headers) {
  2285. if (host != null && typeof host !== "string")
  2286. throw new Errorf(
  2287. 'The parameter "host" of "createRequestHeaders" a non-empty String, but %v given.',
  2288. host
  2289. );
  2290. host = host || "localhost";
  2291. if (secure != null && typeof secure !== "boolean")
  2292. throw new Errorf(
  2293. 'The parameter "secure" of "createRequestHeaders" should be a String, but %v given.',
  2294. secure
  2295. );
  2296. secure = Boolean(secure);
  2297. if (cookie != null && typeof cookie !== "object" && typeof cookie !== "string" || Array.isArray(cookie)) {
  2298. throw new Errorf(
  2299. 'The parameter "cookie" of "createRequestHeaders" should be a String or Object, but %v given.',
  2300. cookie
  2301. );
  2302. }
  2303. if (headers != null && typeof headers !== "object" || Array.isArray(headers)) {
  2304. throw new Errorf(
  2305. 'The parameter "headers" of "createRequestHeaders" should be an Object, but %v given.',
  2306. headers
  2307. );
  2308. }
  2309. headers = headers || {};
  2310. if (encoding != null && typeof encoding !== "string")
  2311. throw new Errorf(
  2312. 'The parameter "encoding" of "createRequestHeaders" should be a String, but %v given.',
  2313. encoding
  2314. );
  2315. encoding = encoding || "utf-8";
  2316. const obj = { ...headers };
  2317. obj["host"] = host;
  2318. if (secure) obj["x-forwarded-proto"] = "https";
  2319. if (cookie != null) {
  2320. if (typeof cookie === "string") {
  2321. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  2322. obj["cookie"] += cookie;
  2323. } else if (typeof cookie === "object") {
  2324. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  2325. obj["cookie"] += createCookieString(cookie);
  2326. }
  2327. }
  2328. if (obj["content-type"] == null) {
  2329. if (typeof body === "string") {
  2330. obj["content-type"] = "text/plain";
  2331. } else if (Buffer.isBuffer(body)) {
  2332. obj["content-type"] = "application/octet-stream";
  2333. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  2334. obj["content-type"] = "application/json";
  2335. }
  2336. }
  2337. if (body != null && obj["content-length"] == null) {
  2338. if (typeof body === "string") {
  2339. const length = Buffer.byteLength(body, encoding);
  2340. obj["content-length"] = String(length);
  2341. } else if (Buffer.isBuffer(body)) {
  2342. const length = Buffer.byteLength(body);
  2343. obj["content-length"] = String(length);
  2344. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  2345. const json = JSON.stringify(body);
  2346. const length = Buffer.byteLength(json, encoding);
  2347. obj["content-length"] = String(length);
  2348. }
  2349. }
  2350. return obj;
  2351. }
  2352. // src/utils/create-response-mock.js
  2353. var import_stream = require("stream");
  2354. function createResponseMock() {
  2355. const res = new import_stream.PassThrough();
  2356. patchEncoding(res);
  2357. patchHeaders(res);
  2358. patchBody(res);
  2359. return res;
  2360. }
  2361. function patchEncoding(res) {
  2362. Object.defineProperty(res, "_encoding", {
  2363. configurable: true,
  2364. writable: true,
  2365. value: void 0
  2366. });
  2367. Object.defineProperty(res, "setEncoding", {
  2368. configurable: true,
  2369. value: function(enc) {
  2370. this._encoding = enc;
  2371. return this;
  2372. }
  2373. });
  2374. Object.defineProperty(res, "getEncoding", {
  2375. configurable: true,
  2376. value: function() {
  2377. return this._encoding;
  2378. }
  2379. });
  2380. }
  2381. function patchHeaders(res) {
  2382. Object.defineProperty(res, "_headersSent", {
  2383. configurable: true,
  2384. writable: true,
  2385. value: false
  2386. });
  2387. Object.defineProperty(res, "headersSent", {
  2388. configurable: true,
  2389. get() {
  2390. return this._headersSent;
  2391. }
  2392. });
  2393. Object.defineProperty(res, "_headers", {
  2394. configurable: true,
  2395. writable: true,
  2396. value: {}
  2397. });
  2398. Object.defineProperty(res, "setHeader", {
  2399. configurable: true,
  2400. value: function(name, value) {
  2401. if (this.headersSent)
  2402. throw new Error(
  2403. "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
  2404. );
  2405. const key = name.toLowerCase();
  2406. this._headers[key] = String(value);
  2407. return this;
  2408. }
  2409. });
  2410. Object.defineProperty(res, "getHeader", {
  2411. configurable: true,
  2412. value: function(name) {
  2413. return this._headers[name.toLowerCase()];
  2414. }
  2415. });
  2416. Object.defineProperty(res, "getHeaders", {
  2417. configurable: true,
  2418. value: function() {
  2419. return JSON.parse(JSON.stringify(this._headers));
  2420. }
  2421. });
  2422. }
  2423. function patchBody(res) {
  2424. let resolve, reject;
  2425. const promise = new Promise((res2, rej) => {
  2426. resolve = res2;
  2427. reject = rej;
  2428. });
  2429. const data = [];
  2430. res.on("data", (c) => data.push(c));
  2431. res.on("error", (e) => reject(e));
  2432. res.on("end", () => {
  2433. res._headersSent = true;
  2434. resolve(Buffer.concat(data));
  2435. });
  2436. Object.defineProperty(res, "getBody", {
  2437. configurable: true,
  2438. value: function() {
  2439. return promise.then((buffer) => {
  2440. const enc = this.getEncoding();
  2441. const str = buffer.toString(enc);
  2442. return data.length ? str : void 0;
  2443. });
  2444. }
  2445. });
  2446. }
  2447. // src/utils/get-request-pathname.js
  2448. function getRequestPathname(req) {
  2449. if (!req || typeof req !== "object" || Array.isArray(req) || typeof req.url !== "string") {
  2450. throw new Errorf(
  2451. 'The first argument of "getRequestPathname" should be an instance of IncomingMessage, but %v given.',
  2452. req
  2453. );
  2454. }
  2455. return (req.url || "/").replace(/\?.*$/, "");
  2456. }
  2457. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  2458. var InvalidArgumentError = class extends Errorf {
  2459. };
  2460. // node_modules/@e22m4u/js-service/src/service-container.js
  2461. var ServiceContainer = class _ServiceContainer {
  2462. /**
  2463. * Services map.
  2464. *
  2465. * @type {Map<any, any>}
  2466. * @private
  2467. */
  2468. _services = /* @__PURE__ */ new Map();
  2469. /**
  2470. * Parent container.
  2471. *
  2472. * @type {ServiceContainer}
  2473. * @private
  2474. */
  2475. _parent;
  2476. /**
  2477. * Constructor.
  2478. *
  2479. * @param {ServiceContainer|undefined} parent
  2480. */
  2481. constructor(parent = void 0) {
  2482. if (parent != null) {
  2483. if (!(parent instanceof _ServiceContainer))
  2484. throw new InvalidArgumentError(
  2485. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  2486. parent
  2487. );
  2488. this._parent = parent;
  2489. }
  2490. }
  2491. /**
  2492. * Получить существующий или новый экземпляр.
  2493. *
  2494. * @param {*} ctor
  2495. * @param {*} args
  2496. * @return {*}
  2497. */
  2498. get(ctor, ...args) {
  2499. if (!ctor || typeof ctor !== "function")
  2500. throw new InvalidArgumentError(
  2501. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  2502. ctor
  2503. );
  2504. if (!this._services.has(ctor) && this._parent && this._parent.has(ctor)) {
  2505. return this._parent.get(ctor);
  2506. }
  2507. let service = this._services.get(ctor);
  2508. if (!service || args.length) {
  2509. service = "prototype" in ctor && ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2510. this._services.set(ctor, service);
  2511. } else if (typeof service === "function") {
  2512. service = service();
  2513. this._services.set(ctor, service);
  2514. }
  2515. return service;
  2516. }
  2517. /**
  2518. * Проверка существования конструктора в контейнере.
  2519. *
  2520. * @param {*} ctor
  2521. * @return {boolean}
  2522. */
  2523. has(ctor) {
  2524. if (this._services.has(ctor)) return true;
  2525. if (this._parent) return this._parent.has(ctor);
  2526. return false;
  2527. }
  2528. /**
  2529. * Добавить конструктор в контейнер.
  2530. *
  2531. * @param {*} ctor
  2532. * @param {*} args
  2533. * @return {this}
  2534. */
  2535. add(ctor, ...args) {
  2536. if (!ctor || typeof ctor !== "function")
  2537. throw new InvalidArgumentError(
  2538. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  2539. ctor
  2540. );
  2541. const factory = () => ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2542. this._services.set(ctor, factory);
  2543. return this;
  2544. }
  2545. /**
  2546. * Добавить конструктор и создать экземпляр.
  2547. *
  2548. * @param {*} ctor
  2549. * @param {*} args
  2550. * @return {this}
  2551. */
  2552. use(ctor, ...args) {
  2553. if (!ctor || typeof ctor !== "function")
  2554. throw new InvalidArgumentError(
  2555. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  2556. ctor
  2557. );
  2558. const service = ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2559. this._services.set(ctor, service);
  2560. return this;
  2561. }
  2562. /**
  2563. * Добавить конструктор и связанный экземпляр.
  2564. *
  2565. * @param {*} ctor
  2566. * @param {*} service
  2567. * @return {this}
  2568. */
  2569. set(ctor, service) {
  2570. if (!ctor || typeof ctor !== "function")
  2571. throw new InvalidArgumentError(
  2572. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  2573. ctor
  2574. );
  2575. if (!service || typeof service !== "object" || Array.isArray(service))
  2576. throw new InvalidArgumentError(
  2577. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  2578. service
  2579. );
  2580. this._services.set(ctor, service);
  2581. return this;
  2582. }
  2583. };
  2584. // node_modules/@e22m4u/js-service/src/service.js
  2585. var Service = class {
  2586. /**
  2587. * Container.
  2588. *
  2589. * @type {ServiceContainer}
  2590. */
  2591. container;
  2592. /**
  2593. * Constructor.
  2594. *
  2595. * @param {ServiceContainer|undefined} container
  2596. */
  2597. constructor(container = void 0) {
  2598. this.container = container instanceof ServiceContainer ? container : new ServiceContainer();
  2599. }
  2600. /**
  2601. * Получить существующий или новый экземпляр.
  2602. *
  2603. * @param {*} ctor
  2604. * @param {*} args
  2605. * @return {*}
  2606. */
  2607. getService(ctor, ...args) {
  2608. return this.container.get(ctor, ...args);
  2609. }
  2610. /**
  2611. * Проверка существования конструктора в контейнере.
  2612. *
  2613. * @param {*} ctor
  2614. * @return {boolean}
  2615. */
  2616. hasService(ctor) {
  2617. return this.container.has(ctor);
  2618. }
  2619. /**
  2620. * Добавить конструктор в контейнер.
  2621. *
  2622. * @param {*} ctor
  2623. * @param {*} args
  2624. * @return {this}
  2625. */
  2626. addService(ctor, ...args) {
  2627. this.container.add(ctor, ...args);
  2628. return this;
  2629. }
  2630. /**
  2631. * Добавить конструктор и создать экземпляр.
  2632. *
  2633. * @param {*} ctor
  2634. * @param {*} args
  2635. * @return {this}
  2636. */
  2637. useService(ctor, ...args) {
  2638. this.container.use(ctor, ...args);
  2639. return this;
  2640. }
  2641. /**
  2642. * Добавить конструктор и связанный экземпляр.
  2643. *
  2644. * @param {*} ctor
  2645. * @param {*} service
  2646. * @return {this}
  2647. */
  2648. setService(ctor, service) {
  2649. this.container.set(ctor, service);
  2650. return this;
  2651. }
  2652. };
  2653. // src/debuggable-service.js
  2654. var DebuggableService = class extends Service {
  2655. /**
  2656. * Debug.
  2657. *
  2658. * @type {Function}
  2659. */
  2660. debug;
  2661. /**
  2662. * Constructor.
  2663. *
  2664. * @param {ServiceContainer} container
  2665. */
  2666. constructor(container) {
  2667. super(container);
  2668. const serviceName = toCamelCase(this.constructor.name);
  2669. this.debug = createDebugger(serviceName);
  2670. this.debug("The %v is created.", this.constructor);
  2671. }
  2672. };
  2673. // src/hooks/hook-registry.js
  2674. var HookName = {
  2675. PRE_HANDLER: "preHandler",
  2676. POST_HANDLER: "postHandler"
  2677. };
  2678. var HookRegistry = class extends DebuggableService {
  2679. /**
  2680. * Hooks.
  2681. *
  2682. * @type {Map<string, Function[]>}
  2683. * @private
  2684. */
  2685. _hooks = /* @__PURE__ */ new Map();
  2686. /**
  2687. * Add hook.
  2688. *
  2689. * @param {string} name
  2690. * @param {Function} hook
  2691. * @returns {this}
  2692. */
  2693. addHook(name, hook) {
  2694. if (!name || typeof name !== "string")
  2695. throw new Errorf("The hook name is required, but %v given.", name);
  2696. if (!Object.values(HookName).includes(name))
  2697. throw new Errorf("The hook name %v is not supported.", name);
  2698. if (!hook || typeof hook !== "function")
  2699. throw new Errorf(
  2700. "The hook %v should be a Function, but %v given.",
  2701. name,
  2702. hook
  2703. );
  2704. const hooks = this._hooks.get(name) || [];
  2705. hooks.push(hook);
  2706. this._hooks.set(name, hooks);
  2707. return this;
  2708. }
  2709. /**
  2710. * Has hook.
  2711. *
  2712. * @param {string} name
  2713. * @param {Function} hook
  2714. * @returns {boolean}
  2715. */
  2716. hasHook(name, hook) {
  2717. if (!name || typeof name !== "string")
  2718. throw new Errorf("The hook name is required, but %v given.", name);
  2719. if (!Object.values(HookName).includes(name))
  2720. throw new Errorf("The hook name %v is not supported.", name);
  2721. if (!hook || typeof hook !== "function")
  2722. throw new Errorf(
  2723. "The hook %v should be a Function, but %v given.",
  2724. name,
  2725. hook
  2726. );
  2727. const hooks = this._hooks.get(name) || [];
  2728. return hooks.indexOf(hook) > -1;
  2729. }
  2730. /**
  2731. * Get hooks.
  2732. *
  2733. * @param {string} name
  2734. * @returns {Function[]}
  2735. */
  2736. getHooks(name) {
  2737. if (!name || typeof name !== "string")
  2738. throw new Errorf("The hook name is required, but %v given.", name);
  2739. if (!Object.values(HookName).includes(name))
  2740. throw new Errorf("The hook name %v is not supported.", name);
  2741. return this._hooks.get(name) || [];
  2742. }
  2743. };
  2744. // src/hooks/hook-invoker.js
  2745. var HookInvoker = class extends DebuggableService {
  2746. /**
  2747. * Invoke and continue until value received.
  2748. *
  2749. * @param {Route} route
  2750. * @param {string} hookName
  2751. * @param {import('http').ServerResponse} response
  2752. * @param {*[]} args
  2753. * @returns {Promise<*>|*}
  2754. */
  2755. invokeAndContinueUntilValueReceived(route, hookName, response, ...args) {
  2756. if (!route || !(route instanceof Route))
  2757. throw new Errorf(
  2758. 'The parameter "route" of the HookInvoker.invokeAndContinueUntilValueReceived should be a Route instance, but %v given.',
  2759. route
  2760. );
  2761. if (!hookName || typeof hookName !== "string")
  2762. throw new Errorf(
  2763. 'The parameter "hookName" of the HookInvoker.invokeAndContinueUntilValueReceived should be a non-empty String, but %v given.',
  2764. hookName
  2765. );
  2766. if (!Object.values(HookName).includes(hookName))
  2767. throw new Errorf("The hook name %v is not supported.", hookName);
  2768. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  2769. throw new Errorf(
  2770. 'The parameter "response" of the HookInvoker.invokeAndContinueUntilValueReceived should be a ServerResponse instance, but %v given.',
  2771. response
  2772. );
  2773. }
  2774. const hooks = [
  2775. ...this.getService(HookRegistry).getHooks(hookName),
  2776. ...route.hookRegistry.getHooks(hookName)
  2777. ];
  2778. let result = void 0;
  2779. for (const hook of hooks) {
  2780. if (isResponseSent(response)) {
  2781. result = response;
  2782. break;
  2783. }
  2784. if (result == null) {
  2785. result = hook(...args);
  2786. } else if (isPromise(result)) {
  2787. result = result.then((prevVal) => {
  2788. if (isResponseSent(response)) {
  2789. result = response;
  2790. return;
  2791. }
  2792. if (prevVal != null) return prevVal;
  2793. return hook(...args);
  2794. });
  2795. } else {
  2796. break;
  2797. }
  2798. }
  2799. return result;
  2800. }
  2801. };
  2802. // src/route.js
  2803. var HttpMethod = {
  2804. GET: "GET",
  2805. POST: "POST",
  2806. PUT: "PUT",
  2807. PATCH: "PATCH",
  2808. DELETE: "DELETE"
  2809. };
  2810. var debug = createDebugger("route");
  2811. var Route = class {
  2812. /**
  2813. * Method.
  2814. *
  2815. * @type {string}
  2816. * @private
  2817. */
  2818. _method;
  2819. /**
  2820. * Getter of the method.
  2821. *
  2822. * @returns {string}
  2823. */
  2824. get method() {
  2825. return this._method;
  2826. }
  2827. /**
  2828. * Path template.
  2829. *
  2830. * @type {string}
  2831. * @private
  2832. */
  2833. _path;
  2834. /**
  2835. * Getter of the path.
  2836. *
  2837. * @returns {string}
  2838. */
  2839. get path() {
  2840. return this._path;
  2841. }
  2842. /**
  2843. * Handler.
  2844. *
  2845. * @type {RouteHandler}
  2846. * @private
  2847. */
  2848. _handler;
  2849. /**
  2850. * Getter of the handler.
  2851. *
  2852. * @returns {*}
  2853. */
  2854. get handler() {
  2855. return this._handler;
  2856. }
  2857. /**
  2858. * Hook registry.
  2859. *
  2860. * @type {HookRegistry}
  2861. * @private
  2862. */
  2863. _hookRegistry = new HookRegistry();
  2864. /**
  2865. * Getter of the hook registry.
  2866. *
  2867. * @returns {HookRegistry}
  2868. */
  2869. get hookRegistry() {
  2870. return this._hookRegistry;
  2871. }
  2872. /**
  2873. * Constructor.
  2874. *
  2875. * @param {RouteDefinition} routeDef
  2876. */
  2877. constructor(routeDef) {
  2878. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  2879. throw new Errorf(
  2880. "The first parameter of Route.controller should be an Object, but %v given.",
  2881. routeDef
  2882. );
  2883. if (!routeDef.method || typeof routeDef.method !== "string")
  2884. throw new Errorf(
  2885. 'The option "method" of the Route should be a non-empty String, but %v given.',
  2886. routeDef.method
  2887. );
  2888. this._method = routeDef.method.toUpperCase();
  2889. if (typeof routeDef.path !== "string")
  2890. throw new Errorf(
  2891. 'The option "path" of the Route should be a String, but %v given.',
  2892. routeDef.path
  2893. );
  2894. this._path = routeDef.path;
  2895. if (typeof routeDef.handler !== "function")
  2896. throw new Errorf(
  2897. 'The option "handler" of the Route should be a Function, but %v given.',
  2898. routeDef.handler
  2899. );
  2900. this._handler = routeDef.handler;
  2901. if (routeDef.preHandler != null) {
  2902. const preHandlerHooks = Array.isArray(routeDef.preHandler) ? routeDef.preHandler : [routeDef.preHandler];
  2903. preHandlerHooks.forEach((hook) => {
  2904. this._hookRegistry.addHook(HookName.PRE_HANDLER, hook);
  2905. });
  2906. }
  2907. if (routeDef.postHandler != null) {
  2908. const postHandlerHooks = Array.isArray(routeDef.postHandler) ? routeDef.postHandler : [routeDef.postHandler];
  2909. postHandlerHooks.forEach((hook) => {
  2910. this._hookRegistry.addHook(HookName.POST_HANDLER, hook);
  2911. });
  2912. }
  2913. }
  2914. /**
  2915. * Handle request.
  2916. *
  2917. * @param {RequestContext} context
  2918. * @returns {*}
  2919. */
  2920. handle(context) {
  2921. const requestPath = getRequestPathname(context.req);
  2922. debug(
  2923. "Invoking the Route handler for the request %s %v.",
  2924. this.method.toUpperCase(),
  2925. requestPath
  2926. );
  2927. return this._handler(context);
  2928. }
  2929. };
  2930. // src/senders/data-sender.js
  2931. var DataSender = class extends DebuggableService {
  2932. /**
  2933. * Send.
  2934. *
  2935. * @param {import('http').ServerResponse} res
  2936. * @param {*} data
  2937. * @returns {undefined}
  2938. */
  2939. send(res, data) {
  2940. if (data === res || res.headersSent) {
  2941. this.debug(
  2942. "Response sending was skipped because its headers where sent already ."
  2943. );
  2944. return;
  2945. }
  2946. if (data == null) {
  2947. res.statusCode = 204;
  2948. res.end();
  2949. this.debug("The empty response was sent.");
  2950. return;
  2951. }
  2952. if (isReadableStream(data)) {
  2953. res.setHeader("Content-Type", "application/octet-stream");
  2954. data.pipe(res);
  2955. this.debug("The stream response was sent.");
  2956. return;
  2957. }
  2958. let debugMsg;
  2959. switch (typeof data) {
  2960. case "object":
  2961. case "boolean":
  2962. case "number":
  2963. if (Buffer.isBuffer(data)) {
  2964. res.setHeader("content-type", "application/octet-stream");
  2965. debugMsg = "The Buffer was sent as binary data.";
  2966. } else {
  2967. res.setHeader("content-type", "application/json");
  2968. debugMsg = format("The %v was sent as JSON.", typeof data);
  2969. data = JSON.stringify(data);
  2970. }
  2971. break;
  2972. default:
  2973. res.setHeader("content-type", "text/plain");
  2974. debugMsg = "The response data was sent as plain text.";
  2975. data = String(data);
  2976. break;
  2977. }
  2978. res.end(data);
  2979. this.debug(debugMsg);
  2980. }
  2981. };
  2982. // src/senders/error-sender.js
  2983. var import_util = require("util");
  2984. var import_statuses = __toESM(require_statuses(), 1);
  2985. var EXPOSED_ERROR_PROPERTIES = ["code", "details"];
  2986. var ErrorSender = class extends DebuggableService {
  2987. /**
  2988. * Handle.
  2989. *
  2990. * @param {import('http').IncomingMessage} req
  2991. * @param {import('http').ServerResponse} res
  2992. * @param {Error} error
  2993. * @returns {undefined}
  2994. */
  2995. send(req, res, error) {
  2996. let safeError = {};
  2997. if (error) {
  2998. if (typeof error === "object") {
  2999. safeError = error;
  3000. } else {
  3001. safeError = { message: String(error) };
  3002. }
  3003. }
  3004. const statusCode = error.statusCode || error.status || 500;
  3005. const body = { error: {} };
  3006. if (safeError.message && typeof safeError.message === "string") {
  3007. body.error.message = safeError.message;
  3008. } else {
  3009. body.error.message = (0, import_statuses.default)(statusCode);
  3010. }
  3011. EXPOSED_ERROR_PROPERTIES.forEach((name) => {
  3012. if (name in safeError) body.error[name] = safeError[name];
  3013. });
  3014. const requestData = {
  3015. url: req.url,
  3016. method: req.method,
  3017. headers: req.headers
  3018. };
  3019. const inspectOptions = {
  3020. showHidden: false,
  3021. depth: null,
  3022. colors: true,
  3023. compact: false
  3024. };
  3025. console.warn((0, import_util.inspect)(requestData, inspectOptions));
  3026. console.warn((0, import_util.inspect)(body, inspectOptions));
  3027. res.statusCode = statusCode;
  3028. res.setHeader("content-type", "application/json; charset=utf-8");
  3029. res.end(JSON.stringify(body, null, 2), "utf-8");
  3030. this.debug(
  3031. "The %s error is sent for the request %s %v.",
  3032. statusCode,
  3033. req.method,
  3034. getRequestPathname(req)
  3035. );
  3036. }
  3037. /**
  3038. * Send 404.
  3039. *
  3040. * @param {import('http').IncomingMessage} req
  3041. * @param {import('http').ServerResponse} res
  3042. * @returns {undefined}
  3043. */
  3044. send404(req, res) {
  3045. res.statusCode = 404;
  3046. res.setHeader("content-type", "text/plain; charset=utf-8");
  3047. res.end("404 Not Found", "utf-8");
  3048. this.debug(
  3049. "The 404 error is sent for the request %s %v.",
  3050. req.method,
  3051. getRequestPathname(req)
  3052. );
  3053. }
  3054. };
  3055. // src/parsers/body-parser.js
  3056. var import_http_errors2 = __toESM(require_http_errors(), 1);
  3057. // src/router-options.js
  3058. var RouterOptions = class extends DebuggableService {
  3059. /**
  3060. * Request body bytes limit.
  3061. *
  3062. * @type {number}
  3063. * @private
  3064. */
  3065. _requestBodyBytesLimit = 512e3;
  3066. // 512kb
  3067. /**
  3068. * Getter of request body bytes limit.
  3069. *
  3070. * @returns {number}
  3071. */
  3072. get requestBodyBytesLimit() {
  3073. return this._requestBodyBytesLimit;
  3074. }
  3075. /**
  3076. * Set request body bytes limit.
  3077. *
  3078. * @param {number} input
  3079. * @returns {RouterOptions}
  3080. */
  3081. setRequestBodyBytesLimit(input) {
  3082. if (typeof input !== "number" || input < 0)
  3083. throw new Errorf(
  3084. 'The option "requestBodyBytesLimit" must be a positive Number or 0, but %v given.',
  3085. input
  3086. );
  3087. this._requestBodyBytesLimit = input;
  3088. return this;
  3089. }
  3090. };
  3091. // src/parsers/body-parser.js
  3092. var METHODS_WITH_BODY = ["POST", "PUT", "PATCH", "DELETE"];
  3093. var UNPARSABLE_MEDIA_TYPES = ["multipart/form-data"];
  3094. var BodyParser = class extends DebuggableService {
  3095. /**
  3096. * Parsers.
  3097. *
  3098. * @type {{[mime: string]: Function}}
  3099. */
  3100. _parsers = {
  3101. "text/plain": (v) => String(v),
  3102. "application/json": parseJsonBody
  3103. };
  3104. /**
  3105. * Set parser.
  3106. *
  3107. * @param {string} mediaType
  3108. * @param {Function} parser
  3109. * @returns {this}
  3110. */
  3111. defineParser(mediaType, parser) {
  3112. if (!mediaType || typeof mediaType !== "string")
  3113. throw new Errorf(
  3114. 'The parameter "mediaType" of BodyParser.defineParser should be a non-empty String, but %v given.',
  3115. mediaType
  3116. );
  3117. if (!parser || typeof parser !== "function")
  3118. throw new Errorf(
  3119. 'The parameter "parser" of BodyParser.defineParser should be a Function, but %v given.',
  3120. parser
  3121. );
  3122. this._parsers[mediaType] = parser;
  3123. return this;
  3124. }
  3125. /**
  3126. * Has parser.
  3127. *
  3128. * @param {string} mediaType
  3129. * @returns {boolean}
  3130. */
  3131. hasParser(mediaType) {
  3132. if (!mediaType || typeof mediaType !== "string")
  3133. throw new Errorf(
  3134. 'The parameter "mediaType" of BodyParser.hasParser should be a non-empty String, but %v given.',
  3135. mediaType
  3136. );
  3137. return Boolean(this._parsers[mediaType]);
  3138. }
  3139. /**
  3140. * Delete parser.
  3141. *
  3142. * @param {string} mediaType
  3143. * @returns {this}
  3144. */
  3145. deleteParser(mediaType) {
  3146. if (!mediaType || typeof mediaType !== "string")
  3147. throw new Errorf(
  3148. 'The parameter "mediaType" of BodyParser.deleteParser should be a non-empty String, but %v given.',
  3149. mediaType
  3150. );
  3151. const parser = this._parsers[mediaType];
  3152. if (!parser) throw new Errorf("The parser of %v is not found.", mediaType);
  3153. delete this._parsers[mediaType];
  3154. return this;
  3155. }
  3156. /**
  3157. * Parse.
  3158. *
  3159. * @param {import('http').IncomingMessage} req
  3160. * @returns {Promise<*>|undefined}
  3161. */
  3162. parse(req) {
  3163. if (!METHODS_WITH_BODY.includes(req.method.toUpperCase())) {
  3164. this.debug(
  3165. "Body parsing was skipped for the %s request.",
  3166. req.method.toUpperCase()
  3167. );
  3168. return;
  3169. }
  3170. const contentType = (req.headers["content-type"] || "").replace(
  3171. /^([^;]+);.*$/,
  3172. "$1"
  3173. );
  3174. if (!contentType) {
  3175. this.debug(
  3176. "Body parsing was skipped because the request has no content type."
  3177. );
  3178. return;
  3179. }
  3180. const { mediaType } = parseContentType(contentType);
  3181. if (!mediaType)
  3182. throw createError(
  3183. import_http_errors2.default.BadRequest,
  3184. 'Unable to parse the "content-type" header.'
  3185. );
  3186. const parser = this._parsers[mediaType];
  3187. if (!parser) {
  3188. if (UNPARSABLE_MEDIA_TYPES.includes(mediaType)) {
  3189. this.debug("Body parsing was skipped for %v.", mediaType);
  3190. return;
  3191. }
  3192. throw createError(
  3193. import_http_errors2.default.UnsupportedMediaType,
  3194. "Media type %v is not supported.",
  3195. mediaType
  3196. );
  3197. }
  3198. const bodyBytesLimit = this.getService(RouterOptions).requestBodyBytesLimit;
  3199. return fetchRequestBody(req, bodyBytesLimit).then((rawBody) => {
  3200. if (rawBody != null) return parser(rawBody);
  3201. return rawBody;
  3202. });
  3203. }
  3204. };
  3205. function parseJsonBody(input) {
  3206. if (typeof input !== "string") return void 0;
  3207. try {
  3208. return JSON.parse(input);
  3209. } catch (error) {
  3210. if (process.env["DEBUG"] || process.env["NODE_ENV"] === "development")
  3211. console.warn(error);
  3212. throw createError(import_http_errors2.default.BadRequest, "Unable to parse request body.");
  3213. }
  3214. }
  3215. // src/parsers/query-parser.js
  3216. var import_querystring2 = __toESM(require("querystring"), 1);
  3217. var QueryParser = class extends DebuggableService {
  3218. /**
  3219. * Parse
  3220. *
  3221. * @param {import('http').IncomingMessage} req
  3222. * @returns {object}
  3223. */
  3224. parse(req) {
  3225. const queryStr = req.url.replace(/^[^?]*\??/, "");
  3226. const query = queryStr ? import_querystring2.default.parse(queryStr) : {};
  3227. const queryKeys = Object.keys(query);
  3228. if (queryKeys.length) {
  3229. queryKeys.forEach((key) => {
  3230. this.debug("The query %v has the value %v.", key, query[key]);
  3231. });
  3232. } else {
  3233. this.debug(
  3234. "The request %s %v has no query.",
  3235. req.method,
  3236. getRequestPathname(req)
  3237. );
  3238. }
  3239. return query;
  3240. }
  3241. };
  3242. // src/parsers/cookie-parser.js
  3243. var CookieParser = class extends DebuggableService {
  3244. /**
  3245. * Parse
  3246. *
  3247. * @param {import('http').IncomingMessage} req
  3248. * @returns {object}
  3249. */
  3250. parse(req) {
  3251. const cookieString = req.headers["cookie"] || "";
  3252. const cookie = parseCookie(cookieString);
  3253. const cookieKeys = Object.keys(cookie);
  3254. if (cookieKeys.length) {
  3255. cookieKeys.forEach((key) => {
  3256. this.debug("The cookie %v has the value %v.", key, cookie[key]);
  3257. });
  3258. } else {
  3259. this.debug(
  3260. "The request %s %v has no cookie.",
  3261. req.method,
  3262. getRequestPathname(req)
  3263. );
  3264. }
  3265. return cookie;
  3266. }
  3267. };
  3268. // src/parsers/request-parser.js
  3269. var import_http3 = require("http");
  3270. var RequestParser = class extends DebuggableService {
  3271. /**
  3272. * Parse.
  3273. *
  3274. * @param {IncomingMessage} req
  3275. * @returns {Promise<object>|object}
  3276. */
  3277. parse(req) {
  3278. if (!(req instanceof import_http3.IncomingMessage))
  3279. throw new Errorf(
  3280. "The first argument of RequestParser.parse should be an instance of IncomingMessage, but %v given.",
  3281. req
  3282. );
  3283. const data = {};
  3284. const promises = [];
  3285. const parsedQuery = this.getService(QueryParser).parse(req);
  3286. if (isPromise(parsedQuery)) {
  3287. promises.push(parsedQuery.then((v) => data.query = v));
  3288. } else {
  3289. data.query = parsedQuery;
  3290. }
  3291. const parsedCookie = this.getService(CookieParser).parse(req);
  3292. if (isPromise(parsedCookie)) {
  3293. promises.push(parsedCookie.then((v) => data.cookie = v));
  3294. } else {
  3295. data.cookie = parsedCookie;
  3296. }
  3297. const parsedBody = this.getService(BodyParser).parse(req);
  3298. if (isPromise(parsedBody)) {
  3299. promises.push(parsedBody.then((v) => data.body = v));
  3300. } else {
  3301. data.body = parsedBody;
  3302. }
  3303. data.headers = JSON.parse(JSON.stringify(req.headers));
  3304. return promises.length ? Promise.all(promises).then(() => data) : data;
  3305. }
  3306. };
  3307. // node_modules/@e22m4u/js-path-trie/src/path-trie.js
  3308. var import_path_to_regexp = __toESM(require_dist(), 1);
  3309. // node_modules/@e22m4u/js-path-trie/src/utils/create-debugger.js
  3310. var import_debug2 = __toESM(require_src(), 1);
  3311. function createDebugger2() {
  3312. const debug3 = (0, import_debug2.default)(`jsPathTrie`);
  3313. return function(message, ...args) {
  3314. const interpolatedMessage = format(message, ...args);
  3315. return debug3(interpolatedMessage);
  3316. };
  3317. }
  3318. // node_modules/@e22m4u/js-path-trie/src/path-trie.js
  3319. var debug2 = createDebugger2();
  3320. var PathTrie = class {
  3321. /**
  3322. * Root node.
  3323. *
  3324. * @type {Node}
  3325. * @private
  3326. */
  3327. _root = {
  3328. token: "",
  3329. regexp: void 0,
  3330. names: [],
  3331. value: void 0,
  3332. children: {}
  3333. };
  3334. /**
  3335. * Add value.
  3336. *
  3337. * @param {string} pathTemplate
  3338. * @param {*} value
  3339. * @returns {this}
  3340. */
  3341. add(pathTemplate, value) {
  3342. if (typeof pathTemplate !== "string")
  3343. throw new Errorf(
  3344. "The first argument of PathTrie.add should be a String, but %v given.",
  3345. pathTemplate
  3346. );
  3347. if (value == null)
  3348. throw new Errorf(
  3349. "The second argument of PathTrie.add is required, but %v given.",
  3350. value
  3351. );
  3352. debug2("Adding the value to %v.", pathTemplate);
  3353. const tokens = pathTemplate.split("/").filter(Boolean);
  3354. this._createNode(tokens, 0, value, this._root);
  3355. return this;
  3356. }
  3357. /**
  3358. * Match value.
  3359. *
  3360. * @param {string} path
  3361. * @returns {ResolvedValue|undefined}
  3362. */
  3363. match(path) {
  3364. if (typeof path !== "string")
  3365. throw new Errorf(
  3366. "The first argument of PathTrie.match should be a String, but %v given.",
  3367. path
  3368. );
  3369. debug2("Matching a value with the path %v.", path);
  3370. const tokens = path.split("/").filter(Boolean);
  3371. const params = {};
  3372. const result = this._matchNode(tokens, 0, params, this._root);
  3373. if (!result || !result.node.value) return;
  3374. return { value: result.node.value, params };
  3375. }
  3376. /**
  3377. * Create node.
  3378. *
  3379. * @param {string[]} tokens
  3380. * @param {number} index
  3381. * @param {*} value
  3382. * @param {Node} parent
  3383. * @returns {Node}
  3384. * @private
  3385. */
  3386. _createNode(tokens, index, value, parent) {
  3387. if (tokens.length === 0 && index === 0) {
  3388. if (parent.value == null) {
  3389. parent.value = value;
  3390. } else if (parent.value !== value) {
  3391. throw new Errorf('The duplicate path "" has a different value.');
  3392. }
  3393. debug2("The value has set to the root node.");
  3394. return parent;
  3395. }
  3396. const token = tokens[index];
  3397. if (token == null)
  3398. throw new Errorf(
  3399. "Invalid index %v has passed to the PathTrie._createNode.",
  3400. index
  3401. );
  3402. const isLast = tokens.length - 1 === index;
  3403. let child = parent.children[token];
  3404. if (isLast && child != null) {
  3405. debug2("The node %v already exist.", token);
  3406. if (child.value == null) {
  3407. child.value = value;
  3408. } else if (child.value !== value) {
  3409. throw new Errorf(
  3410. "The duplicate path %v has a different value.",
  3411. "/" + tokens.join("/")
  3412. );
  3413. }
  3414. return child;
  3415. }
  3416. debug2("The node %v does not exist.", token);
  3417. child = {
  3418. token,
  3419. regexp: void 0,
  3420. names: [],
  3421. value: void 0,
  3422. children: {}
  3423. };
  3424. if (isLast) {
  3425. debug2("The node %v is last.", token);
  3426. child.value = value;
  3427. }
  3428. if (token.indexOf(":") > -1) {
  3429. debug2("The node %v has parameters.", token);
  3430. const modifiers = /([?*+{}])/.exec(token);
  3431. if (modifiers)
  3432. throw new Errorf(
  3433. "The symbol %v is not supported in path %v.",
  3434. modifiers[0],
  3435. "/" + tokens.join("/")
  3436. );
  3437. let regexp, keys;
  3438. try {
  3439. const regexpAndKeys = (0, import_path_to_regexp.pathToRegexp)(token);
  3440. regexp = regexpAndKeys.regexp;
  3441. keys = regexpAndKeys.keys;
  3442. } catch (error) {
  3443. if (error.message.indexOf("Missing parameter") > -1)
  3444. throw new Errorf(
  3445. 'The symbol ":" should be used to define path parameters, but no parameters found in the path %v.',
  3446. "/" + tokens.join("/")
  3447. );
  3448. throw error;
  3449. }
  3450. if (Array.isArray(keys) && keys.length) {
  3451. child.names = keys.map((p) => `${p.name}`);
  3452. child.regexp = regexp;
  3453. } else {
  3454. throw new Errorf(
  3455. 'The symbol ":" should be used to define path parameters, but no parameters found in the path %v.',
  3456. "/" + tokens.join("/")
  3457. );
  3458. }
  3459. debug2("Found parameters are %l.", child.names);
  3460. }
  3461. parent.children[token] = child;
  3462. debug2("The node %v has created.", token);
  3463. if (isLast) return child;
  3464. return this._createNode(tokens, index + 1, value, child);
  3465. }
  3466. /**
  3467. * Match node.
  3468. *
  3469. * @param {string[]} tokens
  3470. * @param {number} index
  3471. * @param {object} params
  3472. * @param {Node} parent
  3473. * @returns {ResolvedNode|undefined}
  3474. * @private
  3475. */
  3476. _matchNode(tokens, index, params, parent) {
  3477. if (tokens.length === 0 && index === 0) {
  3478. if (parent.value) {
  3479. debug2(
  3480. "The path %v matched with the root node.",
  3481. "/" + tokens.join("/")
  3482. );
  3483. return { node: parent, params };
  3484. }
  3485. return;
  3486. }
  3487. const token = tokens[index];
  3488. if (token == null)
  3489. throw new Errorf(
  3490. "Invalid index %v has passed to the PathTrie._matchNode.",
  3491. index
  3492. );
  3493. const resolvedNodes = this._matchChildrenNodes(token, parent);
  3494. debug2("%v nodes matches the token %v.", resolvedNodes.length, token);
  3495. if (!resolvedNodes.length) return;
  3496. const isLast = tokens.length - 1 === index;
  3497. if (isLast) {
  3498. debug2("The token %v is last.", token);
  3499. for (const child of resolvedNodes) {
  3500. debug2("The node %v matches the token %v.", child.node.token, token);
  3501. if (child.node.value) {
  3502. debug2("The node %v has a value.", child.node.token);
  3503. const paramNames = Object.keys(child.params);
  3504. if (paramNames.length) {
  3505. paramNames.forEach((name) => {
  3506. debug2(
  3507. "The node %v has parameter %v with the value %v.",
  3508. child.node.token,
  3509. name,
  3510. child.params[name]
  3511. );
  3512. });
  3513. } else {
  3514. debug2("The node %v has no parameters.", child.node.token);
  3515. }
  3516. Object.assign(params, child.params);
  3517. return { node: child.node, params };
  3518. }
  3519. }
  3520. } else {
  3521. for (const child of resolvedNodes) {
  3522. const result = this._matchNode(tokens, index + 1, params, child.node);
  3523. if (result) {
  3524. debug2("A value has found for the path %v.", "/" + tokens.join("/"));
  3525. const paramNames = Object.keys(child.params);
  3526. if (paramNames.length) {
  3527. paramNames.forEach((name) => {
  3528. debug2(
  3529. "The node %v has parameter %v with the value %v.",
  3530. child.node.token,
  3531. name,
  3532. child.params[name]
  3533. );
  3534. });
  3535. } else {
  3536. debug2("The node %v has no parameters.", child.node.token);
  3537. }
  3538. Object.assign(params, child.params);
  3539. return result;
  3540. }
  3541. }
  3542. }
  3543. debug2("No matched nodes with the path %v.", "/" + tokens.join("/"));
  3544. return void 0;
  3545. }
  3546. /**
  3547. * Match children nodes.
  3548. *
  3549. * @param {string} token
  3550. * @param {Node} parent
  3551. * @returns {ResolvedNode[]}
  3552. * @private
  3553. */
  3554. _matchChildrenNodes(token, parent) {
  3555. const resolvedNodes = [];
  3556. let child = parent.children[token];
  3557. if (child) {
  3558. resolvedNodes.push({ node: child, params: {} });
  3559. return resolvedNodes;
  3560. }
  3561. for (const key in parent.children) {
  3562. child = parent.children[key];
  3563. if (!child.names || !child.regexp) continue;
  3564. const match = child.regexp.exec(token);
  3565. if (match) {
  3566. const resolved = { node: child, params: {} };
  3567. let i = 0;
  3568. for (const name of child.names) {
  3569. const val = match[++i];
  3570. resolved.params[name] = decodeURIComponent(val);
  3571. }
  3572. resolvedNodes.push(resolved);
  3573. }
  3574. }
  3575. return resolvedNodes;
  3576. }
  3577. };
  3578. // src/route-registry.js
  3579. var RouteRegistry = class extends DebuggableService {
  3580. /**
  3581. * Constructor.
  3582. *
  3583. * @param {ServiceContainer} container
  3584. */
  3585. constructor(container) {
  3586. super(container);
  3587. this._trie = new PathTrie();
  3588. }
  3589. /**
  3590. * Define route.
  3591. *
  3592. * @param {import('./route.js').RouteDefinition} routeDef
  3593. * @returns {Route}
  3594. */
  3595. defineRoute(routeDef) {
  3596. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  3597. throw new Errorf(
  3598. "The route definition should be an Object, but %v given.",
  3599. routeDef
  3600. );
  3601. const route = new Route(routeDef);
  3602. const triePath = `${route.method}/${route.path}`;
  3603. this._trie.add(triePath, route);
  3604. this.debug(
  3605. "The route %s %v is registered.",
  3606. route.method.toUpperCase(),
  3607. route.path
  3608. );
  3609. return route;
  3610. }
  3611. /**
  3612. * Match route by request.
  3613. *
  3614. * @param {import('http').IncomingRequest} req
  3615. * @returns {ResolvedRoute|undefined}
  3616. */
  3617. matchRouteByRequest(req) {
  3618. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  3619. this.debug(
  3620. "Matching %s %v with registered routes.",
  3621. req.method.toUpperCase(),
  3622. requestPath
  3623. );
  3624. const triePath = `${req.method.toUpperCase()}/${requestPath}`;
  3625. const resolved = this._trie.match(triePath);
  3626. if (resolved) {
  3627. const route = resolved.value;
  3628. this.debug(
  3629. "The request %s %v was matched to the route %s %v.",
  3630. req.method.toUpperCase(),
  3631. requestPath,
  3632. route.method.toUpperCase(),
  3633. route.path
  3634. );
  3635. const paramNames = Object.keys(resolved.params);
  3636. if (paramNames) {
  3637. paramNames.forEach((name) => {
  3638. this.debug(
  3639. "The path parameter %v has the value %v.",
  3640. name,
  3641. resolved.params[name]
  3642. );
  3643. });
  3644. } else {
  3645. this.debug("No path parameters found.");
  3646. }
  3647. return { route, params: resolved.params };
  3648. }
  3649. this.debug(
  3650. "No matched route for the request %s %v.",
  3651. req.method.toUpperCase(),
  3652. requestPath
  3653. );
  3654. }
  3655. };
  3656. // src/request-context.js
  3657. var RequestContext = class {
  3658. /**
  3659. * Service container.
  3660. *
  3661. * @type {import('@e22m4u/js-service').ServiceContainer}
  3662. */
  3663. container;
  3664. /**
  3665. * Request.
  3666. *
  3667. * @type {import('http').IncomingMessage}
  3668. */
  3669. req;
  3670. /**
  3671. * Response.
  3672. *
  3673. * @type {import('http').ServerResponse}
  3674. */
  3675. res;
  3676. /**
  3677. * Query.
  3678. *
  3679. * @type {object}
  3680. */
  3681. query = {};
  3682. /**
  3683. * Path parameters.
  3684. *
  3685. * @type {object}
  3686. */
  3687. params = {};
  3688. /**
  3689. * Headers.
  3690. *
  3691. * @type {object}
  3692. */
  3693. headers = {};
  3694. /**
  3695. * Parsed cookie.
  3696. *
  3697. * @type {object}
  3698. */
  3699. cookie = {};
  3700. /**
  3701. * Parsed body.
  3702. *
  3703. * @type {*}
  3704. */
  3705. body;
  3706. /**
  3707. * Method.
  3708. *
  3709. * @returns {string}
  3710. */
  3711. get method() {
  3712. return this.req.method.toUpperCase();
  3713. }
  3714. /**
  3715. * Path.
  3716. *
  3717. * @returns {string}
  3718. */
  3719. get path() {
  3720. return this.req.url;
  3721. }
  3722. /**
  3723. * Pathname.
  3724. *
  3725. * @type {string|undefined}
  3726. * @private
  3727. */
  3728. _pathname = void 0;
  3729. /**
  3730. * Pathname.
  3731. *
  3732. * @returns {string}
  3733. */
  3734. get pathname() {
  3735. if (this._pathname != null) return this._pathname;
  3736. this._pathname = getRequestPathname(this.req);
  3737. return this._pathname;
  3738. }
  3739. /**
  3740. * Constructor.
  3741. *
  3742. * @param {ServiceContainer} container
  3743. * @param {import('http').IncomingMessage} request
  3744. * @param {import('http').ServerResponse} response
  3745. */
  3746. constructor(container, request, response) {
  3747. if (!(container instanceof ServiceContainer))
  3748. throw new Errorf(
  3749. 'The parameter "container" of RequestContext.constructor should be an instance of ServiceContainer, but %v given.',
  3750. container
  3751. );
  3752. this.container = container;
  3753. if (!request || typeof request !== "object" || Array.isArray(request) || !isReadableStream(request)) {
  3754. throw new Errorf(
  3755. 'The parameter "request" of RequestContext.constructor should be an instance of IncomingMessage, but %v given.',
  3756. request
  3757. );
  3758. }
  3759. this.req = request;
  3760. if (!response || typeof response !== "object" || Array.isArray(response) || !isWritableStream(response)) {
  3761. throw new Errorf(
  3762. 'The parameter "response" of RequestContext.constructor should be an instance of ServerResponse, but %v given.',
  3763. response
  3764. );
  3765. }
  3766. this.res = response;
  3767. }
  3768. };
  3769. // src/trie-router.js
  3770. var TrieRouter = class extends DebuggableService {
  3771. /**
  3772. * Define route.
  3773. *
  3774. * Example 1:
  3775. * ```
  3776. * const router = new TrieRouter();
  3777. * router.defineRoute({
  3778. * method: HttpMethod.GET, // Request method.
  3779. * path: '/', // Path template.
  3780. * handler: ctx => 'Hello world!', // Request handler.
  3781. * });
  3782. * ```
  3783. *
  3784. * Example 2:
  3785. * ```
  3786. * const router = new TrieRouter();
  3787. * router.defineRoute({
  3788. * method: HttpMethod.POST, // Request method.
  3789. * path: '/users/:id', // The path template may have parameters.
  3790. * preHandler(ctx) { ... }, // The "preHandler" is executed before a route handler.
  3791. * handler(ctx) { ... }, // Request handler function.
  3792. * postHandler(ctx, data) { ... }, // The "postHandler" is executed after a route handler.
  3793. * });
  3794. * ```
  3795. *
  3796. * @param {import('./route-registry.js').RouteDefinition} routeDef
  3797. * @returns {import('./route.js').Route}
  3798. */
  3799. defineRoute(routeDef) {
  3800. return this.getService(RouteRegistry).defineRoute(routeDef);
  3801. }
  3802. /**
  3803. * Request listener.
  3804. *
  3805. * Example:
  3806. * ```
  3807. * import http from 'http';
  3808. * import {TrieRouter} from '@e22m4u/js-trie-router';
  3809. *
  3810. * const router = new TrieRouter();
  3811. * const server = new http.Server();
  3812. * server.on('request', router.requestListener); // Sets the request listener.
  3813. * server.listen(3000); // Starts listening for connections.
  3814. * ```
  3815. *
  3816. * @returns {Function}
  3817. */
  3818. get requestListener() {
  3819. return this._handleRequest.bind(this);
  3820. }
  3821. /**
  3822. * Handle incoming request.
  3823. *
  3824. * @param {import('http').IncomingMessage} req
  3825. * @param {import('http').ServerResponse} res
  3826. * @returns {Promise<undefined>}
  3827. * @private
  3828. */
  3829. async _handleRequest(req, res) {
  3830. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  3831. this.debug("Preparing to handle %s %v.", req.method, requestPath);
  3832. const resolved = this.getService(RouteRegistry).matchRouteByRequest(req);
  3833. if (!resolved) {
  3834. this.debug("No route for the request %s %v.", req.method, requestPath);
  3835. this.getService(ErrorSender).send404(req, res);
  3836. } else {
  3837. const { route, params } = resolved;
  3838. const container = new ServiceContainer(this.container);
  3839. const context = new RequestContext(container, req, res);
  3840. context.params = params;
  3841. const reqDataOrPromise = this.getService(RequestParser).parse(req);
  3842. if (isPromise(reqDataOrPromise)) {
  3843. const reqData = await reqDataOrPromise;
  3844. Object.assign(context, reqData);
  3845. } else {
  3846. Object.assign(context, reqDataOrPromise);
  3847. }
  3848. let data, error;
  3849. const hookInvoker = this.getService(HookInvoker);
  3850. try {
  3851. data = hookInvoker.invokeAndContinueUntilValueReceived(
  3852. route,
  3853. HookName.PRE_HANDLER,
  3854. res,
  3855. context
  3856. );
  3857. if (isPromise(data)) data = await data;
  3858. if (data == null) {
  3859. data = route.handle(context);
  3860. if (isPromise(data)) data = await data;
  3861. let postHandlerData = hookInvoker.invokeAndContinueUntilValueReceived(
  3862. route,
  3863. HookName.POST_HANDLER,
  3864. res,
  3865. context,
  3866. data
  3867. );
  3868. if (isPromise(postHandlerData))
  3869. postHandlerData = await postHandlerData;
  3870. if (postHandlerData != null) data = postHandlerData;
  3871. }
  3872. } catch (err) {
  3873. error = err;
  3874. }
  3875. if (error) {
  3876. this.getService(ErrorSender).send(req, res, error);
  3877. } else {
  3878. this.getService(DataSender).send(res, data);
  3879. }
  3880. }
  3881. }
  3882. /**
  3883. * Add hook.
  3884. *
  3885. * Example:
  3886. * ```
  3887. * import {TrieRouter} from '@e22m4u/js-trie-router';
  3888. * import {HookName} from '@e22m4u/js-trie-router';
  3889. *
  3890. * // Router instance.
  3891. * const router = new TrieRouter();
  3892. *
  3893. * // Adds the "preHandler" hook for each route.
  3894. * router.addHook(
  3895. * HookName.PRE_HANDLER,
  3896. * ctx => { ... },
  3897. * );
  3898. *
  3899. * // Adds the "postHandler" hook for each route.
  3900. * router.addHook(
  3901. * HookName.POST_HANDLER,
  3902. * ctx => { ... },
  3903. * );
  3904. * ```
  3905. *
  3906. * @param {string} name
  3907. * @param {Function} hook
  3908. * @returns {this}
  3909. */
  3910. addHook(name, hook) {
  3911. this.getService(HookRegistry).addHook(name, hook);
  3912. return this;
  3913. }
  3914. };
  3915. // Annotate the CommonJS export names for ESM import in node:
  3916. 0 && (module.exports = {
  3917. BUFFER_ENCODING_LIST,
  3918. BodyParser,
  3919. CookieParser,
  3920. DataSender,
  3921. EXPOSED_ERROR_PROPERTIES,
  3922. ErrorSender,
  3923. HookInvoker,
  3924. HookName,
  3925. HookRegistry,
  3926. HttpMethod,
  3927. METHODS_WITH_BODY,
  3928. QueryParser,
  3929. RequestContext,
  3930. RequestParser,
  3931. Route,
  3932. RouteRegistry,
  3933. RouterOptions,
  3934. TrieRouter,
  3935. UNPARSABLE_MEDIA_TYPES,
  3936. createCookieString,
  3937. createDebugger,
  3938. createError,
  3939. createRequestMock,
  3940. createResponseMock,
  3941. fetchRequestBody,
  3942. getRequestPathname,
  3943. isPromise,
  3944. isReadableStream,
  3945. isResponseSent,
  3946. isWritableStream,
  3947. parseContentType,
  3948. parseCookie,
  3949. parseJsonBody,
  3950. toCamelCase
  3951. });
  3952. /*! Bundled license information:
  3953. depd/index.js:
  3954. (*!
  3955. * depd
  3956. * Copyright(c) 2014-2018 Douglas Christopher Wilson
  3957. * MIT Licensed
  3958. *)
  3959. statuses/index.js:
  3960. (*!
  3961. * statuses
  3962. * Copyright(c) 2014 Jonathan Ong
  3963. * Copyright(c) 2016 Douglas Christopher Wilson
  3964. * MIT Licensed
  3965. *)
  3966. toidentifier/index.js:
  3967. (*!
  3968. * toidentifier
  3969. * Copyright(c) 2016 Douglas Christopher Wilson
  3970. * MIT Licensed
  3971. *)
  3972. http-errors/index.js:
  3973. (*!
  3974. * http-errors
  3975. * Copyright(c) 2014 Jonathan Ong
  3976. * Copyright(c) 2016 Douglas Christopher Wilson
  3977. * MIT Licensed
  3978. *)
  3979. */