UNPKG

rexuws

Version:

An express-like framework built on top of uWebsocket.js aims at simple codebase and high performance

147 lines (143 loc) 5.39 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMime = exports.toArrayBuffer = exports.hasAsync = exports.readBody = exports.extractParamsPath = exports.notFoundHtml = exports.toHtml = exports.getParamNames = exports.setCharset = exports.charsetRegExp = void 0; /* eslint-disable prefer-rest-params */ const content_type_1 = __importDefault(require("content-type")); const mmmagic_1 = __importStar(require("mmmagic")); const util_1 = __importDefault(require("util")); exports.charsetRegExp = /;\s*charset\s*=/; const setCharset = function setCharset(type, charset) { if (!type || !charset) { return type; } // parse type const parsed = content_type_1.default.parse(type); // set charset parsed.parameters.charset = charset; // format type return content_type_1.default.format(parsed); }; exports.setCharset = setCharset; const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm; const ARGUMENT_NAMES = /([^\s,]+)/g; const getParamNames = (func) => { const fnStr = func.toString().replace(STRIP_COMMENTS, ''); let result = fnStr .slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')) .match(ARGUMENT_NAMES); if (result === null) result = []; return result; }; exports.getParamNames = getParamNames; const toHtml = (str, title = 'Error') => `<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>${title}</title> </head> <body> <pre>${str}</pre> </body> </html>`; exports.toHtml = toHtml; const notFoundHtml = (method, path) => exports.toHtml(`Cannot ${method.toUpperCase()} ${path}`, 'Not found'); exports.notFoundHtml = notFoundHtml; const extractParamsPath = (path) => path === '/' ? { path: '/', parametersMap: [], basePath: '', } : path.split('/').reduce((acc, cur) => { if ((cur.indexOf('*') > 0 || (cur.indexOf('*') === 0 && cur.length > 1)) && cur.indexOf(':') === -1) // eslint-disable-next-line no-param-reassign cur = `:value${acc.parametersMap.length + 1 || 1}`; if (cur.indexOf(':') !== -1) { const paramPart = cur.split(':'); acc.basePath += `/:value${acc.parametersMap.length + 1 || 1}`; acc.parametersMap.push(paramPart[paramPart.length - 1]); acc.path += `/:${paramPart[paramPart.length - 1]}`; return acc; } if (cur) { acc.path += `/${cur}`; acc.basePath += `/${cur}`; } return acc; }, { parametersMap: [], path: '', basePath: '', }); exports.extractParamsPath = extractParamsPath; const readBody = (res, cb) => { let buffer; /* Register data cb */ res.onData((ab, isLast) => { const chunk = Buffer.from(ab); if (isLast) { if (buffer) { cb(Buffer.concat([buffer, chunk])); } else { cb(chunk); } } else { buffer = buffer ? Buffer.concat([buffer, chunk]) : Buffer.concat([chunk]); } }); }; exports.readBody = readBody; const hasAsync = (logger, es5 = true) => { const hasLogged = false; return (fn) => { if (fn.constructor.name === 'AsyncFunction') return true; if (!es5) return false; const str = fn.toString(); if (!str) { if (!hasLogged) logger.warn("You are using bytenodes build which does not allow function.toString() to check whether the ES5 function has __generator / __awaiter (that's how typescript compiled AsyncFunction to ES5). All middlewares will be treated as AsyncFunction"); return true; } return (str.indexOf('__generator(') !== -1 && str.indexOf('__awaiter(') !== -1); }; }; exports.hasAsync = hasAsync; /** * This code was taken from uWebSockets.js examples * * @see https://github.com/uNetworking/uWebSockets.js/blob/master/examples/VideoStreamer.js * @param buffer */ const toArrayBuffer = (buffer) => buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); exports.toArrayBuffer = toArrayBuffer; const magic = new mmmagic_1.default.Magic(mmmagic_1.MAGIC_MIME_TYPE); exports.getMime = util_1.default.promisify(magic.detectFile).bind(magic);