index.cjs 57 KB

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