index.cjs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  9. var __export = (target, all) => {
  10. for (var name in all)
  11. __defProp(target, name, { get: all[name], enumerable: true });
  12. };
  13. var __copyProps = (to, from, except, desc) => {
  14. if (from && typeof from === "object" || typeof from === "function") {
  15. for (let key of __getOwnPropNames(from))
  16. if (!__hasOwnProp.call(to, key) && key !== except)
  17. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  18. }
  19. return to;
  20. };
  21. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  22. // If the importer is in node compatibility mode or this is not an ESM
  23. // file that has been converted to a CommonJS file using a Babel-
  24. // compatible transform (i.e. "__esModule" has not been set), then set
  25. // "default" to the CommonJS "module.exports" for node compatibility.
  26. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  27. mod
  28. ));
  29. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  30. // src/index.js
  31. var index_exports = {};
  32. __export(index_exports, {
  33. BodyParser: () => BodyParser,
  34. CHARACTER_ENCODING_LIST: () => CHARACTER_ENCODING_LIST,
  35. CookiesParser: () => CookiesParser,
  36. DataSender: () => DataSender,
  37. EXPOSED_ERROR_PROPERTIES: () => EXPOSED_ERROR_PROPERTIES,
  38. ErrorSender: () => ErrorSender,
  39. HookInvoker: () => HookInvoker,
  40. HookRegistry: () => HookRegistry,
  41. HttpMethod: () => HttpMethod,
  42. METHODS_WITH_BODY: () => METHODS_WITH_BODY,
  43. QueryParser: () => QueryParser,
  44. RequestContext: () => RequestContext,
  45. RequestParser: () => RequestParser,
  46. Route: () => Route,
  47. RouteRegistry: () => RouteRegistry,
  48. RouterHookType: () => RouterHookType,
  49. RouterOptions: () => RouterOptions,
  50. TrieRouter: () => TrieRouter,
  51. UNPARSABLE_MEDIA_TYPES: () => UNPARSABLE_MEDIA_TYPES,
  52. cloneDeep: () => cloneDeep,
  53. createCookieString: () => createCookieString,
  54. createError: () => createError,
  55. createRequestMock: () => createRequestMock,
  56. createResponseMock: () => createResponseMock,
  57. createRouteMock: () => createRouteMock,
  58. fetchRequestBody: () => fetchRequestBody,
  59. getRequestPathname: () => getRequestPathname,
  60. isPromise: () => isPromise,
  61. isReadableStream: () => isReadableStream,
  62. isResponseSent: () => isResponseSent,
  63. isWritableStream: () => isWritableStream,
  64. parseContentType: () => parseContentType,
  65. parseCookieString: () => parseCookieString,
  66. parseJsonBody: () => parseJsonBody,
  67. toCamelCase: () => toCamelCase
  68. });
  69. module.exports = __toCommonJS(index_exports);
  70. // src/route.js
  71. var import_js_format12 = require("@e22m4u/js-format");
  72. var import_js_debug = require("@e22m4u/js-debug");
  73. // src/hooks/hook-invoker.js
  74. var import_js_format11 = require("@e22m4u/js-format");
  75. // src/debuggable-service.js
  76. var import_js_service = require("@e22m4u/js-service");
  77. var MODULE_DEBUG_NAMESPACE = "jsTrieRouter";
  78. var _DebuggableService = class _DebuggableService extends import_js_service.DebuggableService {
  79. /**
  80. * Constructor.
  81. *
  82. * @param {ServiceContainer} container
  83. */
  84. constructor(container = void 0) {
  85. super(container, {
  86. namespace: MODULE_DEBUG_NAMESPACE,
  87. noEnvironmentNamespace: true
  88. });
  89. }
  90. };
  91. __name(_DebuggableService, "DebuggableService");
  92. var DebuggableService = _DebuggableService;
  93. // src/utils/clone-deep.js
  94. function cloneDeep(value) {
  95. if (value == null || typeof value !== "object") {
  96. return value;
  97. }
  98. if (value instanceof Date) {
  99. return new Date(value.getTime());
  100. }
  101. if (Array.isArray(value)) {
  102. return value.map((item) => cloneDeep(item));
  103. }
  104. const proto = Object.getPrototypeOf(value);
  105. if (proto === Object.prototype || proto === null) {
  106. const newObj = proto === null ? /* @__PURE__ */ Object.create(null) : {};
  107. for (const key in value) {
  108. if (Object.prototype.hasOwnProperty.call(value, key)) {
  109. newObj[key] = cloneDeep(value[key]);
  110. }
  111. }
  112. return newObj;
  113. }
  114. return value;
  115. }
  116. __name(cloneDeep, "cloneDeep");
  117. // src/utils/is-promise.js
  118. function isPromise(value) {
  119. if (!value) return false;
  120. if (typeof value !== "object") return false;
  121. return typeof value.then === "function";
  122. }
  123. __name(isPromise, "isPromise");
  124. // src/utils/create-error.js
  125. var import_js_format = require("@e22m4u/js-format");
  126. function createError(errorCtor, message, ...args) {
  127. if (typeof errorCtor !== "function")
  128. throw new import_js_format.Errorf(
  129. 'The first parameter of "createError" should be a constructor, but %v was given.',
  130. errorCtor
  131. );
  132. if (message != null && typeof message !== "string")
  133. throw new import_js_format.Errorf(
  134. 'The second parameter of "createError" should be a String, but %v was given.',
  135. message
  136. );
  137. if (message == null) return new errorCtor();
  138. const interpolatedMessage = (0, import_js_format.format)(message, ...args);
  139. return new errorCtor(interpolatedMessage);
  140. }
  141. __name(createError, "createError");
  142. // src/utils/to-camel-case.js
  143. var import_js_format2 = require("@e22m4u/js-format");
  144. function toCamelCase(input) {
  145. if (typeof input !== "string")
  146. throw new import_js_format2.Errorf(
  147. 'The first parameter of "toCamelCase" should be a String, but %v was given.',
  148. input
  149. );
  150. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  151. }
  152. __name(toCamelCase, "toCamelCase");
  153. // src/utils/is-response-sent.js
  154. var import_js_format3 = require("@e22m4u/js-format");
  155. function isResponseSent(response) {
  156. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  157. throw new import_js_format3.Errorf(
  158. 'The first parameter of "isResponseSent" should be an instance of ServerResponse, but %v was given.',
  159. response
  160. );
  161. }
  162. return response.headersSent;
  163. }
  164. __name(isResponseSent, "isResponseSent");
  165. // src/utils/create-route-mock.js
  166. function createRouteMock(options = {}) {
  167. return new Route({
  168. method: options.method || HttpMethod.GET,
  169. path: options.path || "/",
  170. handler: options.handler || (() => "OK")
  171. });
  172. }
  173. __name(createRouteMock, "createRouteMock");
  174. // src/utils/is-readable-stream.js
  175. function isReadableStream(value) {
  176. if (!value || typeof value !== "object") return false;
  177. return typeof value.pipe === "function";
  178. }
  179. __name(isReadableStream, "isReadableStream");
  180. // src/utils/parse-content-type.js
  181. var import_js_format4 = require("@e22m4u/js-format");
  182. function parseContentType(input) {
  183. if (typeof input !== "string")
  184. throw new import_js_format4.Errorf(
  185. "The first parameter of `parseContentType` should be a String, but %v was given.",
  186. input
  187. );
  188. const res = { mediaType: void 0, charset: void 0, boundary: void 0 };
  189. const re = /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  190. const matches = re.exec(input);
  191. if (matches && matches[1]) {
  192. res.mediaType = matches[1];
  193. if (matches[2]) res.charset = matches[2];
  194. if (matches[3]) res.boundary = matches[3];
  195. }
  196. return res;
  197. }
  198. __name(parseContentType, "parseContentType");
  199. // src/utils/is-writable-stream.js
  200. function isWritableStream(value) {
  201. if (!value || typeof value !== "object") return false;
  202. return typeof value.end === "function";
  203. }
  204. __name(isWritableStream, "isWritableStream");
  205. // src/utils/fetch-request-body.js
  206. var import_http_errors = __toESM(require("http-errors"), 1);
  207. var import_http = require("http");
  208. var import_js_format5 = require("@e22m4u/js-format");
  209. var CHARACTER_ENCODING_LIST = [
  210. "ascii",
  211. "utf8",
  212. "utf-8",
  213. "utf16le",
  214. "utf-16le",
  215. "ucs2",
  216. "ucs-2",
  217. "latin1"
  218. ];
  219. function fetchRequestBody(request, bodyBytesLimit = 0) {
  220. if (!(request instanceof import_http.IncomingMessage))
  221. throw new import_js_format5.Errorf(
  222. 'The first parameter of "fetchRequestBody" should be an IncomingMessage instance, but %v was given.',
  223. request
  224. );
  225. if (typeof bodyBytesLimit !== "number")
  226. throw new import_js_format5.Errorf(
  227. 'The parameter "bodyBytesLimit" of "fetchRequestBody" should be a number, but %v was given.',
  228. bodyBytesLimit
  229. );
  230. return new Promise((resolve, reject) => {
  231. const contentLength = parseInt(
  232. request.headers["content-length"] || "0",
  233. 10
  234. );
  235. if (bodyBytesLimit && contentLength && contentLength > bodyBytesLimit)
  236. throw createError(
  237. import_http_errors.default.PayloadTooLarge,
  238. "Request body limit is %s bytes, but %s bytes given.",
  239. bodyBytesLimit,
  240. contentLength
  241. );
  242. let encoding = "utf-8";
  243. const contentType = request.headers["content-type"] || "";
  244. if (contentType) {
  245. const parsedContentType = parseContentType(contentType);
  246. if (parsedContentType && parsedContentType.charset) {
  247. encoding = parsedContentType.charset.toLowerCase();
  248. if (!CHARACTER_ENCODING_LIST.includes(encoding))
  249. throw createError(
  250. import_http_errors.default.UnsupportedMediaType,
  251. "Request encoding %v is not supported.",
  252. encoding
  253. );
  254. }
  255. }
  256. const data = [];
  257. let receivedLength = 0;
  258. const onData = /* @__PURE__ */ __name((chunk) => {
  259. receivedLength += chunk.length;
  260. if (bodyBytesLimit && receivedLength > bodyBytesLimit) {
  261. request.removeAllListeners();
  262. const error = createError(
  263. import_http_errors.default.PayloadTooLarge,
  264. "Request body limit is %v bytes, but %v bytes given.",
  265. bodyBytesLimit,
  266. receivedLength
  267. );
  268. reject(error);
  269. return;
  270. }
  271. data.push(chunk);
  272. }, "onData");
  273. const onEnd = /* @__PURE__ */ __name(() => {
  274. request.removeAllListeners();
  275. if (contentLength && contentLength !== receivedLength) {
  276. const error = createError(
  277. import_http_errors.default.BadRequest,
  278. 'Received bytes do not match the "content-length" header.'
  279. );
  280. reject(error);
  281. return;
  282. }
  283. const buffer = Buffer.concat(data);
  284. const body = buffer.toString(encoding);
  285. resolve(body || void 0);
  286. }, "onEnd");
  287. const onError = /* @__PURE__ */ __name((error) => {
  288. request.removeAllListeners();
  289. reject((0, import_http_errors.default)(400, error));
  290. }, "onError");
  291. request.on("data", onData);
  292. request.on("end", onEnd);
  293. request.on("error", onError);
  294. request.resume();
  295. });
  296. }
  297. __name(fetchRequestBody, "fetchRequestBody");
  298. // src/utils/parse-cookie-string.js
  299. var import_js_format6 = require("@e22m4u/js-format");
  300. function parseCookieString(input) {
  301. if (typeof input !== "string")
  302. throw new import_js_format6.Errorf(
  303. 'The first parameter of "parseCookieString" must be a String, but %v was given.',
  304. input
  305. );
  306. return input.split(";").filter((v) => v !== "").map((v) => v.split("=")).reduce((cookies, tuple) => {
  307. const key = decodeURIComponent(tuple[0]).trim();
  308. const value = tuple[1] !== void 0 ? decodeURIComponent(tuple[1]).trim() : "";
  309. cookies[key] = value;
  310. return cookies;
  311. }, {});
  312. }
  313. __name(parseCookieString, "parseCookieString");
  314. // src/utils/create-request-mock.js
  315. var import_net = require("net");
  316. var import_tls = require("tls");
  317. var import_http2 = require("http");
  318. var import_querystring = __toESM(require("querystring"), 1);
  319. var import_js_format8 = require("@e22m4u/js-format");
  320. // src/utils/create-cookie-string.js
  321. var import_js_format7 = require("@e22m4u/js-format");
  322. function createCookieString(data) {
  323. if (!data || typeof data !== "object" || Array.isArray(data))
  324. throw new import_js_format7.Errorf(
  325. 'The first parameter of "createCookieString" should be an Object, but %v was given.',
  326. data
  327. );
  328. let cookies = "";
  329. for (const key in data) {
  330. if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
  331. const val = data[key];
  332. if (val == null) continue;
  333. cookies += `${key}=${val}; `;
  334. }
  335. return cookies.trim();
  336. }
  337. __name(createCookieString, "createCookieString");
  338. // src/utils/create-request-mock.js
  339. function createRequestMock(patch) {
  340. if (patch != null && typeof patch !== "object" || Array.isArray(patch)) {
  341. throw new import_js_format8.Errorf(
  342. 'The first parameter of "createRequestMock" should be an Object, but %v was given.',
  343. patch
  344. );
  345. }
  346. patch = patch || {};
  347. if (patch.host != null && typeof patch.host !== "string")
  348. throw new import_js_format8.Errorf(
  349. 'The parameter "host" of "createRequestMock" should be a String, but %v was given.',
  350. patch.host
  351. );
  352. if (patch.method != null && typeof patch.method !== "string")
  353. throw new import_js_format8.Errorf(
  354. 'The parameter "method" of "createRequestMock" should be a String, but %v was given.',
  355. patch.method
  356. );
  357. if (patch.secure != null && typeof patch.secure !== "boolean")
  358. throw new import_js_format8.Errorf(
  359. 'The parameter "secure" of "createRequestMock" should be a Boolean, but %v was given.',
  360. patch.secure
  361. );
  362. if (patch.path != null && typeof patch.path !== "string")
  363. throw new import_js_format8.Errorf(
  364. 'The parameter "path" of "createRequestMock" should be a String, but %v was given.',
  365. patch.path
  366. );
  367. if (patch.query != null && typeof patch.query !== "object" && typeof patch.query !== "string" || Array.isArray(patch.query)) {
  368. throw new import_js_format8.Errorf(
  369. 'The parameter "query" of "createRequestMock" should be a String or Object, but %v was given.',
  370. patch.query
  371. );
  372. }
  373. if (patch.cookies != null && typeof patch.cookies !== "string" && typeof patch.cookies !== "object" || Array.isArray(patch.cookies)) {
  374. throw new import_js_format8.Errorf(
  375. 'The parameter "cookies" of "createRequestMock" should be a String or Object, but %v was given.',
  376. patch.cookies
  377. );
  378. }
  379. if (patch.headers != null && typeof patch.headers !== "object" || Array.isArray(patch.headers)) {
  380. throw new import_js_format8.Errorf(
  381. 'The parameter "headers" of "createRequestMock" should be an Object, but %v was given.',
  382. patch.headers
  383. );
  384. }
  385. if (patch.stream != null && !isReadableStream(patch.stream))
  386. throw new import_js_format8.Errorf(
  387. 'The parameter "stream" of "createRequestMock" should be a Stream, but %v was given.',
  388. patch.stream
  389. );
  390. if (patch.encoding != null) {
  391. if (typeof patch.encoding !== "string")
  392. throw new import_js_format8.Errorf(
  393. 'The parameter "encoding" of "createRequestMock" should be a String, but %v was given.',
  394. patch.encoding
  395. );
  396. if (!CHARACTER_ENCODING_LIST.includes(patch.encoding))
  397. throw new import_js_format8.Errorf(
  398. "Character encoding %v is not supported.",
  399. patch.encoding
  400. );
  401. }
  402. if (patch.stream) {
  403. if (patch.secure != null)
  404. throw new import_js_format8.Errorf(
  405. 'The "createRequestMock" does not allow specifying the "stream" and "secure" options simultaneously.'
  406. );
  407. if (patch.body != null)
  408. throw new import_js_format8.Errorf(
  409. 'The "createRequestMock" does not allow specifying the "stream" and "body" options simultaneously.'
  410. );
  411. if (patch.encoding != null)
  412. throw new import_js_format8.Errorf(
  413. 'The "createRequestMock" does not allow specifying the "stream" and "encoding" options simultaneously.'
  414. );
  415. }
  416. const request = patch.stream || createRequestStream(patch.secure, patch.body, patch.encoding);
  417. request.url = createRequestUrl(patch.path || "/", patch.query);
  418. request.headers = createRequestHeaders(
  419. patch.host,
  420. patch.secure,
  421. patch.body,
  422. patch.cookies,
  423. patch.encoding,
  424. patch.headers
  425. );
  426. request.method = (patch.method || "get").toUpperCase();
  427. return request;
  428. }
  429. __name(createRequestMock, "createRequestMock");
  430. function createRequestStream(secure, body, encoding) {
  431. if (encoding != null && typeof encoding !== "string")
  432. throw new import_js_format8.Errorf(
  433. 'The parameter "encoding" of "createRequestStream" should be a String, but %v was given.',
  434. encoding
  435. );
  436. encoding = encoding || "utf-8";
  437. let socket = new import_net.Socket();
  438. if (secure) socket = new import_tls.TLSSocket(socket);
  439. const request = new import_http2.IncomingMessage(socket);
  440. if (body != null) {
  441. if (typeof body === "string") {
  442. request.push(body, encoding);
  443. } else if (Buffer.isBuffer(body)) {
  444. request.push(body);
  445. } else {
  446. request.push(JSON.stringify(body));
  447. }
  448. }
  449. request.push(null);
  450. return request;
  451. }
  452. __name(createRequestStream, "createRequestStream");
  453. function createRequestUrl(path, query) {
  454. if (typeof path !== "string")
  455. throw new import_js_format8.Errorf(
  456. 'The parameter "path" of "createRequestUrl" should be a String, but %v was given.',
  457. path
  458. );
  459. if (query != null && typeof query !== "string" && typeof query !== "object" || Array.isArray(query)) {
  460. throw new import_js_format8.Errorf(
  461. 'The parameter "query" of "createRequestUrl" should be a String or Object, but %v was given.',
  462. query
  463. );
  464. }
  465. let url = ("/" + path).replace("//", "/");
  466. if (typeof query === "object") {
  467. const qs = import_querystring.default.stringify(query);
  468. if (qs) url += `?${qs}`;
  469. } else if (typeof query === "string") {
  470. url += `?${query.replace(/^\?/, "")}`;
  471. }
  472. return url;
  473. }
  474. __name(createRequestUrl, "createRequestUrl");
  475. function createRequestHeaders(host, secure, body, cookies, encoding, headers) {
  476. if (host != null && typeof host !== "string")
  477. throw new import_js_format8.Errorf(
  478. 'The parameter "host" of "createRequestHeaders" a non-empty String, but %v was given.',
  479. host
  480. );
  481. host = host || "localhost";
  482. if (secure != null && typeof secure !== "boolean")
  483. throw new import_js_format8.Errorf(
  484. 'The parameter "secure" of "createRequestHeaders" should be a String, but %v was given.',
  485. secure
  486. );
  487. secure = Boolean(secure);
  488. if (cookies != null && typeof cookies !== "object" && typeof cookies !== "string" || Array.isArray(cookies)) {
  489. throw new import_js_format8.Errorf(
  490. 'The parameter "cookies" of "createRequestHeaders" should be a String or Object, but %v was given.',
  491. cookies
  492. );
  493. }
  494. if (headers != null && typeof headers !== "object" || Array.isArray(headers)) {
  495. throw new import_js_format8.Errorf(
  496. 'The parameter "headers" of "createRequestHeaders" should be an Object, but %v was given.',
  497. headers
  498. );
  499. }
  500. headers = headers || {};
  501. if (encoding != null && typeof encoding !== "string")
  502. throw new import_js_format8.Errorf(
  503. 'The parameter "encoding" of "createRequestHeaders" should be a String, but %v was given.',
  504. encoding
  505. );
  506. encoding = encoding || "utf-8";
  507. const obj = { ...headers };
  508. obj["host"] = host;
  509. if (secure) obj["x-forwarded-proto"] = "https";
  510. if (cookies != null) {
  511. if (typeof cookies === "string") {
  512. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  513. obj["cookie"] += obj["cookie"] ? `; ${cookies}` : cookies;
  514. } else if (typeof cookies === "object") {
  515. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  516. const newCookies = createCookieString(cookies);
  517. obj["cookie"] += obj["cookie"] ? `; ${newCookies}` : newCookies;
  518. }
  519. }
  520. if (obj["content-type"] == null) {
  521. if (typeof body === "string") {
  522. obj["content-type"] = "text/plain";
  523. } else if (Buffer.isBuffer(body)) {
  524. obj["content-type"] = "application/octet-stream";
  525. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  526. obj["content-type"] = "application/json";
  527. }
  528. }
  529. if (body != null && obj["content-length"] == null) {
  530. if (typeof body === "string") {
  531. const length = Buffer.byteLength(body, encoding);
  532. obj["content-length"] = String(length);
  533. } else if (Buffer.isBuffer(body)) {
  534. const length = Buffer.byteLength(body);
  535. obj["content-length"] = String(length);
  536. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  537. const json = JSON.stringify(body);
  538. const length = Buffer.byteLength(json, encoding);
  539. obj["content-length"] = String(length);
  540. }
  541. }
  542. return obj;
  543. }
  544. __name(createRequestHeaders, "createRequestHeaders");
  545. // src/utils/create-response-mock.js
  546. var import_stream = require("stream");
  547. function createResponseMock() {
  548. const response = new import_stream.PassThrough();
  549. patchEncoding(response);
  550. patchHeaders(response);
  551. patchBody(response);
  552. return response;
  553. }
  554. __name(createResponseMock, "createResponseMock");
  555. function patchEncoding(response) {
  556. Object.defineProperty(response, "_encoding", {
  557. configurable: true,
  558. writable: true,
  559. value: void 0
  560. });
  561. Object.defineProperty(response, "setEncoding", {
  562. configurable: true,
  563. value: /* @__PURE__ */ __name(function(enc) {
  564. this._encoding = enc;
  565. return this;
  566. }, "value")
  567. });
  568. Object.defineProperty(response, "getEncoding", {
  569. configurable: true,
  570. value: /* @__PURE__ */ __name(function() {
  571. return this._encoding;
  572. }, "value")
  573. });
  574. }
  575. __name(patchEncoding, "patchEncoding");
  576. function patchHeaders(response) {
  577. Object.defineProperty(response, "_headersSent", {
  578. configurable: true,
  579. writable: true,
  580. value: false
  581. });
  582. Object.defineProperty(response, "headersSent", {
  583. configurable: true,
  584. get() {
  585. return this._headersSent;
  586. }
  587. });
  588. Object.defineProperty(response, "_headers", {
  589. configurable: true,
  590. writable: true,
  591. value: {}
  592. });
  593. Object.defineProperty(response, "setHeader", {
  594. configurable: true,
  595. value: /* @__PURE__ */ __name(function(name, value) {
  596. if (this.headersSent)
  597. throw new Error(
  598. "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
  599. );
  600. const key = name.toLowerCase();
  601. this._headers[key] = String(value);
  602. return this;
  603. }, "value")
  604. });
  605. Object.defineProperty(response, "getHeader", {
  606. configurable: true,
  607. value: /* @__PURE__ */ __name(function(name) {
  608. return this._headers[name.toLowerCase()];
  609. }, "value")
  610. });
  611. Object.defineProperty(response, "getHeaders", {
  612. configurable: true,
  613. value: /* @__PURE__ */ __name(function() {
  614. return JSON.parse(JSON.stringify(this._headers));
  615. }, "value")
  616. });
  617. }
  618. __name(patchHeaders, "patchHeaders");
  619. function patchBody(response) {
  620. let resolve, reject;
  621. const promise = new Promise((rsv, rej) => {
  622. resolve = rsv;
  623. reject = rej;
  624. });
  625. const data = [];
  626. response.on("data", (c) => data.push(c));
  627. response.on("error", (e) => reject(e));
  628. response.on("end", () => {
  629. resolve(Buffer.concat(data));
  630. });
  631. const originalEnd = response.end.bind(response);
  632. response.end = function(...args) {
  633. this._headersSent = true;
  634. return originalEnd(...args);
  635. };
  636. Object.defineProperty(response, "getBody", {
  637. configurable: true,
  638. value: /* @__PURE__ */ __name(function() {
  639. return promise.then((buffer) => {
  640. const enc = this.getEncoding();
  641. const str = buffer.toString(enc);
  642. return data.length ? str : void 0;
  643. });
  644. }, "value")
  645. });
  646. }
  647. __name(patchBody, "patchBody");
  648. // src/utils/get-request-pathname.js
  649. var import_js_format9 = require("@e22m4u/js-format");
  650. function getRequestPathname(request) {
  651. if (!request || typeof request !== "object" || Array.isArray(request) || typeof request.url !== "string") {
  652. throw new import_js_format9.Errorf(
  653. 'The first parameter of "getRequestPathname" should be an instance of IncomingMessage, but %v was given.',
  654. request
  655. );
  656. }
  657. return (request.url || "/").replace(/\?.*$/, "");
  658. }
  659. __name(getRequestPathname, "getRequestPathname");
  660. // src/hooks/hook-registry.js
  661. var import_js_format10 = require("@e22m4u/js-format");
  662. var RouterHookType = {
  663. PRE_HANDLER: "preHandler",
  664. POST_HANDLER: "postHandler"
  665. };
  666. var _HookRegistry = class _HookRegistry {
  667. /**
  668. * Hooks.
  669. *
  670. * @type {Map<string, Function[]>}
  671. * @private
  672. */
  673. _hooks = /* @__PURE__ */ new Map();
  674. /**
  675. * Add hook.
  676. *
  677. * @param {string} type
  678. * @param {Function} hook
  679. * @returns {this}
  680. */
  681. addHook(type, hook) {
  682. if (!type || typeof type !== "string")
  683. throw new import_js_format10.Errorf("The hook type is required, but %v was given.", type);
  684. if (!Object.values(RouterHookType).includes(type))
  685. throw new import_js_format10.Errorf("The hook type %v is not supported.", type);
  686. if (!hook || typeof hook !== "function")
  687. throw new import_js_format10.Errorf(
  688. "The hook %v should be a Function, but %v was given.",
  689. type,
  690. hook
  691. );
  692. const hooks = this._hooks.get(type) || [];
  693. hooks.push(hook);
  694. this._hooks.set(type, hooks);
  695. return this;
  696. }
  697. /**
  698. * Has hook.
  699. *
  700. * @param {string} type
  701. * @param {Function} hook
  702. * @returns {boolean}
  703. */
  704. hasHook(type, hook) {
  705. if (!type || typeof type !== "string")
  706. throw new import_js_format10.Errorf("The hook type is required, but %v was given.", type);
  707. if (!Object.values(RouterHookType).includes(type))
  708. throw new import_js_format10.Errorf("The hook type %v is not supported.", type);
  709. if (!hook || typeof hook !== "function")
  710. throw new import_js_format10.Errorf(
  711. "The hook %v should be a Function, but %v was given.",
  712. type,
  713. hook
  714. );
  715. const hooks = this._hooks.get(type) || [];
  716. return hooks.indexOf(hook) > -1;
  717. }
  718. /**
  719. * Get hooks.
  720. *
  721. * @param {string} type
  722. * @returns {Function[]}
  723. */
  724. getHooks(type) {
  725. if (!type || typeof type !== "string")
  726. throw new import_js_format10.Errorf("The hook type is required, but %v was given.", type);
  727. if (!Object.values(RouterHookType).includes(type))
  728. throw new import_js_format10.Errorf("The hook type %v is not supported.", type);
  729. return this._hooks.get(type) || [];
  730. }
  731. };
  732. __name(_HookRegistry, "HookRegistry");
  733. var HookRegistry = _HookRegistry;
  734. // src/hooks/hook-invoker.js
  735. var _HookInvoker = class _HookInvoker extends DebuggableService {
  736. /**
  737. * Invoke and continue until value received.
  738. *
  739. * @param {Route} route
  740. * @param {string} hookType
  741. * @param {import('http').ServerResponse} response
  742. * @param {*[]} args
  743. * @returns {Promise<*>|*}
  744. */
  745. invokeAndContinueUntilValueReceived(route, hookType, response, ...args) {
  746. if (!route || !(route instanceof Route))
  747. throw new import_js_format11.Errorf(
  748. 'The parameter "route" of the HookInvoker.invokeAndContinueUntilValueReceived should be a Route instance, but %v was given.',
  749. route
  750. );
  751. if (!hookType || typeof hookType !== "string")
  752. throw new import_js_format11.Errorf(
  753. 'The parameter "hookType" of the HookInvoker.invokeAndContinueUntilValueReceived should be a non-empty String, but %v was given.',
  754. hookType
  755. );
  756. if (!Object.values(RouterHookType).includes(hookType))
  757. throw new import_js_format11.Errorf("The hook type %v is not supported.", hookType);
  758. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  759. throw new import_js_format11.Errorf(
  760. 'The parameter "response" of the HookInvoker.invokeAndContinueUntilValueReceived should be a ServerResponse instance, but %v was given.',
  761. response
  762. );
  763. }
  764. if (isResponseSent(response)) {
  765. return response;
  766. }
  767. const hooks = [
  768. ...this.getService(HookRegistry).getHooks(hookType),
  769. ...route.hookRegistry.getHooks(hookType)
  770. ];
  771. let result = void 0;
  772. for (let i = 0; i < hooks.length; i++) {
  773. const hook = hooks[i];
  774. result = hook(...args);
  775. if (isResponseSent(response)) {
  776. return response;
  777. }
  778. if (result != null) {
  779. if (isPromise(result)) {
  780. return (async () => {
  781. let asyncResult = await result;
  782. if (isResponseSent(response)) {
  783. return response;
  784. }
  785. if (asyncResult != null) {
  786. return asyncResult;
  787. }
  788. for (let j = i + 1; j < hooks.length; j++) {
  789. asyncResult = await hooks[j](...args);
  790. if (isResponseSent(response)) {
  791. return response;
  792. }
  793. if (asyncResult != null) {
  794. return asyncResult;
  795. }
  796. }
  797. return;
  798. })();
  799. }
  800. return result;
  801. }
  802. }
  803. return;
  804. }
  805. };
  806. __name(_HookInvoker, "HookInvoker");
  807. var HookInvoker = _HookInvoker;
  808. // src/route.js
  809. var HttpMethod = {
  810. GET: "GET",
  811. POST: "POST",
  812. PUT: "PUT",
  813. PATCH: "PATCH",
  814. DELETE: "DELETE"
  815. };
  816. var _Route = class _Route extends import_js_debug.Debuggable {
  817. /**
  818. * Method.
  819. *
  820. * @type {string}
  821. * @private
  822. */
  823. _method;
  824. /**
  825. * Getter of the method.
  826. *
  827. * @returns {string}
  828. */
  829. get method() {
  830. return this._method;
  831. }
  832. /**
  833. * Path template.
  834. *
  835. * @type {string}
  836. * @private
  837. */
  838. _path;
  839. /**
  840. * Getter of the path.
  841. *
  842. * @returns {string}
  843. */
  844. get path() {
  845. return this._path;
  846. }
  847. /**
  848. * Meta.
  849. *
  850. * @type {object}
  851. */
  852. _meta = {};
  853. /**
  854. * Getter of the meta.
  855. *
  856. * @returns {object}
  857. */
  858. get meta() {
  859. return this._meta;
  860. }
  861. /**
  862. * Handler.
  863. *
  864. * @type {RouteHandler}
  865. * @private
  866. */
  867. _handler;
  868. /**
  869. * Getter of the handler.
  870. *
  871. * @returns {*}
  872. */
  873. get handler() {
  874. return this._handler;
  875. }
  876. /**
  877. * Hook registry.
  878. *
  879. * @type {HookRegistry}
  880. * @private
  881. */
  882. _hookRegistry = new HookRegistry();
  883. /**
  884. * Getter of the hook registry.
  885. *
  886. * @returns {HookRegistry}
  887. */
  888. get hookRegistry() {
  889. return this._hookRegistry;
  890. }
  891. /**
  892. * Constructor.
  893. *
  894. * @param {RouteDefinition} routeDef
  895. */
  896. constructor(routeDef) {
  897. super({
  898. namespace: MODULE_DEBUG_NAMESPACE,
  899. noEnvironmentNamespace: true,
  900. noInstantiationMessage: true
  901. });
  902. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  903. throw new import_js_format12.Errorf(
  904. "The first parameter of Route.constructor should be an Object, but %v was given.",
  905. routeDef
  906. );
  907. if (!routeDef.method || typeof routeDef.method !== "string")
  908. throw new import_js_format12.Errorf(
  909. 'The option "method" of the Route should be a non-empty String, but %v was given.',
  910. routeDef.method
  911. );
  912. this._method = routeDef.method.toUpperCase();
  913. if (typeof routeDef.path !== "string")
  914. throw new import_js_format12.Errorf(
  915. 'The option "path" of the Route should be a String, but %v was given.',
  916. routeDef.path
  917. );
  918. this._path = routeDef.path;
  919. if (typeof routeDef.handler !== "function")
  920. throw new import_js_format12.Errorf(
  921. 'The option "handler" of the Route should be a Function, but %v was given.',
  922. routeDef.handler
  923. );
  924. if (routeDef.meta != null) {
  925. if (typeof routeDef.meta !== "object" || Array.isArray(routeDef.meta))
  926. throw new import_js_format12.Errorf(
  927. 'The option "meta" of the Route should be a plain Object, but %v was given.',
  928. routeDef.meta
  929. );
  930. this._meta = cloneDeep(routeDef.meta);
  931. }
  932. this._handler = routeDef.handler;
  933. if (routeDef.preHandler != null) {
  934. const preHandlerHooks = Array.isArray(routeDef.preHandler) ? routeDef.preHandler : [routeDef.preHandler];
  935. preHandlerHooks.forEach((hook) => {
  936. this._hookRegistry.addHook(RouterHookType.PRE_HANDLER, hook);
  937. });
  938. }
  939. if (routeDef.postHandler != null) {
  940. const postHandlerHooks = Array.isArray(routeDef.postHandler) ? routeDef.postHandler : [routeDef.postHandler];
  941. postHandlerHooks.forEach((hook) => {
  942. this._hookRegistry.addHook(RouterHookType.POST_HANDLER, hook);
  943. });
  944. }
  945. this.ctorDebug("A new route %s %v was created.", this._method, this._path);
  946. }
  947. /**
  948. * Handle request.
  949. *
  950. * @param {RequestContext} context
  951. * @returns {*}
  952. */
  953. handle(context) {
  954. const debug = this.getDebuggerFor(this.handle);
  955. const requestPath = getRequestPathname(context.request);
  956. debug(
  957. "Invoking the Route handler for the request %s %v.",
  958. this.method.toUpperCase(),
  959. requestPath
  960. );
  961. return this._handler(context);
  962. }
  963. };
  964. __name(_Route, "Route");
  965. var Route = _Route;
  966. // src/parsers/body-parser.js
  967. var import_http_errors2 = __toESM(require("http-errors"), 1);
  968. var import_js_format14 = require("@e22m4u/js-format");
  969. // src/router-options.js
  970. var import_js_format13 = require("@e22m4u/js-format");
  971. var _RouterOptions = class _RouterOptions extends DebuggableService {
  972. /**
  973. * Request body bytes limit.
  974. *
  975. * @type {number}
  976. * @private
  977. */
  978. _requestBodyBytesLimit = 512e3;
  979. // 512kb
  980. /**
  981. * Getter of request body bytes limit.
  982. *
  983. * @returns {number}
  984. */
  985. get requestBodyBytesLimit() {
  986. return this._requestBodyBytesLimit;
  987. }
  988. /**
  989. * Set request body bytes limit.
  990. *
  991. * @param {number} input
  992. * @returns {RouterOptions}
  993. */
  994. setRequestBodyBytesLimit(input) {
  995. if (typeof input !== "number" || input < 0)
  996. throw new import_js_format13.Errorf(
  997. 'The option "requestBodyBytesLimit" must be a positive Number or 0, but %v was given.',
  998. input
  999. );
  1000. this._requestBodyBytesLimit = input;
  1001. return this;
  1002. }
  1003. };
  1004. __name(_RouterOptions, "RouterOptions");
  1005. var RouterOptions = _RouterOptions;
  1006. // src/parsers/body-parser.js
  1007. var METHODS_WITH_BODY = ["POST", "PUT", "PATCH", "DELETE"];
  1008. var UNPARSABLE_MEDIA_TYPES = ["multipart/form-data"];
  1009. var _BodyParser = class _BodyParser extends DebuggableService {
  1010. /**
  1011. * Parsers.
  1012. *
  1013. * @type {{[mime: string]: Function}}
  1014. */
  1015. _parsers = {
  1016. "text/plain": /* @__PURE__ */ __name((v) => String(v), "text/plain"),
  1017. "application/json": parseJsonBody
  1018. };
  1019. /**
  1020. * Set parser.
  1021. *
  1022. * @param {string} mediaType
  1023. * @param {Function} parser
  1024. * @returns {this}
  1025. */
  1026. defineParser(mediaType, parser) {
  1027. if (!mediaType || typeof mediaType !== "string")
  1028. throw new import_js_format14.Errorf(
  1029. 'The parameter "mediaType" of BodyParser.defineParser should be a non-empty String, but %v was given.',
  1030. mediaType
  1031. );
  1032. if (!parser || typeof parser !== "function")
  1033. throw new import_js_format14.Errorf(
  1034. 'The parameter "parser" of BodyParser.defineParser should be a Function, but %v was given.',
  1035. parser
  1036. );
  1037. this._parsers[mediaType] = parser;
  1038. return this;
  1039. }
  1040. /**
  1041. * Has parser.
  1042. *
  1043. * @param {string} mediaType
  1044. * @returns {boolean}
  1045. */
  1046. hasParser(mediaType) {
  1047. if (!mediaType || typeof mediaType !== "string")
  1048. throw new import_js_format14.Errorf(
  1049. 'The parameter "mediaType" of BodyParser.hasParser should be a non-empty String, but %v was given.',
  1050. mediaType
  1051. );
  1052. return Boolean(this._parsers[mediaType]);
  1053. }
  1054. /**
  1055. * Delete parser.
  1056. *
  1057. * @param {string} mediaType
  1058. * @returns {this}
  1059. */
  1060. deleteParser(mediaType) {
  1061. if (!mediaType || typeof mediaType !== "string")
  1062. throw new import_js_format14.Errorf(
  1063. 'The parameter "mediaType" of BodyParser.deleteParser should be a non-empty String, but %v was given.',
  1064. mediaType
  1065. );
  1066. const parser = this._parsers[mediaType];
  1067. if (!parser) throw new import_js_format14.Errorf("The parser of %v is not found.", mediaType);
  1068. delete this._parsers[mediaType];
  1069. return this;
  1070. }
  1071. /**
  1072. * Parse.
  1073. *
  1074. * @param {import('http').IncomingMessage} request
  1075. * @returns {Promise<*>|undefined}
  1076. */
  1077. parse(request) {
  1078. const debug = this.getDebuggerFor(this.parse);
  1079. if (!METHODS_WITH_BODY.includes(request.method.toUpperCase())) {
  1080. debug(
  1081. "Body parsing was skipped for the %s request.",
  1082. request.method.toUpperCase()
  1083. );
  1084. return;
  1085. }
  1086. const contentType = (request.headers["content-type"] || "").replace(
  1087. /^([^;]+);.*$/,
  1088. "$1"
  1089. );
  1090. if (!contentType) {
  1091. debug(
  1092. "Body parsing was skipped because the request had no content type."
  1093. );
  1094. return;
  1095. }
  1096. const { mediaType } = parseContentType(contentType);
  1097. if (!mediaType)
  1098. throw createError(
  1099. import_http_errors2.default.BadRequest,
  1100. 'Unable to parse the "content-type" header.'
  1101. );
  1102. const parser = this._parsers[mediaType];
  1103. if (!parser) {
  1104. if (UNPARSABLE_MEDIA_TYPES.includes(mediaType)) {
  1105. debug("Body parsing was skipped for %v.", mediaType);
  1106. return;
  1107. }
  1108. throw createError(
  1109. import_http_errors2.default.UnsupportedMediaType,
  1110. "Media type %v is not supported.",
  1111. mediaType
  1112. );
  1113. }
  1114. const bodyBytesLimit = this.getService(RouterOptions).requestBodyBytesLimit;
  1115. return fetchRequestBody(request, bodyBytesLimit).then((rawBody) => {
  1116. if (rawBody != null) return parser(rawBody);
  1117. return rawBody;
  1118. });
  1119. }
  1120. };
  1121. __name(_BodyParser, "BodyParser");
  1122. var BodyParser = _BodyParser;
  1123. function parseJsonBody(input) {
  1124. if (typeof input !== "string") return void 0;
  1125. try {
  1126. return JSON.parse(input);
  1127. } catch (error) {
  1128. throw createError(import_http_errors2.default.BadRequest, error.message);
  1129. }
  1130. }
  1131. __name(parseJsonBody, "parseJsonBody");
  1132. // src/parsers/query-parser.js
  1133. var import_querystring2 = __toESM(require("querystring"), 1);
  1134. var _QueryParser = class _QueryParser extends DebuggableService {
  1135. /**
  1136. * Parse
  1137. *
  1138. * @param {import('http').IncomingMessage} request
  1139. * @returns {object}
  1140. */
  1141. parse(request) {
  1142. const debug = this.getDebuggerFor(this.parse);
  1143. const queryStr = request.url.replace(/^[^?]*\??/, "");
  1144. const query = queryStr ? import_querystring2.default.parse(queryStr) : {};
  1145. const queryKeys = Object.keys(query);
  1146. if (queryKeys.length) {
  1147. queryKeys.forEach((key) => {
  1148. debug("The query parameter %v had the value %v.", key, query[key]);
  1149. });
  1150. } else {
  1151. debug(
  1152. "The request %s %v had no query parameters.",
  1153. request.method,
  1154. getRequestPathname(request)
  1155. );
  1156. }
  1157. return query;
  1158. }
  1159. };
  1160. __name(_QueryParser, "QueryParser");
  1161. var QueryParser = _QueryParser;
  1162. // src/parsers/cookies-parser.js
  1163. var _CookiesParser = class _CookiesParser extends DebuggableService {
  1164. /**
  1165. * Parse
  1166. *
  1167. * @param {import('http').IncomingMessage} request
  1168. * @returns {object}
  1169. */
  1170. parse(request) {
  1171. const debug = this.getDebuggerFor(this.parse);
  1172. const cookiesString = request.headers["cookie"] || "";
  1173. const cookies = parseCookieString(cookiesString);
  1174. const cookiesKeys = Object.keys(cookies);
  1175. if (cookiesKeys.length) {
  1176. cookiesKeys.forEach((key) => {
  1177. debug("The cookie %v had the value %v.", key, cookies[key]);
  1178. });
  1179. } else {
  1180. debug(
  1181. "The request %s %v had no cookies.",
  1182. request.method,
  1183. getRequestPathname(request)
  1184. );
  1185. }
  1186. return cookies;
  1187. }
  1188. };
  1189. __name(_CookiesParser, "CookiesParser");
  1190. var CookiesParser = _CookiesParser;
  1191. // src/parsers/request-parser.js
  1192. var import_http3 = require("http");
  1193. var import_js_format15 = require("@e22m4u/js-format");
  1194. var _RequestParser = class _RequestParser extends DebuggableService {
  1195. /**
  1196. * Parse.
  1197. *
  1198. * @param {IncomingMessage} request
  1199. * @returns {Promise<object>|object}
  1200. */
  1201. parse(request) {
  1202. if (!(request instanceof import_http3.IncomingMessage))
  1203. throw new import_js_format15.Errorf(
  1204. "The first parameter of RequestParser.parse should be an instance of IncomingMessage, but %v was given.",
  1205. request
  1206. );
  1207. const data = {};
  1208. const promises = [];
  1209. const parsedQuery = this.getService(QueryParser).parse(request);
  1210. if (isPromise(parsedQuery)) {
  1211. promises.push(parsedQuery.then((v) => data.query = v));
  1212. } else {
  1213. data.query = parsedQuery;
  1214. }
  1215. const parsedCookies = this.getService(CookiesParser).parse(request);
  1216. if (isPromise(parsedCookies)) {
  1217. promises.push(parsedCookies.then((v) => data.cookies = v));
  1218. } else {
  1219. data.cookies = parsedCookies;
  1220. }
  1221. const parsedBody = this.getService(BodyParser).parse(request);
  1222. if (isPromise(parsedBody)) {
  1223. promises.push(parsedBody.then((v) => data.body = v));
  1224. } else {
  1225. data.body = parsedBody;
  1226. }
  1227. data.headers = Object.assign({}, request.headers);
  1228. return promises.length ? Promise.all(promises).then(() => data) : data;
  1229. }
  1230. };
  1231. __name(_RequestParser, "RequestParser");
  1232. var RequestParser = _RequestParser;
  1233. // src/route-registry.js
  1234. var import_js_format16 = require("@e22m4u/js-format");
  1235. var import_js_path_trie = require("@e22m4u/js-path-trie");
  1236. var import_js_service2 = require("@e22m4u/js-service");
  1237. var _RouteRegistry = class _RouteRegistry extends DebuggableService {
  1238. /**
  1239. * Constructor.
  1240. *
  1241. * @param {ServiceContainer} container
  1242. */
  1243. constructor(container) {
  1244. super(container);
  1245. this._trie = new import_js_path_trie.PathTrie();
  1246. }
  1247. /**
  1248. * Define route.
  1249. *
  1250. * @param {import('./route.js').RouteDefinition} routeDef
  1251. * @returns {Route}
  1252. */
  1253. defineRoute(routeDef) {
  1254. const debug = this.getDebuggerFor(this.defineRoute);
  1255. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  1256. throw new import_js_format16.Errorf(
  1257. "The route definition should be an Object, but %v was given.",
  1258. routeDef
  1259. );
  1260. const route = new Route(routeDef);
  1261. const triePath = `${route.method}/${route.path}`;
  1262. this._trie.add(triePath, route);
  1263. debug(
  1264. "The route %s %v was registered.",
  1265. route.method.toUpperCase(),
  1266. route.path
  1267. );
  1268. return route;
  1269. }
  1270. /**
  1271. * Match route by request.
  1272. *
  1273. * @param {import('http').IncomingRequest} request
  1274. * @returns {ResolvedRoute|undefined}
  1275. */
  1276. matchRouteByRequest(request) {
  1277. const debug = this.getDebuggerFor(this.matchRouteByRequest);
  1278. const requestPath = (request.url || "/").replace(/\?.*$/, "");
  1279. debug(
  1280. "Matching routes with the request %s %v.",
  1281. request.method.toUpperCase(),
  1282. requestPath
  1283. );
  1284. const rawTriePath = `${request.method.toUpperCase()}/${requestPath}`;
  1285. const triePath = rawTriePath.replace(/\/+/g, "/");
  1286. const resolved = this._trie.match(triePath);
  1287. if (resolved) {
  1288. const route = resolved.value;
  1289. debug(
  1290. "The route %s %v was matched.",
  1291. route.method.toUpperCase(),
  1292. route.path
  1293. );
  1294. const paramNames = Object.keys(resolved.params);
  1295. if (paramNames.length) {
  1296. paramNames.forEach((name) => {
  1297. debug(
  1298. "The path parameter %v had the value %v.",
  1299. name,
  1300. resolved.params[name]
  1301. );
  1302. });
  1303. } else {
  1304. debug("No path parameters found.");
  1305. }
  1306. return { route, params: resolved.params };
  1307. }
  1308. debug(
  1309. "No matched route for the request %s %v.",
  1310. request.method.toUpperCase(),
  1311. requestPath
  1312. );
  1313. }
  1314. };
  1315. __name(_RouteRegistry, "RouteRegistry");
  1316. var RouteRegistry = _RouteRegistry;
  1317. // src/request-context.js
  1318. var import_js_format17 = require("@e22m4u/js-format");
  1319. var import_js_service3 = require("@e22m4u/js-service");
  1320. var _RequestContext = class _RequestContext {
  1321. /**
  1322. * Service container.
  1323. *
  1324. * @type {ServiceContainer}
  1325. */
  1326. _container;
  1327. /**
  1328. * Getter of service container.
  1329. *
  1330. * @type {ServiceContainer}
  1331. */
  1332. get container() {
  1333. return this._container;
  1334. }
  1335. /**
  1336. * Request.
  1337. *
  1338. * @type {import('http').IncomingMessage}
  1339. */
  1340. _request;
  1341. /**
  1342. * Getter of request.
  1343. *
  1344. * @type {import('http').IncomingMessage}
  1345. */
  1346. get request() {
  1347. return this._request;
  1348. }
  1349. /**
  1350. * Response.
  1351. *
  1352. * @type {import('http').ServerResponse}
  1353. */
  1354. _response;
  1355. /**
  1356. * Getter of response.
  1357. *
  1358. * @type {import('http').ServerResponse}
  1359. */
  1360. get response() {
  1361. return this._response;
  1362. }
  1363. /**
  1364. * Route
  1365. *
  1366. * @type {Route}
  1367. */
  1368. _route;
  1369. /**
  1370. * Getter of route.
  1371. *
  1372. * @type {Route}
  1373. */
  1374. get route() {
  1375. return this._route;
  1376. }
  1377. /**
  1378. * Query.
  1379. *
  1380. * @type {object}
  1381. */
  1382. query = {};
  1383. /**
  1384. * Path parameters.
  1385. *
  1386. * @type {object}
  1387. */
  1388. params = {};
  1389. /**
  1390. * Headers.
  1391. *
  1392. * @type {object}
  1393. */
  1394. headers = {};
  1395. /**
  1396. * Parsed cookies.
  1397. *
  1398. * @type {object}
  1399. */
  1400. cookies = {};
  1401. /**
  1402. * Parsed body.
  1403. *
  1404. * @type {*}
  1405. */
  1406. body;
  1407. /**
  1408. * State.
  1409. *
  1410. * @type {object}
  1411. */
  1412. state = {};
  1413. /**
  1414. * Route meta.
  1415. *
  1416. * @type {import('./route.js').RouteMeta}
  1417. */
  1418. get meta() {
  1419. return this.route.meta;
  1420. }
  1421. /**
  1422. * Method.
  1423. *
  1424. * @returns {string}
  1425. */
  1426. get method() {
  1427. return this.request.method.toUpperCase();
  1428. }
  1429. /**
  1430. * Path.
  1431. *
  1432. * @returns {string}
  1433. */
  1434. get path() {
  1435. return this.request.url;
  1436. }
  1437. /**
  1438. * Pathname.
  1439. *
  1440. * @type {string|undefined}
  1441. * @private
  1442. */
  1443. _pathname = void 0;
  1444. /**
  1445. * Pathname.
  1446. *
  1447. * @returns {string}
  1448. */
  1449. get pathname() {
  1450. if (this._pathname != null) return this._pathname;
  1451. this._pathname = getRequestPathname(this.request);
  1452. return this._pathname;
  1453. }
  1454. /**
  1455. * Constructor.
  1456. *
  1457. * @param {ServiceContainer} container
  1458. * @param {import('http').IncomingMessage} request
  1459. * @param {import('http').ServerResponse} response
  1460. * @param {Route} route
  1461. */
  1462. constructor(container, request, response, route) {
  1463. if (!(0, import_js_service3.isServiceContainer)(container))
  1464. throw new import_js_format17.Errorf(
  1465. 'The parameter "container" of RequestContext.constructor should be an instance of ServiceContainer, but %v was given.',
  1466. container
  1467. );
  1468. this._container = container;
  1469. if (!request || typeof request !== "object" || Array.isArray(request) || !isReadableStream(request)) {
  1470. throw new import_js_format17.Errorf(
  1471. 'The parameter "request" of RequestContext.constructor should be an instance of IncomingMessage, but %v was given.',
  1472. request
  1473. );
  1474. }
  1475. this._request = request;
  1476. if (!response || typeof response !== "object" || Array.isArray(response) || !isWritableStream(response)) {
  1477. throw new import_js_format17.Errorf(
  1478. 'The parameter "response" of RequestContext.constructor should be an instance of ServerResponse, but %v was given.',
  1479. response
  1480. );
  1481. }
  1482. this._response = response;
  1483. if (!(route instanceof Route)) {
  1484. throw new import_js_format17.Errorf(
  1485. 'The parameter "route" of RequestContext.constructor should be an instance of Route, but %v was given.',
  1486. route
  1487. );
  1488. }
  1489. this._route = route;
  1490. }
  1491. };
  1492. __name(_RequestContext, "RequestContext");
  1493. var RequestContext = _RequestContext;
  1494. // src/trie-router.js
  1495. var import_js_service4 = require("@e22m4u/js-service");
  1496. var import_http4 = require("http");
  1497. // src/senders/data-sender.js
  1498. var import_js_format18 = require("@e22m4u/js-format");
  1499. var _DataSender = class _DataSender extends DebuggableService {
  1500. /**
  1501. * Send.
  1502. *
  1503. * @param {import('http').ServerResponse} response
  1504. * @param {*} data
  1505. * @returns {undefined}
  1506. */
  1507. send(response, data) {
  1508. const debug = this.getDebuggerFor(this.send);
  1509. if (data === response || response.headersSent) {
  1510. debug(
  1511. "Response sending was skipped because its headers where sent already."
  1512. );
  1513. return;
  1514. }
  1515. if (data == null) {
  1516. response.statusCode = 204;
  1517. response.end();
  1518. debug("The empty response was sent.");
  1519. return;
  1520. }
  1521. if (isReadableStream(data)) {
  1522. response.setHeader("Content-Type", "application/octet-stream");
  1523. data.pipe(response);
  1524. debug("The stream response was sent.");
  1525. return;
  1526. }
  1527. let debugMsg;
  1528. switch (typeof data) {
  1529. case "object":
  1530. case "boolean":
  1531. case "number":
  1532. if (Buffer.isBuffer(data)) {
  1533. response.setHeader("content-type", "application/octet-stream");
  1534. debugMsg = "The Buffer was sent as binary data.";
  1535. } else {
  1536. response.setHeader("content-type", "application/json");
  1537. debugMsg = (0, import_js_format18.format)("The %v was sent as JSON.", typeof data);
  1538. data = JSON.stringify(data);
  1539. }
  1540. break;
  1541. default:
  1542. response.setHeader("content-type", "text/plain");
  1543. debugMsg = "The response data was sent as plain text.";
  1544. data = String(data);
  1545. break;
  1546. }
  1547. response.end(data);
  1548. debug(debugMsg);
  1549. }
  1550. };
  1551. __name(_DataSender, "DataSender");
  1552. var DataSender = _DataSender;
  1553. // src/senders/error-sender.js
  1554. var import_util = require("util");
  1555. var import_statuses = __toESM(require("statuses"), 1);
  1556. var EXPOSED_ERROR_PROPERTIES = ["code", "details"];
  1557. var _ErrorSender = class _ErrorSender extends DebuggableService {
  1558. /**
  1559. * Handle.
  1560. *
  1561. * @param {import('http').IncomingMessage} request
  1562. * @param {import('http').ServerResponse} response
  1563. * @param {Error} error
  1564. * @returns {undefined}
  1565. */
  1566. send(request, response, error) {
  1567. const debug = this.getDebuggerFor(this.send);
  1568. let safeError = {};
  1569. if (error) {
  1570. if (typeof error === "object") {
  1571. safeError = error;
  1572. } else {
  1573. safeError = { message: String(error) };
  1574. }
  1575. }
  1576. const statusCode = error.statusCode || error.status || 500;
  1577. const body = { error: {} };
  1578. if (safeError.message && typeof safeError.message === "string") {
  1579. body.error.message = safeError.message;
  1580. } else {
  1581. body.error.message = (0, import_statuses.default)(statusCode);
  1582. }
  1583. EXPOSED_ERROR_PROPERTIES.forEach((name) => {
  1584. if (name in safeError) body.error[name] = safeError[name];
  1585. });
  1586. const requestData = {
  1587. url: request.url,
  1588. method: request.method,
  1589. headers: request.headers
  1590. };
  1591. const inspectOptions = {
  1592. showHidden: false,
  1593. depth: null,
  1594. colors: true,
  1595. compact: false
  1596. };
  1597. console.warn((0, import_util.inspect)(requestData, inspectOptions));
  1598. console.warn((0, import_util.inspect)(body, inspectOptions));
  1599. if (error.stack) {
  1600. console.log(error.stack);
  1601. } else {
  1602. console.error(error);
  1603. }
  1604. response.statusCode = statusCode;
  1605. response.setHeader("content-type", "application/json; charset=utf-8");
  1606. response.end(JSON.stringify(body, null, 2), "utf-8");
  1607. debug(
  1608. "The %s error was sent for the request %s %v.",
  1609. statusCode,
  1610. request.method,
  1611. getRequestPathname(request)
  1612. );
  1613. }
  1614. /**
  1615. * Send 404.
  1616. *
  1617. * @param {import('http').IncomingMessage} request
  1618. * @param {import('http').ServerResponse} response
  1619. * @returns {undefined}
  1620. */
  1621. send404(request, response) {
  1622. const debug = this.getDebuggerFor(this.send404);
  1623. response.statusCode = 404;
  1624. response.setHeader("content-type", "text/plain; charset=utf-8");
  1625. response.end("404 Not Found", "utf-8");
  1626. debug(
  1627. "The 404 error was sent for the request %s %v.",
  1628. request.method,
  1629. getRequestPathname(request)
  1630. );
  1631. }
  1632. };
  1633. __name(_ErrorSender, "ErrorSender");
  1634. var ErrorSender = _ErrorSender;
  1635. // src/trie-router.js
  1636. var _TrieRouter = class _TrieRouter extends DebuggableService {
  1637. /**
  1638. * Define route.
  1639. *
  1640. * Example 1:
  1641. * ```
  1642. * const router = new TrieRouter();
  1643. * router.defineRoute({
  1644. * method: HttpMethod.GET, // Request method.
  1645. * path: '/', // Path template.
  1646. * handler: ctx => 'Hello world!', // Request handler.
  1647. * });
  1648. * ```
  1649. *
  1650. * Example 2:
  1651. * ```
  1652. * const router = new TrieRouter();
  1653. * router.defineRoute({
  1654. * method: HttpMethod.POST, // Request method.
  1655. * path: '/users/:id', // The path template may have parameters.
  1656. * preHandler(ctx) { ... }, // The "preHandler" executes before a route handler.
  1657. * handler(ctx) { ... }, // Request handler function.
  1658. * postHandler(ctx, data) { ... }, // The "postHandler" executes after a route handler.
  1659. * });
  1660. * ```
  1661. *
  1662. * @param {import('./route-registry.js').RouteDefinition} routeDef
  1663. * @returns {import('./route.js').Route}
  1664. */
  1665. defineRoute(routeDef) {
  1666. return this.getService(RouteRegistry).defineRoute(routeDef);
  1667. }
  1668. /**
  1669. * Request listener.
  1670. *
  1671. * Example:
  1672. * ```
  1673. * import http from 'http';
  1674. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1675. *
  1676. * const router = new TrieRouter();
  1677. * const server = new http.Server();
  1678. * server.on('request', router.requestListener); // Sets the request listener.
  1679. * server.listen(3000); // Starts listening for connections.
  1680. * ```
  1681. *
  1682. * @returns {Function}
  1683. */
  1684. get requestListener() {
  1685. return this._handleRequest.bind(this);
  1686. }
  1687. /**
  1688. * Handle incoming request.
  1689. *
  1690. * @param {import('http').IncomingMessage} request
  1691. * @param {import('http').ServerResponse} response
  1692. * @returns {Promise<undefined>}
  1693. * @private
  1694. */
  1695. async _handleRequest(request, response) {
  1696. const debug = this.getDebuggerFor(this._handleRequest);
  1697. const requestPath = (request.url || "/").replace(/\?.*$/, "");
  1698. debug(
  1699. "Preparing to handle an incoming request %s %v.",
  1700. request.method,
  1701. requestPath
  1702. );
  1703. const resolved = this.getService(RouteRegistry).matchRouteByRequest(request);
  1704. if (!resolved) {
  1705. debug("No route for the request %s %v.", request.method, requestPath);
  1706. this.getService(ErrorSender).send404(request, response);
  1707. } else {
  1708. const { route, params } = resolved;
  1709. const container = new import_js_service4.ServiceContainer(this.container);
  1710. const context = new RequestContext(container, request, response, route);
  1711. container.set(RequestContext, context);
  1712. container.set(import_http4.IncomingMessage, request);
  1713. container.set(import_http4.ServerResponse, response);
  1714. context.params = params;
  1715. let data;
  1716. try {
  1717. const reqDataOrPromise = this.getService(RequestParser).parse(request);
  1718. if (isPromise(reqDataOrPromise)) {
  1719. const reqData = await reqDataOrPromise;
  1720. Object.assign(context, reqData);
  1721. } else {
  1722. Object.assign(context, reqDataOrPromise);
  1723. }
  1724. const hookInvoker = this.getService(HookInvoker);
  1725. data = hookInvoker.invokeAndContinueUntilValueReceived(
  1726. route,
  1727. RouterHookType.PRE_HANDLER,
  1728. response,
  1729. context
  1730. );
  1731. if (isPromise(data)) data = await data;
  1732. if (!isResponseSent(response) && data == null) {
  1733. data = route.handle(context);
  1734. if (isPromise(data)) data = await data;
  1735. let postHandlerData = hookInvoker.invokeAndContinueUntilValueReceived(
  1736. route,
  1737. RouterHookType.POST_HANDLER,
  1738. response,
  1739. context,
  1740. data
  1741. );
  1742. if (isPromise(postHandlerData))
  1743. postHandlerData = await postHandlerData;
  1744. if (postHandlerData != null) data = postHandlerData;
  1745. }
  1746. } catch (error) {
  1747. this.getService(ErrorSender).send(request, response, error);
  1748. return;
  1749. }
  1750. if (!isResponseSent(response)) {
  1751. this.getService(DataSender).send(response, data);
  1752. }
  1753. }
  1754. }
  1755. /**
  1756. * Add hook.
  1757. *
  1758. * Example:
  1759. * ```
  1760. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1761. * import {RouterHookType} from '@e22m4u/js-trie-router';
  1762. *
  1763. * // Router instance.
  1764. * const router = new TrieRouter();
  1765. *
  1766. * // Adds the "preHandler" hook for each route.
  1767. * router.addHook(
  1768. * RouterHookType.PRE_HANDLER,
  1769. * ctx => { ... },
  1770. * );
  1771. *
  1772. * // Adds the "postHandler" hook for each route.
  1773. * router.addHook(
  1774. * RouterHookType.POST_HANDLER,
  1775. * ctx => { ... },
  1776. * );
  1777. * ```
  1778. *
  1779. * @param {string} type
  1780. * @param {Function} hook
  1781. * @returns {this}
  1782. */
  1783. addHook(type, hook) {
  1784. this.getService(HookRegistry).addHook(type, hook);
  1785. return this;
  1786. }
  1787. /**
  1788. * Add pre-handler hook.
  1789. *
  1790. * @param {Function} hook
  1791. * @returns {this}
  1792. */
  1793. addPreHandler(hook) {
  1794. this.getService(HookRegistry).addHook(RouterHookType.PRE_HANDLER, hook);
  1795. return this;
  1796. }
  1797. /**
  1798. * Add post-handler hook.
  1799. *
  1800. * @param {Function} hook
  1801. * @returns {this}
  1802. */
  1803. addPostHandler(hook) {
  1804. this.getService(HookRegistry).addHook(RouterHookType.POST_HANDLER, hook);
  1805. return this;
  1806. }
  1807. };
  1808. __name(_TrieRouter, "TrieRouter");
  1809. var TrieRouter = _TrieRouter;
  1810. // Annotate the CommonJS export names for ESM import in node:
  1811. 0 && (module.exports = {
  1812. BodyParser,
  1813. CHARACTER_ENCODING_LIST,
  1814. CookiesParser,
  1815. DataSender,
  1816. EXPOSED_ERROR_PROPERTIES,
  1817. ErrorSender,
  1818. HookInvoker,
  1819. HookRegistry,
  1820. HttpMethod,
  1821. METHODS_WITH_BODY,
  1822. QueryParser,
  1823. RequestContext,
  1824. RequestParser,
  1825. Route,
  1826. RouteRegistry,
  1827. RouterHookType,
  1828. RouterOptions,
  1829. TrieRouter,
  1830. UNPARSABLE_MEDIA_TYPES,
  1831. cloneDeep,
  1832. createCookieString,
  1833. createError,
  1834. createRequestMock,
  1835. createResponseMock,
  1836. createRouteMock,
  1837. fetchRequestBody,
  1838. getRequestPathname,
  1839. isPromise,
  1840. isReadableStream,
  1841. isResponseSent,
  1842. isWritableStream,
  1843. parseContentType,
  1844. parseCookieString,
  1845. parseJsonBody,
  1846. toCamelCase
  1847. });