index.cjs 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694
  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. BodyParser: () => BodyParser,
  1823. CookieParser: () => CookieParser,
  1824. DataSender: () => DataSender,
  1825. EXPOSED_ERROR_PROPERTIES: () => EXPOSED_ERROR_PROPERTIES,
  1826. ErrorSender: () => ErrorSender,
  1827. HOOK_NAME: () => HOOK_NAME,
  1828. HookInvoker: () => HookInvoker,
  1829. HookRegistry: () => HookRegistry,
  1830. HttpMethod: () => HttpMethod,
  1831. METHODS_WITH_BODY: () => METHODS_WITH_BODY,
  1832. QueryParser: () => QueryParser,
  1833. RequestContext: () => RequestContext,
  1834. RequestParser: () => RequestParser,
  1835. Route: () => Route,
  1836. RouteRegistry: () => RouteRegistry,
  1837. RouterOptions: () => RouterOptions,
  1838. TrieRouter: () => TrieRouter,
  1839. UNPARSABLE_MEDIA_TYPES: () => UNPARSABLE_MEDIA_TYPES,
  1840. parseJsonBody: () => parseJsonBody
  1841. });
  1842. module.exports = __toCommonJS(src_exports);
  1843. // node_modules/@e22m4u/js-format/src/utils/is-class.js
  1844. function isClass(value) {
  1845. if (!value) return false;
  1846. return typeof value === "function" && /^class\s/.test(Function.prototype.toString.call(value));
  1847. }
  1848. // node_modules/@e22m4u/js-format/src/value-to-string.js
  1849. var BASE_CTOR_NAMES = [
  1850. "String",
  1851. "Number",
  1852. "Boolean",
  1853. "Object",
  1854. "Array",
  1855. "Function",
  1856. "Symbol",
  1857. "Map",
  1858. "Set",
  1859. "Date"
  1860. ];
  1861. function valueToString(input) {
  1862. if (input == null) return String(input);
  1863. if (typeof input === "string") return `"${input}"`;
  1864. if (typeof input === "number" || typeof input === "boolean")
  1865. return String(input);
  1866. if (isClass(input)) return input.name ? input.name : "Class";
  1867. if (input.constructor && input.constructor.name)
  1868. return BASE_CTOR_NAMES.includes(input.constructor.name) ? input.constructor.name : `${input.constructor.name} (instance)`;
  1869. if (typeof input === "object" && input.constructor == null) return "Object";
  1870. return String(input);
  1871. }
  1872. // node_modules/@e22m4u/js-format/src/array-to-list.js
  1873. var SEPARATOR = ", ";
  1874. function arrayToList(input) {
  1875. if (Array.isArray(input) && input.length)
  1876. return input.map(valueToString).join(SEPARATOR);
  1877. return valueToString(input);
  1878. }
  1879. // node_modules/@e22m4u/js-format/src/format.js
  1880. function format(pattern) {
  1881. if (pattern instanceof Date) {
  1882. pattern = pattern.toISOString();
  1883. } else if (typeof pattern !== "string") {
  1884. pattern = String(pattern);
  1885. }
  1886. const re = /(%?)(%([sdjvl]))/g;
  1887. const args = Array.prototype.slice.call(arguments, 1);
  1888. if (args.length) {
  1889. pattern = pattern.replace(re, function(match, escaped, ptn, flag) {
  1890. let arg = args.shift();
  1891. switch (flag) {
  1892. case "s":
  1893. arg = String(arg);
  1894. break;
  1895. case "d":
  1896. arg = Number(arg);
  1897. break;
  1898. case "j":
  1899. arg = JSON.stringify(arg);
  1900. break;
  1901. case "v":
  1902. arg = valueToString(arg);
  1903. break;
  1904. case "l":
  1905. arg = arrayToList(arg);
  1906. break;
  1907. }
  1908. if (!escaped) return arg;
  1909. args.unshift(arg);
  1910. return match;
  1911. });
  1912. }
  1913. if (args.length) pattern += " " + args.join(" ");
  1914. pattern = pattern.replace(/%{2}/g, "%");
  1915. return "" + pattern;
  1916. }
  1917. // node_modules/@e22m4u/js-format/src/errorf.js
  1918. var Errorf = class extends Error {
  1919. /**
  1920. * Constructor.
  1921. *
  1922. * @param {string|undefined} pattern
  1923. * @param {any} args
  1924. */
  1925. constructor(pattern = void 0, ...args) {
  1926. const message = pattern != null ? format(pattern, ...args) : void 0;
  1927. super(message);
  1928. }
  1929. };
  1930. // src/utils/is-promise.js
  1931. function isPromise(value) {
  1932. if (!value) return false;
  1933. if (typeof value !== "object") return false;
  1934. return typeof value.then === "function";
  1935. }
  1936. // src/utils/parse-cookie.js
  1937. function parseCookie(input) {
  1938. if (typeof input !== "string")
  1939. throw new Errorf(
  1940. 'The first parameter of "parseCookie" should be a String, but %v given.',
  1941. input
  1942. );
  1943. return input.split(";").filter((v) => v !== "").map((v) => v.split("=")).reduce((cookies, tuple) => {
  1944. const key = decodeURIComponent(tuple[0]).trim();
  1945. cookies[key] = decodeURIComponent(tuple[1]).trim();
  1946. return cookies;
  1947. }, {});
  1948. }
  1949. // src/utils/create-error.js
  1950. function createError(errorCtor, message, ...args) {
  1951. if (typeof errorCtor !== "function")
  1952. throw new Errorf(
  1953. 'The first argument of "createError" should be a constructor, but %v given.',
  1954. errorCtor
  1955. );
  1956. if (message != null && typeof message !== "string")
  1957. throw new Errorf(
  1958. 'The second argument of "createError" should be a String, but %v given.',
  1959. message
  1960. );
  1961. if (message == null) return new errorCtor();
  1962. const interpolatedMessage = format(message, ...args);
  1963. return new errorCtor(interpolatedMessage);
  1964. }
  1965. // src/utils/to-camel-case.js
  1966. function toCamelCase(input) {
  1967. if (typeof input !== "string")
  1968. throw new Errorf(
  1969. 'The first argument of "toCamelCase" should be a String, but %v given.',
  1970. input
  1971. );
  1972. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  1973. }
  1974. // src/utils/create-debugger.js
  1975. var import_debug = __toESM(require_src(), 1);
  1976. function createDebugger(name) {
  1977. if (typeof name !== "string")
  1978. throw new Errorf(
  1979. 'The first argument of "createDebugger" should be a String, but %v given.',
  1980. name
  1981. );
  1982. const debug3 = (0, import_debug.default)(`jsTrieRouter:${name}`);
  1983. return function(message, ...args) {
  1984. const interpolatedMessage = format(message, ...args);
  1985. return debug3(interpolatedMessage);
  1986. };
  1987. }
  1988. // src/utils/is-response-sent.js
  1989. function isResponseSent(res) {
  1990. if (!res || typeof res !== "object" || Array.isArray(res) || typeof res.headersSent !== "boolean") {
  1991. throw new Errorf(
  1992. 'The first argument of "isResponseSent" should be an instance of ServerResponse, but %v given.',
  1993. res
  1994. );
  1995. }
  1996. return res.headersSent;
  1997. }
  1998. // src/utils/is-readable-stream.js
  1999. function isReadableStream(value) {
  2000. if (!value || typeof value !== "object") return false;
  2001. return typeof value.pipe === "function";
  2002. }
  2003. // src/utils/is-writable-stream.js
  2004. function isWritableStream(value) {
  2005. if (!value || typeof value !== "object") return false;
  2006. return typeof value.end === "function";
  2007. }
  2008. // src/utils/fetch-request-body.js
  2009. var import_http_errors = __toESM(require_http_errors(), 1);
  2010. // src/utils/parse-content-type.js
  2011. function parseContentType(input) {
  2012. if (typeof input !== "string")
  2013. throw new Errorf(
  2014. 'The parameter "input" of "parseContentType" should be a String, but %v given.',
  2015. input
  2016. );
  2017. const res = { mediaType: void 0, charset: void 0, boundary: void 0 };
  2018. const re = /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  2019. const matches = re.exec(input);
  2020. if (matches && matches[1]) {
  2021. res.mediaType = matches[1];
  2022. if (matches[2]) res.charset = matches[2];
  2023. if (matches[3]) res.boundary = matches[3];
  2024. }
  2025. return res;
  2026. }
  2027. // src/utils/fetch-request-body.js
  2028. var import_http = require("http");
  2029. var BUFFER_ENCODING_LIST = [
  2030. "ascii",
  2031. "utf8",
  2032. "utf-8",
  2033. "utf16le",
  2034. "utf-16le",
  2035. "ucs2",
  2036. "ucs-2",
  2037. "base64",
  2038. "base64url",
  2039. "latin1",
  2040. "binary",
  2041. "hex"
  2042. ];
  2043. function fetchRequestBody(req, bodyBytesLimit = 0) {
  2044. if (!(req instanceof import_http.IncomingMessage))
  2045. throw new Errorf(
  2046. 'The first parameter of "fetchRequestBody" should be an IncomingMessage instance, but %v given.',
  2047. req
  2048. );
  2049. if (typeof bodyBytesLimit !== "number")
  2050. throw new Errorf(
  2051. 'The parameter "bodyBytesLimit" of "fetchRequestBody" should be a number, but %v given.',
  2052. bodyBytesLimit
  2053. );
  2054. return new Promise((resolve, reject) => {
  2055. const contentLength = parseInt(req.headers["content-length"] || "0", 10);
  2056. if (bodyBytesLimit && contentLength && contentLength > bodyBytesLimit)
  2057. throw createError(
  2058. import_http_errors.default.PayloadTooLarge,
  2059. "Request body limit is %s bytes, but %s bytes given.",
  2060. bodyBytesLimit,
  2061. contentLength
  2062. );
  2063. let encoding = "utf-8";
  2064. const contentType = req.headers["content-type"] || "";
  2065. if (contentType) {
  2066. const parsedContentType = parseContentType(contentType);
  2067. if (parsedContentType && parsedContentType.charset) {
  2068. encoding = parsedContentType.charset.toLowerCase();
  2069. if (!BUFFER_ENCODING_LIST.includes(encoding))
  2070. throw createError(
  2071. import_http_errors.default.UnsupportedMediaType,
  2072. "Request encoding %v is not supported.",
  2073. encoding
  2074. );
  2075. }
  2076. }
  2077. const data = [];
  2078. let receivedLength = 0;
  2079. const onData = (chunk) => {
  2080. receivedLength += chunk.length;
  2081. if (bodyBytesLimit && receivedLength > bodyBytesLimit) {
  2082. req.removeAllListeners();
  2083. const error = createError(
  2084. import_http_errors.default.PayloadTooLarge,
  2085. "Request body limit is %v bytes, but %v bytes given.",
  2086. bodyBytesLimit,
  2087. receivedLength
  2088. );
  2089. reject(error);
  2090. return;
  2091. }
  2092. data.push(chunk);
  2093. };
  2094. const onEnd = () => {
  2095. req.removeAllListeners();
  2096. if (contentLength && contentLength !== receivedLength) {
  2097. const error = createError(
  2098. import_http_errors.default.BadRequest,
  2099. 'Received bytes do not match the "content-length" header.'
  2100. );
  2101. reject(error);
  2102. return;
  2103. }
  2104. const buffer = Buffer.concat(data);
  2105. const body = Buffer.from(buffer, encoding).toString();
  2106. resolve(body || void 0);
  2107. };
  2108. const onError = (error) => {
  2109. req.removeAllListeners();
  2110. reject((0, import_http_errors.default)(400, error));
  2111. };
  2112. req.on("data", onData);
  2113. req.on("end", onEnd);
  2114. req.on("error", onError);
  2115. req.resume();
  2116. });
  2117. }
  2118. // src/utils/get-request-pathname.js
  2119. function getRequestPathname(req) {
  2120. if (!req || typeof req !== "object" || Array.isArray(req) || typeof req.url !== "string") {
  2121. throw new Errorf(
  2122. 'The first argument of "getRequestPathname" should be an instance of IncomingMessage, but %v given.',
  2123. req
  2124. );
  2125. }
  2126. return (req.url || "/").replace(/\?.*$/, "");
  2127. }
  2128. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  2129. var InvalidArgumentError = class extends Errorf {
  2130. };
  2131. // node_modules/@e22m4u/js-service/src/service-container.js
  2132. var ServiceContainer = class _ServiceContainer {
  2133. /**
  2134. * Services map.
  2135. *
  2136. * @type {Map<any, any>}
  2137. * @private
  2138. */
  2139. _services = /* @__PURE__ */ new Map();
  2140. /**
  2141. * Parent container.
  2142. *
  2143. * @type {ServiceContainer}
  2144. * @private
  2145. */
  2146. _parent;
  2147. /**
  2148. * Constructor.
  2149. *
  2150. * @param {ServiceContainer|undefined} parent
  2151. */
  2152. constructor(parent = void 0) {
  2153. if (parent != null) {
  2154. if (!(parent instanceof _ServiceContainer))
  2155. throw new InvalidArgumentError(
  2156. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  2157. parent
  2158. );
  2159. this._parent = parent;
  2160. }
  2161. }
  2162. /**
  2163. * Получить существующий или новый экземпляр.
  2164. *
  2165. * @param {*} ctor
  2166. * @param {*} args
  2167. * @return {*}
  2168. */
  2169. get(ctor, ...args) {
  2170. if (!ctor || typeof ctor !== "function")
  2171. throw new InvalidArgumentError(
  2172. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  2173. ctor
  2174. );
  2175. if (!this._services.has(ctor) && this._parent && this._parent.has(ctor)) {
  2176. return this._parent.get(ctor);
  2177. }
  2178. let service = this._services.get(ctor);
  2179. if (!service || args.length) {
  2180. service = "prototype" in ctor && ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2181. this._services.set(ctor, service);
  2182. } else if (typeof service === "function") {
  2183. service = service();
  2184. this._services.set(ctor, service);
  2185. }
  2186. return service;
  2187. }
  2188. /**
  2189. * Проверка существования конструктора в контейнере.
  2190. *
  2191. * @param {*} ctor
  2192. * @return {boolean}
  2193. */
  2194. has(ctor) {
  2195. if (this._services.has(ctor)) return true;
  2196. if (this._parent) return this._parent.has(ctor);
  2197. return false;
  2198. }
  2199. /**
  2200. * Добавить конструктор в контейнер.
  2201. *
  2202. * @param {*} ctor
  2203. * @param {*} args
  2204. * @return {this}
  2205. */
  2206. add(ctor, ...args) {
  2207. if (!ctor || typeof ctor !== "function")
  2208. throw new InvalidArgumentError(
  2209. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  2210. ctor
  2211. );
  2212. const factory = () => ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2213. this._services.set(ctor, factory);
  2214. return this;
  2215. }
  2216. /**
  2217. * Добавить конструктор и создать экземпляр.
  2218. *
  2219. * @param {*} ctor
  2220. * @param {*} args
  2221. * @return {this}
  2222. */
  2223. use(ctor, ...args) {
  2224. if (!ctor || typeof ctor !== "function")
  2225. throw new InvalidArgumentError(
  2226. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  2227. ctor
  2228. );
  2229. const service = ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  2230. this._services.set(ctor, service);
  2231. return this;
  2232. }
  2233. /**
  2234. * Добавить конструктор и связанный экземпляр.
  2235. *
  2236. * @param {*} ctor
  2237. * @param {*} service
  2238. * @return {this}
  2239. */
  2240. set(ctor, service) {
  2241. if (!ctor || typeof ctor !== "function")
  2242. throw new InvalidArgumentError(
  2243. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  2244. ctor
  2245. );
  2246. if (!service || typeof service !== "object" || Array.isArray(service))
  2247. throw new InvalidArgumentError(
  2248. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  2249. service
  2250. );
  2251. this._services.set(ctor, service);
  2252. return this;
  2253. }
  2254. };
  2255. // node_modules/@e22m4u/js-service/src/service.js
  2256. var Service = class {
  2257. /**
  2258. * Container.
  2259. *
  2260. * @type {ServiceContainer}
  2261. */
  2262. container;
  2263. /**
  2264. * Constructor.
  2265. *
  2266. * @param {ServiceContainer|undefined} container
  2267. */
  2268. constructor(container = void 0) {
  2269. this.container = container instanceof ServiceContainer ? container : new ServiceContainer();
  2270. }
  2271. /**
  2272. * Получить существующий или новый экземпляр.
  2273. *
  2274. * @param {*} ctor
  2275. * @param {*} args
  2276. * @return {*}
  2277. */
  2278. getService(ctor, ...args) {
  2279. return this.container.get(ctor, ...args);
  2280. }
  2281. /**
  2282. * Проверка существования конструктора в контейнере.
  2283. *
  2284. * @param {*} ctor
  2285. * @return {boolean}
  2286. */
  2287. hasService(ctor) {
  2288. return this.container.has(ctor);
  2289. }
  2290. /**
  2291. * Добавить конструктор в контейнер.
  2292. *
  2293. * @param {*} ctor
  2294. * @param {*} args
  2295. * @return {this}
  2296. */
  2297. addService(ctor, ...args) {
  2298. this.container.add(ctor, ...args);
  2299. return this;
  2300. }
  2301. /**
  2302. * Добавить конструктор и создать экземпляр.
  2303. *
  2304. * @param {*} ctor
  2305. * @param {*} args
  2306. * @return {this}
  2307. */
  2308. useService(ctor, ...args) {
  2309. this.container.use(ctor, ...args);
  2310. return this;
  2311. }
  2312. /**
  2313. * Добавить конструктор и связанный экземпляр.
  2314. *
  2315. * @param {*} ctor
  2316. * @param {*} service
  2317. * @return {this}
  2318. */
  2319. setService(ctor, service) {
  2320. this.container.set(ctor, service);
  2321. return this;
  2322. }
  2323. };
  2324. // src/debuggable-service.js
  2325. var DebuggableService = class extends Service {
  2326. /**
  2327. * Debug.
  2328. *
  2329. * @type {Function}
  2330. */
  2331. debug;
  2332. /**
  2333. * Constructor.
  2334. *
  2335. * @param {ServiceContainer} container
  2336. */
  2337. constructor(container) {
  2338. super(container);
  2339. const serviceName = toCamelCase(this.constructor.name);
  2340. this.debug = createDebugger(serviceName);
  2341. this.debug("The %v is created.", this.constructor);
  2342. }
  2343. };
  2344. // src/hooks/hook-registry.js
  2345. var HOOK_NAME = {
  2346. PRE_HANDLER: "preHandler",
  2347. POST_HANDLER: "postHandler"
  2348. };
  2349. var HookRegistry = class extends DebuggableService {
  2350. /**
  2351. * Hooks.
  2352. *
  2353. * @type {Map<string, Function[]>}
  2354. * @private
  2355. */
  2356. _hooks = /* @__PURE__ */ new Map();
  2357. /**
  2358. * Add hook.
  2359. *
  2360. * @param {string} name
  2361. * @param {Function} hook
  2362. * @returns {this}
  2363. */
  2364. addHook(name, hook) {
  2365. if (!name || typeof name !== "string")
  2366. throw new Errorf("The hook name is required, but %v given.", name);
  2367. if (!Object.values(HOOK_NAME).includes(name))
  2368. throw new Errorf("The hook name %v is not supported.", name);
  2369. if (!hook || typeof hook !== "function")
  2370. throw new Errorf(
  2371. "The hook %v should be a Function, but %v given.",
  2372. name,
  2373. hook
  2374. );
  2375. const hooks = this._hooks.get(name) || [];
  2376. hooks.push(hook);
  2377. this._hooks.set(name, hooks);
  2378. return this;
  2379. }
  2380. /**
  2381. * Has hook.
  2382. *
  2383. * @param {string} name
  2384. * @param {Function} hook
  2385. * @returns {boolean}
  2386. */
  2387. hasHook(name, hook) {
  2388. if (!name || typeof name !== "string")
  2389. throw new Errorf("The hook name is required, but %v given.", name);
  2390. if (!Object.values(HOOK_NAME).includes(name))
  2391. throw new Errorf("The hook name %v is not supported.", name);
  2392. if (!hook || typeof hook !== "function")
  2393. throw new Errorf(
  2394. "The hook %v should be a Function, but %v given.",
  2395. name,
  2396. hook
  2397. );
  2398. const hooks = this._hooks.get(name) || [];
  2399. return hooks.indexOf(hook) > -1;
  2400. }
  2401. /**
  2402. * Get hooks.
  2403. *
  2404. * @param {string} name
  2405. * @returns {Function[]}
  2406. */
  2407. getHooks(name) {
  2408. if (!name || typeof name !== "string")
  2409. throw new Errorf("The hook name is required, but %v given.", name);
  2410. if (!Object.values(HOOK_NAME).includes(name))
  2411. throw new Errorf("The hook name %v is not supported.", name);
  2412. return this._hooks.get(name) || [];
  2413. }
  2414. };
  2415. // src/hooks/hook-invoker.js
  2416. var HookInvoker = class extends DebuggableService {
  2417. /**
  2418. * Invoke and continue until value received.
  2419. *
  2420. * @param {Route} route
  2421. * @param {string} hookName
  2422. * @param {import('http').ServerResponse} response
  2423. * @param {*[]} args
  2424. * @returns {Promise<*>|*}
  2425. */
  2426. invokeAndContinueUntilValueReceived(route, hookName, response, ...args) {
  2427. if (!route || !(route instanceof Route))
  2428. throw new Errorf(
  2429. 'The parameter "route" of the HookInvoker.invokeAndContinueUntilValueReceived should be a Route instance, but %v given.',
  2430. route
  2431. );
  2432. if (!hookName || typeof hookName !== "string")
  2433. throw new Errorf(
  2434. 'The parameter "hookName" of the HookInvoker.invokeAndContinueUntilValueReceived should be a non-empty String, but %v given.',
  2435. hookName
  2436. );
  2437. if (!Object.values(HOOK_NAME).includes(hookName))
  2438. throw new Errorf("The hook name %v is not supported.", hookName);
  2439. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  2440. throw new Errorf(
  2441. 'The parameter "response" of the HookInvoker.invokeAndContinueUntilValueReceived should be a ServerResponse instance, but %v given.',
  2442. response
  2443. );
  2444. }
  2445. const hooks = [
  2446. ...this.getService(HookRegistry).getHooks(hookName),
  2447. ...route.hookRegistry.getHooks(hookName)
  2448. ];
  2449. let result = void 0;
  2450. for (const hook of hooks) {
  2451. if (isResponseSent(response)) {
  2452. result = response;
  2453. break;
  2454. }
  2455. if (result == null) {
  2456. result = hook(...args);
  2457. } else if (isPromise(result)) {
  2458. result = result.then((prevVal) => {
  2459. if (isResponseSent(response)) {
  2460. result = response;
  2461. return;
  2462. }
  2463. if (prevVal != null) return prevVal;
  2464. return hook(...args);
  2465. });
  2466. } else {
  2467. break;
  2468. }
  2469. }
  2470. return result;
  2471. }
  2472. };
  2473. // src/route.js
  2474. var HttpMethod = {
  2475. GET: "GET",
  2476. POST: "POST",
  2477. PUT: "PUT",
  2478. PATCH: "PATCH",
  2479. DELETE: "DELETE"
  2480. };
  2481. var debug = createDebugger("route");
  2482. var Route = class {
  2483. /**
  2484. * Method.
  2485. *
  2486. * @type {string}
  2487. * @private
  2488. */
  2489. _method;
  2490. /**
  2491. * Getter of the method.
  2492. *
  2493. * @returns {string}
  2494. */
  2495. get method() {
  2496. return this._method;
  2497. }
  2498. /**
  2499. * Path template.
  2500. *
  2501. * @type {string}
  2502. * @private
  2503. */
  2504. _path;
  2505. /**
  2506. * Getter of the path.
  2507. *
  2508. * @returns {string}
  2509. */
  2510. get path() {
  2511. return this._path;
  2512. }
  2513. /**
  2514. * Handler.
  2515. *
  2516. * @type {RouteHandler}
  2517. * @private
  2518. */
  2519. _handler;
  2520. /**
  2521. * Getter of the handler.
  2522. *
  2523. * @returns {*}
  2524. */
  2525. get handler() {
  2526. return this._handler;
  2527. }
  2528. /**
  2529. * Hook registry.
  2530. *
  2531. * @type {HookRegistry}
  2532. * @private
  2533. */
  2534. _hookRegistry = new HookRegistry();
  2535. /**
  2536. * Getter of the hook registry.
  2537. *
  2538. * @returns {HookRegistry}
  2539. */
  2540. get hookRegistry() {
  2541. return this._hookRegistry;
  2542. }
  2543. /**
  2544. * Constructor.
  2545. *
  2546. * @param {RouteDefinition} routeDef
  2547. */
  2548. constructor(routeDef) {
  2549. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  2550. throw new Errorf(
  2551. "The first parameter of Route.controller should be an Object, but %v given.",
  2552. routeDef
  2553. );
  2554. if (!routeDef.method || typeof routeDef.method !== "string")
  2555. throw new Errorf(
  2556. 'The option "method" of the Route should be a non-empty String, but %v given.',
  2557. routeDef.method
  2558. );
  2559. this._method = routeDef.method.toUpperCase();
  2560. if (typeof routeDef.path !== "string")
  2561. throw new Errorf(
  2562. 'The option "path" of the Route should be a String, but %v given.',
  2563. routeDef.path
  2564. );
  2565. this._path = routeDef.path;
  2566. if (typeof routeDef.handler !== "function")
  2567. throw new Errorf(
  2568. 'The option "handler" of the Route should be a Function, but %v given.',
  2569. routeDef.handler
  2570. );
  2571. this._handler = routeDef.handler;
  2572. if (routeDef.preHandler != null) {
  2573. const preHandlerHooks = Array.isArray(routeDef.preHandler) ? routeDef.preHandler : [routeDef.preHandler];
  2574. preHandlerHooks.forEach((hook) => {
  2575. this._hookRegistry.addHook(HOOK_NAME.PRE_HANDLER, hook);
  2576. });
  2577. }
  2578. if (routeDef.postHandler != null) {
  2579. const postHandlerHooks = Array.isArray(routeDef.postHandler) ? routeDef.postHandler : [routeDef.postHandler];
  2580. postHandlerHooks.forEach((hook) => {
  2581. this._hookRegistry.addHook(HOOK_NAME.POST_HANDLER, hook);
  2582. });
  2583. }
  2584. }
  2585. /**
  2586. * Handle request.
  2587. *
  2588. * @param {RequestContext} context
  2589. * @returns {*}
  2590. */
  2591. handle(context) {
  2592. const requestPath = getRequestPathname(context.req);
  2593. debug(
  2594. "Invoking the Route handler for the request %s %v.",
  2595. this.method.toUpperCase(),
  2596. requestPath
  2597. );
  2598. return this._handler(context);
  2599. }
  2600. };
  2601. // src/senders/data-sender.js
  2602. var DataSender = class extends DebuggableService {
  2603. /**
  2604. * Send.
  2605. *
  2606. * @param {import('http').ServerResponse} res
  2607. * @param {*} data
  2608. * @returns {undefined}
  2609. */
  2610. send(res, data) {
  2611. if (data === res || res.headersSent) {
  2612. this.debug(
  2613. "Response sending was skipped because its headers where sent already ."
  2614. );
  2615. return;
  2616. }
  2617. if (data == null) {
  2618. res.statusCode = 204;
  2619. res.end();
  2620. this.debug("The empty response was sent.");
  2621. return;
  2622. }
  2623. if (isReadableStream(data)) {
  2624. res.setHeader("Content-Type", "application/octet-stream");
  2625. data.pipe(res);
  2626. this.debug("The stream response was sent.");
  2627. return;
  2628. }
  2629. let debugMsg;
  2630. switch (typeof data) {
  2631. case "object":
  2632. case "boolean":
  2633. case "number":
  2634. if (Buffer.isBuffer(data)) {
  2635. res.setHeader("content-type", "application/octet-stream");
  2636. debugMsg = "The Buffer was sent as binary data.";
  2637. } else {
  2638. res.setHeader("content-type", "application/json");
  2639. debugMsg = format("The %v was sent as JSON.", typeof data);
  2640. data = JSON.stringify(data);
  2641. }
  2642. break;
  2643. default:
  2644. res.setHeader("content-type", "text/plain");
  2645. debugMsg = "The response data was sent as plain text.";
  2646. data = String(data);
  2647. break;
  2648. }
  2649. res.end(data);
  2650. this.debug(debugMsg);
  2651. }
  2652. };
  2653. // src/senders/error-sender.js
  2654. var import_util = require("util");
  2655. var import_statuses = __toESM(require_statuses(), 1);
  2656. var EXPOSED_ERROR_PROPERTIES = ["code", "details"];
  2657. var ErrorSender = class extends DebuggableService {
  2658. /**
  2659. * Handle.
  2660. *
  2661. * @param {import('http').IncomingMessage} req
  2662. * @param {import('http').ServerResponse} res
  2663. * @param {Error} error
  2664. * @returns {undefined}
  2665. */
  2666. send(req, res, error) {
  2667. let safeError = {};
  2668. if (error) {
  2669. if (typeof error === "object") {
  2670. safeError = error;
  2671. } else {
  2672. safeError = { message: String(error) };
  2673. }
  2674. }
  2675. const statusCode = error.statusCode || error.status || 500;
  2676. const body = { error: {} };
  2677. if (safeError.message && typeof safeError.message === "string") {
  2678. body.error.message = safeError.message;
  2679. } else {
  2680. body.error.message = (0, import_statuses.default)(statusCode);
  2681. }
  2682. EXPOSED_ERROR_PROPERTIES.forEach((name) => {
  2683. if (name in safeError) body.error[name] = safeError[name];
  2684. });
  2685. const requestData = {
  2686. url: req.url,
  2687. method: req.method,
  2688. headers: req.headers
  2689. };
  2690. const inspectOptions = {
  2691. showHidden: false,
  2692. depth: null,
  2693. colors: true,
  2694. compact: false
  2695. };
  2696. console.warn((0, import_util.inspect)(requestData, inspectOptions));
  2697. console.warn((0, import_util.inspect)(body, inspectOptions));
  2698. res.statusCode = statusCode;
  2699. res.setHeader("content-type", "application/json; charset=utf-8");
  2700. res.end(JSON.stringify(body, null, 2), "utf-8");
  2701. this.debug(
  2702. "The %s error is sent for the request %s %v.",
  2703. statusCode,
  2704. req.method,
  2705. getRequestPathname(req)
  2706. );
  2707. }
  2708. /**
  2709. * Send 404.
  2710. *
  2711. * @param {import('http').IncomingMessage} req
  2712. * @param {import('http').ServerResponse} res
  2713. * @returns {undefined}
  2714. */
  2715. send404(req, res) {
  2716. res.statusCode = 404;
  2717. res.setHeader("content-type", "text/plain; charset=utf-8");
  2718. res.end("404 Not Found", "utf-8");
  2719. this.debug(
  2720. "The 404 error is sent for the request %s %v.",
  2721. req.method,
  2722. getRequestPathname(req)
  2723. );
  2724. }
  2725. };
  2726. // src/parsers/body-parser.js
  2727. var import_http_errors2 = __toESM(require_http_errors(), 1);
  2728. // src/router-options.js
  2729. var RouterOptions = class extends DebuggableService {
  2730. /**
  2731. * Request body bytes limit.
  2732. *
  2733. * @type {number}
  2734. * @private
  2735. */
  2736. _requestBodyBytesLimit = 512e3;
  2737. // 512kb
  2738. /**
  2739. * Getter of request body bytes limit.
  2740. *
  2741. * @returns {number}
  2742. */
  2743. get requestBodyBytesLimit() {
  2744. return this._requestBodyBytesLimit;
  2745. }
  2746. /**
  2747. * Set request body bytes limit.
  2748. *
  2749. * @param {number} input
  2750. * @returns {RouterOptions}
  2751. */
  2752. setRequestBodyBytesLimit(input) {
  2753. if (typeof input !== "number" || input < 0)
  2754. throw new Errorf(
  2755. 'The option "requestBodyBytesLimit" must be a positive Number or 0, but %v given.',
  2756. input
  2757. );
  2758. this._requestBodyBytesLimit = input;
  2759. return this;
  2760. }
  2761. };
  2762. // src/parsers/body-parser.js
  2763. var METHODS_WITH_BODY = ["POST", "PUT", "PATCH", "DELETE"];
  2764. var UNPARSABLE_MEDIA_TYPES = ["multipart/form-data"];
  2765. var BodyParser = class extends DebuggableService {
  2766. /**
  2767. * Parsers.
  2768. *
  2769. * @type {{[mime: string]: Function}}
  2770. */
  2771. _parsers = {
  2772. "text/plain": (v) => String(v),
  2773. "application/json": parseJsonBody
  2774. };
  2775. /**
  2776. * Set parser.
  2777. *
  2778. * @param {string} mediaType
  2779. * @param {Function} parser
  2780. * @returns {this}
  2781. */
  2782. defineParser(mediaType, parser) {
  2783. if (!mediaType || typeof mediaType !== "string")
  2784. throw new Errorf(
  2785. 'The parameter "mediaType" of BodyParser.defineParser should be a non-empty String, but %v given.',
  2786. mediaType
  2787. );
  2788. if (!parser || typeof parser !== "function")
  2789. throw new Errorf(
  2790. 'The parameter "parser" of BodyParser.defineParser should be a Function, but %v given.',
  2791. parser
  2792. );
  2793. this._parsers[mediaType] = parser;
  2794. return this;
  2795. }
  2796. /**
  2797. * Has parser.
  2798. *
  2799. * @param {string} mediaType
  2800. * @returns {boolean}
  2801. */
  2802. hasParser(mediaType) {
  2803. if (!mediaType || typeof mediaType !== "string")
  2804. throw new Errorf(
  2805. 'The parameter "mediaType" of BodyParser.hasParser should be a non-empty String, but %v given.',
  2806. mediaType
  2807. );
  2808. return Boolean(this._parsers[mediaType]);
  2809. }
  2810. /**
  2811. * Delete parser.
  2812. *
  2813. * @param {string} mediaType
  2814. * @returns {this}
  2815. */
  2816. deleteParser(mediaType) {
  2817. if (!mediaType || typeof mediaType !== "string")
  2818. throw new Errorf(
  2819. 'The parameter "mediaType" of BodyParser.deleteParser should be a non-empty String, but %v given.',
  2820. mediaType
  2821. );
  2822. const parser = this._parsers[mediaType];
  2823. if (!parser) throw new Errorf("The parser of %v is not found.", mediaType);
  2824. delete this._parsers[mediaType];
  2825. return this;
  2826. }
  2827. /**
  2828. * Parse.
  2829. *
  2830. * @param {import('http').IncomingMessage} req
  2831. * @returns {Promise<*>|undefined}
  2832. */
  2833. parse(req) {
  2834. if (!METHODS_WITH_BODY.includes(req.method.toUpperCase())) {
  2835. this.debug(
  2836. "Body parsing was skipped for the %s request.",
  2837. req.method.toUpperCase()
  2838. );
  2839. return;
  2840. }
  2841. const contentType = (req.headers["content-type"] || "").replace(
  2842. /^([^;]+);.*$/,
  2843. "$1"
  2844. );
  2845. if (!contentType) {
  2846. this.debug(
  2847. "Body parsing was skipped because the request has no content type."
  2848. );
  2849. return;
  2850. }
  2851. const { mediaType } = parseContentType(contentType);
  2852. if (!mediaType)
  2853. throw createError(
  2854. import_http_errors2.default.BadRequest,
  2855. 'Unable to parse the "content-type" header.'
  2856. );
  2857. const parser = this._parsers[mediaType];
  2858. if (!parser) {
  2859. if (UNPARSABLE_MEDIA_TYPES.includes(mediaType)) {
  2860. this.debug("Body parsing was skipped for %v.", mediaType);
  2861. return;
  2862. }
  2863. throw createError(
  2864. import_http_errors2.default.UnsupportedMediaType,
  2865. "Media type %v is not supported.",
  2866. mediaType
  2867. );
  2868. }
  2869. const bodyBytesLimit = this.getService(RouterOptions).requestBodyBytesLimit;
  2870. return fetchRequestBody(req, bodyBytesLimit).then((rawBody) => {
  2871. if (rawBody != null) return parser(rawBody);
  2872. return rawBody;
  2873. });
  2874. }
  2875. };
  2876. function parseJsonBody(input) {
  2877. if (typeof input !== "string") return void 0;
  2878. try {
  2879. return JSON.parse(input);
  2880. } catch (error) {
  2881. if (process.env["DEBUG"] || process.env["NODE_ENV"] === "development")
  2882. console.warn(error);
  2883. throw createError(import_http_errors2.default.BadRequest, "Unable to parse request body.");
  2884. }
  2885. }
  2886. // src/parsers/query-parser.js
  2887. var import_querystring = __toESM(require("querystring"), 1);
  2888. var QueryParser = class extends DebuggableService {
  2889. /**
  2890. * Parse
  2891. *
  2892. * @param {import('http').IncomingMessage} req
  2893. * @returns {object}
  2894. */
  2895. parse(req) {
  2896. const queryStr = req.url.replace(/^[^?]*\??/, "");
  2897. const query = queryStr ? import_querystring.default.parse(queryStr) : {};
  2898. const queryKeys = Object.keys(query);
  2899. if (queryKeys.length) {
  2900. queryKeys.forEach((key) => {
  2901. this.debug("The query %v has the value %v.", key, query[key]);
  2902. });
  2903. } else {
  2904. this.debug(
  2905. "The request %s %v has no query.",
  2906. req.method,
  2907. getRequestPathname(req)
  2908. );
  2909. }
  2910. return query;
  2911. }
  2912. };
  2913. // src/parsers/cookie-parser.js
  2914. var CookieParser = class extends DebuggableService {
  2915. /**
  2916. * Parse
  2917. *
  2918. * @param {import('http').IncomingMessage} req
  2919. * @returns {object}
  2920. */
  2921. parse(req) {
  2922. const cookieString = req.headers["cookie"] || "";
  2923. const cookie = parseCookie(cookieString);
  2924. const cookieKeys = Object.keys(cookie);
  2925. if (cookieKeys.length) {
  2926. cookieKeys.forEach((key) => {
  2927. this.debug("The cookie %v has the value %v.", key, cookie[key]);
  2928. });
  2929. } else {
  2930. this.debug(
  2931. "The request %s %v has no cookie.",
  2932. req.method,
  2933. getRequestPathname(req)
  2934. );
  2935. }
  2936. return cookie;
  2937. }
  2938. };
  2939. // src/parsers/request-parser.js
  2940. var import_http2 = require("http");
  2941. var RequestParser = class extends DebuggableService {
  2942. /**
  2943. * Parse.
  2944. *
  2945. * @param {IncomingMessage} req
  2946. * @returns {Promise<object>|object}
  2947. */
  2948. parse(req) {
  2949. if (!(req instanceof import_http2.IncomingMessage))
  2950. throw new Errorf(
  2951. "The first argument of RequestParser.parse should be an instance of IncomingMessage, but %v given.",
  2952. req
  2953. );
  2954. const data = {};
  2955. const promises = [];
  2956. const parsedQuery = this.getService(QueryParser).parse(req);
  2957. if (isPromise(parsedQuery)) {
  2958. promises.push(parsedQuery.then((v) => data.query = v));
  2959. } else {
  2960. data.query = parsedQuery;
  2961. }
  2962. const parsedCookie = this.getService(CookieParser).parse(req);
  2963. if (isPromise(parsedCookie)) {
  2964. promises.push(parsedCookie.then((v) => data.cookie = v));
  2965. } else {
  2966. data.cookie = parsedCookie;
  2967. }
  2968. const parsedBody = this.getService(BodyParser).parse(req);
  2969. if (isPromise(parsedBody)) {
  2970. promises.push(parsedBody.then((v) => data.body = v));
  2971. } else {
  2972. data.body = parsedBody;
  2973. }
  2974. data.headers = JSON.parse(JSON.stringify(req.headers));
  2975. return promises.length ? Promise.all(promises).then(() => data) : data;
  2976. }
  2977. };
  2978. // node_modules/@e22m4u/js-path-trie/src/path-trie.js
  2979. var import_path_to_regexp = __toESM(require_dist(), 1);
  2980. // node_modules/@e22m4u/js-path-trie/src/utils/create-debugger.js
  2981. var import_debug2 = __toESM(require_src(), 1);
  2982. function createDebugger2() {
  2983. const debug3 = (0, import_debug2.default)(`jsPathTrie`);
  2984. return function(message, ...args) {
  2985. const interpolatedMessage = format(message, ...args);
  2986. return debug3(interpolatedMessage);
  2987. };
  2988. }
  2989. // node_modules/@e22m4u/js-path-trie/src/path-trie.js
  2990. var debug2 = createDebugger2();
  2991. var PathTrie = class {
  2992. /**
  2993. * Root node.
  2994. *
  2995. * @type {Node}
  2996. * @private
  2997. */
  2998. _root = {
  2999. token: "",
  3000. regexp: void 0,
  3001. names: [],
  3002. value: void 0,
  3003. children: {}
  3004. };
  3005. /**
  3006. * Add value.
  3007. *
  3008. * @param {string} pathTemplate
  3009. * @param {*} value
  3010. * @returns {this}
  3011. */
  3012. add(pathTemplate, value) {
  3013. if (typeof pathTemplate !== "string")
  3014. throw new Errorf(
  3015. "The first argument of PathTrie.add should be a String, but %v given.",
  3016. pathTemplate
  3017. );
  3018. if (value == null)
  3019. throw new Errorf(
  3020. "The second argument of PathTrie.add is required, but %v given.",
  3021. value
  3022. );
  3023. debug2("Adding the value to %v.", pathTemplate);
  3024. const tokens = pathTemplate.split("/").filter(Boolean);
  3025. this._createNode(tokens, 0, value, this._root);
  3026. return this;
  3027. }
  3028. /**
  3029. * Match value.
  3030. *
  3031. * @param {string} path
  3032. * @returns {ResolvedValue|undefined}
  3033. */
  3034. match(path) {
  3035. if (typeof path !== "string")
  3036. throw new Errorf(
  3037. "The first argument of PathTrie.match should be a String, but %v given.",
  3038. path
  3039. );
  3040. debug2("Matching a value with the path %v.", path);
  3041. const tokens = path.split("/").filter(Boolean);
  3042. const params = {};
  3043. const result = this._matchNode(tokens, 0, params, this._root);
  3044. if (!result || !result.node.value) return;
  3045. return { value: result.node.value, params };
  3046. }
  3047. /**
  3048. * Create node.
  3049. *
  3050. * @param {string[]} tokens
  3051. * @param {number} index
  3052. * @param {*} value
  3053. * @param {Node} parent
  3054. * @returns {Node}
  3055. * @private
  3056. */
  3057. _createNode(tokens, index, value, parent) {
  3058. if (tokens.length === 0 && index === 0) {
  3059. if (parent.value == null) {
  3060. parent.value = value;
  3061. } else if (parent.value !== value) {
  3062. throw new Errorf('The duplicate path "" has a different value.');
  3063. }
  3064. debug2("The value has set to the root node.");
  3065. return parent;
  3066. }
  3067. const token = tokens[index];
  3068. if (token == null)
  3069. throw new Errorf(
  3070. "Invalid index %v has passed to the PathTrie._createNode.",
  3071. index
  3072. );
  3073. const isLast = tokens.length - 1 === index;
  3074. let child = parent.children[token];
  3075. if (isLast && child != null) {
  3076. debug2("The node %v already exist.", token);
  3077. if (child.value == null) {
  3078. child.value = value;
  3079. } else if (child.value !== value) {
  3080. throw new Errorf(
  3081. "The duplicate path %v has a different value.",
  3082. "/" + tokens.join("/")
  3083. );
  3084. }
  3085. return child;
  3086. }
  3087. debug2("The node %v does not exist.", token);
  3088. child = {
  3089. token,
  3090. regexp: void 0,
  3091. names: [],
  3092. value: void 0,
  3093. children: {}
  3094. };
  3095. if (isLast) {
  3096. debug2("The node %v is last.", token);
  3097. child.value = value;
  3098. }
  3099. if (token.indexOf(":") > -1) {
  3100. debug2("The node %v has parameters.", token);
  3101. const modifiers = /([?*+{}])/.exec(token);
  3102. if (modifiers)
  3103. throw new Errorf(
  3104. "The symbol %v is not supported in path %v.",
  3105. modifiers[0],
  3106. "/" + tokens.join("/")
  3107. );
  3108. let regexp, keys;
  3109. try {
  3110. const regexpAndKeys = (0, import_path_to_regexp.pathToRegexp)(token);
  3111. regexp = regexpAndKeys.regexp;
  3112. keys = regexpAndKeys.keys;
  3113. } catch (error) {
  3114. if (error.message.indexOf("Missing parameter") > -1)
  3115. throw new Errorf(
  3116. 'The symbol ":" should be used to define path parameters, but no parameters found in the path %v.',
  3117. "/" + tokens.join("/")
  3118. );
  3119. throw error;
  3120. }
  3121. if (Array.isArray(keys) && keys.length) {
  3122. child.names = keys.map((p) => `${p.name}`);
  3123. child.regexp = regexp;
  3124. } else {
  3125. throw new Errorf(
  3126. 'The symbol ":" should be used to define path parameters, but no parameters found in the path %v.',
  3127. "/" + tokens.join("/")
  3128. );
  3129. }
  3130. debug2("Found parameters are %l.", child.names);
  3131. }
  3132. parent.children[token] = child;
  3133. debug2("The node %v has created.", token);
  3134. if (isLast) return child;
  3135. return this._createNode(tokens, index + 1, value, child);
  3136. }
  3137. /**
  3138. * Match node.
  3139. *
  3140. * @param {string[]} tokens
  3141. * @param {number} index
  3142. * @param {object} params
  3143. * @param {Node} parent
  3144. * @returns {ResolvedNode|undefined}
  3145. * @private
  3146. */
  3147. _matchNode(tokens, index, params, parent) {
  3148. if (tokens.length === 0 && index === 0) {
  3149. if (parent.value) {
  3150. debug2(
  3151. "The path %v matched with the root node.",
  3152. "/" + tokens.join("/")
  3153. );
  3154. return { node: parent, params };
  3155. }
  3156. return;
  3157. }
  3158. const token = tokens[index];
  3159. if (token == null)
  3160. throw new Errorf(
  3161. "Invalid index %v has passed to the PathTrie._matchNode.",
  3162. index
  3163. );
  3164. const resolvedNodes = this._matchChildrenNodes(token, parent);
  3165. debug2("%v nodes matches the token %v.", resolvedNodes.length, token);
  3166. if (!resolvedNodes.length) return;
  3167. const isLast = tokens.length - 1 === index;
  3168. if (isLast) {
  3169. debug2("The token %v is last.", token);
  3170. for (const child of resolvedNodes) {
  3171. debug2("The node %v matches the token %v.", child.node.token, token);
  3172. if (child.node.value) {
  3173. debug2("The node %v has a value.", child.node.token);
  3174. const paramNames = Object.keys(child.params);
  3175. if (paramNames.length) {
  3176. paramNames.forEach((name) => {
  3177. debug2(
  3178. "The node %v has parameter %v with the value %v.",
  3179. child.node.token,
  3180. name,
  3181. child.params[name]
  3182. );
  3183. });
  3184. } else {
  3185. debug2("The node %v has no parameters.", child.node.token);
  3186. }
  3187. Object.assign(params, child.params);
  3188. return { node: child.node, params };
  3189. }
  3190. }
  3191. } else {
  3192. for (const child of resolvedNodes) {
  3193. const result = this._matchNode(tokens, index + 1, params, child.node);
  3194. if (result) {
  3195. debug2("A value has found for the path %v.", "/" + tokens.join("/"));
  3196. const paramNames = Object.keys(child.params);
  3197. if (paramNames.length) {
  3198. paramNames.forEach((name) => {
  3199. debug2(
  3200. "The node %v has parameter %v with the value %v.",
  3201. child.node.token,
  3202. name,
  3203. child.params[name]
  3204. );
  3205. });
  3206. } else {
  3207. debug2("The node %v has no parameters.", child.node.token);
  3208. }
  3209. Object.assign(params, child.params);
  3210. return result;
  3211. }
  3212. }
  3213. }
  3214. debug2("No matched nodes with the path %v.", "/" + tokens.join("/"));
  3215. return void 0;
  3216. }
  3217. /**
  3218. * Match children nodes.
  3219. *
  3220. * @param {string} token
  3221. * @param {Node} parent
  3222. * @returns {ResolvedNode[]}
  3223. * @private
  3224. */
  3225. _matchChildrenNodes(token, parent) {
  3226. const resolvedNodes = [];
  3227. let child = parent.children[token];
  3228. if (child) {
  3229. resolvedNodes.push({ node: child, params: {} });
  3230. return resolvedNodes;
  3231. }
  3232. for (const key in parent.children) {
  3233. child = parent.children[key];
  3234. if (!child.names || !child.regexp) continue;
  3235. const match = child.regexp.exec(token);
  3236. if (match) {
  3237. const resolved = { node: child, params: {} };
  3238. let i = 0;
  3239. for (const name of child.names) {
  3240. const val = match[++i];
  3241. resolved.params[name] = decodeURIComponent(val);
  3242. }
  3243. resolvedNodes.push(resolved);
  3244. }
  3245. }
  3246. return resolvedNodes;
  3247. }
  3248. };
  3249. // src/route-registry.js
  3250. var RouteRegistry = class extends DebuggableService {
  3251. /**
  3252. * Constructor.
  3253. *
  3254. * @param {ServiceContainer} container
  3255. */
  3256. constructor(container) {
  3257. super(container);
  3258. this._trie = new PathTrie();
  3259. }
  3260. /**
  3261. * Define route.
  3262. *
  3263. * @param {import('./route.js').RouteDefinition} routeDef
  3264. * @returns {Route}
  3265. */
  3266. defineRoute(routeDef) {
  3267. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  3268. throw new Errorf(
  3269. "The route definition should be an Object, but %v given.",
  3270. routeDef
  3271. );
  3272. const route = new Route(routeDef);
  3273. const triePath = `${route.method}/${route.path}`;
  3274. this._trie.add(triePath, route);
  3275. this.debug(
  3276. "The route %s %v is registered.",
  3277. route.method.toUpperCase(),
  3278. route.path
  3279. );
  3280. return route;
  3281. }
  3282. /**
  3283. * Match route by request.
  3284. *
  3285. * @param {import('http').IncomingRequest} req
  3286. * @returns {ResolvedRoute|undefined}
  3287. */
  3288. matchRouteByRequest(req) {
  3289. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  3290. this.debug(
  3291. "Matching %s %v with registered routes.",
  3292. req.method.toUpperCase(),
  3293. requestPath
  3294. );
  3295. const triePath = `${req.method.toUpperCase()}/${requestPath}`;
  3296. const resolved = this._trie.match(triePath);
  3297. if (resolved) {
  3298. const route = resolved.value;
  3299. this.debug(
  3300. "The request %s %v was matched to the route %s %v.",
  3301. req.method.toUpperCase(),
  3302. requestPath,
  3303. route.method.toUpperCase(),
  3304. route.path
  3305. );
  3306. const paramNames = Object.keys(resolved.params);
  3307. if (paramNames) {
  3308. paramNames.forEach((name) => {
  3309. this.debug(
  3310. "The path parameter %v has the value %v.",
  3311. name,
  3312. resolved.params[name]
  3313. );
  3314. });
  3315. } else {
  3316. this.debug("No path parameters found.");
  3317. }
  3318. return { route, params: resolved.params };
  3319. }
  3320. this.debug(
  3321. "No matched route for the request %s %v.",
  3322. req.method.toUpperCase(),
  3323. requestPath
  3324. );
  3325. }
  3326. };
  3327. // src/request-context.js
  3328. var RequestContext = class {
  3329. /**
  3330. * Service container.
  3331. *
  3332. * @type {import('@e22m4u/js-service').ServiceContainer}
  3333. */
  3334. container;
  3335. /**
  3336. * Request.
  3337. *
  3338. * @type {import('http').IncomingMessage}
  3339. */
  3340. req;
  3341. /**
  3342. * Response.
  3343. *
  3344. * @type {import('http').ServerResponse}
  3345. */
  3346. res;
  3347. /**
  3348. * Query.
  3349. *
  3350. * @type {object}
  3351. */
  3352. query = {};
  3353. /**
  3354. * Path parameters.
  3355. *
  3356. * @type {object}
  3357. */
  3358. params = {};
  3359. /**
  3360. * Parsed body.
  3361. *
  3362. * @type {*}
  3363. */
  3364. body;
  3365. /**
  3366. * Headers.
  3367. *
  3368. * @type {object}
  3369. */
  3370. headers = {};
  3371. /**
  3372. * Parsed cookie.
  3373. *
  3374. * @type {object}
  3375. */
  3376. cookie = {};
  3377. /**
  3378. * Method.
  3379. *
  3380. * @returns {string}
  3381. */
  3382. get method() {
  3383. return this.req.method.toUpperCase();
  3384. }
  3385. /**
  3386. * Path.
  3387. *
  3388. * @returns {string}
  3389. */
  3390. get path() {
  3391. return this.req.url;
  3392. }
  3393. /**
  3394. * Pathname.
  3395. *
  3396. * @type {string|undefined}
  3397. * @private
  3398. */
  3399. _pathname = void 0;
  3400. /**
  3401. * Pathname.
  3402. *
  3403. * @returns {string}
  3404. */
  3405. get pathname() {
  3406. if (this._pathname != null) return this._pathname;
  3407. this._pathname = getRequestPathname(this.req);
  3408. return this._pathname;
  3409. }
  3410. /**
  3411. * Constructor.
  3412. *
  3413. * @param {ServiceContainer} container
  3414. * @param {import('http').IncomingMessage} request
  3415. * @param {import('http').ServerResponse} response
  3416. */
  3417. constructor(container, request, response) {
  3418. if (!(container instanceof ServiceContainer))
  3419. throw new Errorf(
  3420. 'The parameter "container" of RequestContext.constructor should be an instance of ServiceContainer, but %v given.',
  3421. container
  3422. );
  3423. this.container = container;
  3424. if (!request || typeof request !== "object" || Array.isArray(request) || !isReadableStream(request)) {
  3425. throw new Errorf(
  3426. 'The parameter "request" of RequestContext.constructor should be an instance of IncomingMessage, but %v given.',
  3427. request
  3428. );
  3429. }
  3430. this.req = request;
  3431. if (!response || typeof response !== "object" || Array.isArray(response) || !isWritableStream(response)) {
  3432. throw new Errorf(
  3433. 'The parameter "response" of RequestContext.constructor should be an instance of ServerResponse, but %v given.',
  3434. response
  3435. );
  3436. }
  3437. this.res = response;
  3438. }
  3439. };
  3440. // src/trie-router.js
  3441. var TrieRouter = class extends DebuggableService {
  3442. /**
  3443. * Define route.
  3444. *
  3445. * Example 1:
  3446. * ```
  3447. * const router = new TrieRouter();
  3448. * router.defineRoute({
  3449. * method: HttpMethod.GET, // Request method.
  3450. * path: '/', // Path template.
  3451. * handler: ctx => 'Hello world!', // Request handler.
  3452. * });
  3453. * ```
  3454. *
  3455. * Example 2:
  3456. * ```
  3457. * const router = new TrieRouter();
  3458. * router.defineRoute({
  3459. * method: HttpMethod.POST, // Request method.
  3460. * path: '/users/:id', // The path template may have parameters.
  3461. * preHandler(ctx) { ... }, // The "preHandler" is executed before a route handler.
  3462. * handler(ctx) { ... }, // Request handler function.
  3463. * postHandler(ctx, data) { ... }, // The "postHandler" is executed after a route handler.
  3464. * });
  3465. * ```
  3466. *
  3467. * @param {import('./route-registry.js').RouteDefinition} routeDef
  3468. * @returns {import('./route.js').Route}
  3469. */
  3470. defineRoute(routeDef) {
  3471. return this.getService(RouteRegistry).defineRoute(routeDef);
  3472. }
  3473. /**
  3474. * Request listener.
  3475. *
  3476. * Example:
  3477. * ```
  3478. * import http from 'http';
  3479. * import {TrieRouter} from '@e22m4u/js-trie-router';
  3480. *
  3481. * const router = new TrieRouter();
  3482. * const server = new http.Server();
  3483. * server.on('request', router.requestListener); // Sets the request listener.
  3484. * server.listen(3000); // Starts listening for connections.
  3485. * ```
  3486. *
  3487. * @returns {Function}
  3488. */
  3489. get requestListener() {
  3490. return this._handleRequest.bind(this);
  3491. }
  3492. /**
  3493. * Handle incoming request.
  3494. *
  3495. * @param {import('http').IncomingMessage} req
  3496. * @param {import('http').ServerResponse} res
  3497. * @returns {Promise<undefined>}
  3498. * @private
  3499. */
  3500. async _handleRequest(req, res) {
  3501. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  3502. this.debug("Preparing to handle %s %v.", req.method, requestPath);
  3503. const resolved = this.getService(RouteRegistry).matchRouteByRequest(req);
  3504. if (!resolved) {
  3505. this.debug("No route for the request %s %v.", req.method, requestPath);
  3506. this.getService(ErrorSender).send404(req, res);
  3507. } else {
  3508. const { route, params } = resolved;
  3509. const container = new ServiceContainer(this.container);
  3510. const context = new RequestContext(container, req, res);
  3511. context.params = params;
  3512. const reqDataOrPromise = this.getService(RequestParser).parse(req);
  3513. if (isPromise(reqDataOrPromise)) {
  3514. const reqData = await reqDataOrPromise;
  3515. Object.assign(context, reqData);
  3516. } else {
  3517. Object.assign(context, reqDataOrPromise);
  3518. }
  3519. let data, error;
  3520. const hookInvoker = this.getService(HookInvoker);
  3521. try {
  3522. data = hookInvoker.invokeAndContinueUntilValueReceived(
  3523. route,
  3524. HOOK_NAME.PRE_HANDLER,
  3525. res,
  3526. context
  3527. );
  3528. if (isPromise(data)) data = await data;
  3529. if (data == null) {
  3530. data = route.handle(context);
  3531. if (isPromise(data)) data = await data;
  3532. let postHandlerData = hookInvoker.invokeAndContinueUntilValueReceived(
  3533. route,
  3534. HOOK_NAME.POST_HANDLER,
  3535. res,
  3536. context,
  3537. data
  3538. );
  3539. if (isPromise(postHandlerData))
  3540. postHandlerData = await postHandlerData;
  3541. if (postHandlerData != null) data = postHandlerData;
  3542. }
  3543. } catch (err) {
  3544. error = err;
  3545. }
  3546. if (error) {
  3547. this.getService(ErrorSender).send(req, res, error);
  3548. } else {
  3549. this.getService(DataSender).send(res, data);
  3550. }
  3551. }
  3552. }
  3553. /**
  3554. * Add hook.
  3555. *
  3556. * Example:
  3557. * ```
  3558. * import {TrieRouter} from '@e22m4u/js-trie-router';
  3559. * import {HOOK_NAME} from '@e22m4u/js-trie-router';
  3560. *
  3561. * // Router instance.
  3562. * const router = new TrieRouter();
  3563. *
  3564. * // Adds the "preHandler" hook for each route.
  3565. * router.addHook(
  3566. * HOOK_NAME.PRE_HANDLER,
  3567. * ctx => { ... },
  3568. * );
  3569. *
  3570. * // Adds the "postHandler" hook for each route.
  3571. * router.addHook(
  3572. * HOOK_NAME.POST_HANDLER,
  3573. * ctx => { ... },
  3574. * );
  3575. * ```
  3576. *
  3577. * @param {string} name
  3578. * @param {Function} hook
  3579. * @returns {this}
  3580. */
  3581. addHook(name, hook) {
  3582. this.getService(HookRegistry).addHook(name, hook);
  3583. return this;
  3584. }
  3585. };
  3586. // Annotate the CommonJS export names for ESM import in node:
  3587. 0 && (module.exports = {
  3588. BodyParser,
  3589. CookieParser,
  3590. DataSender,
  3591. EXPOSED_ERROR_PROPERTIES,
  3592. ErrorSender,
  3593. HOOK_NAME,
  3594. HookInvoker,
  3595. HookRegistry,
  3596. HttpMethod,
  3597. METHODS_WITH_BODY,
  3598. QueryParser,
  3599. RequestContext,
  3600. RequestParser,
  3601. Route,
  3602. RouteRegistry,
  3603. RouterOptions,
  3604. TrieRouter,
  3605. UNPARSABLE_MEDIA_TYPES,
  3606. parseJsonBody
  3607. });
  3608. /*! Bundled license information:
  3609. depd/index.js:
  3610. (*!
  3611. * depd
  3612. * Copyright(c) 2014-2018 Douglas Christopher Wilson
  3613. * MIT Licensed
  3614. *)
  3615. statuses/index.js:
  3616. (*!
  3617. * statuses
  3618. * Copyright(c) 2014 Jonathan Ong
  3619. * Copyright(c) 2016 Douglas Christopher Wilson
  3620. * MIT Licensed
  3621. *)
  3622. toidentifier/index.js:
  3623. (*!
  3624. * toidentifier
  3625. * Copyright(c) 2016 Douglas Christopher Wilson
  3626. * MIT Licensed
  3627. *)
  3628. http-errors/index.js:
  3629. (*!
  3630. * http-errors
  3631. * Copyright(c) 2014 Jonathan Ong
  3632. * Copyright(c) 2016 Douglas Christopher Wilson
  3633. * MIT Licensed
  3634. *)
  3635. */