@tinyhttp/app
Advanced tools
Comparing version 0.2.5 to 0.2.6
# @tinyhttp/app | ||
## 0.2.6 | ||
### Patch Changes | ||
- Return compression back | ||
- Updated dependencies [undefined] | ||
- @tinyhttp/cookie@0.1.2 | ||
- @tinyhttp/cookie-signature@0.1.2 | ||
- @tinyhttp/etag@0.2.2 | ||
## 0.2.5 | ||
@@ -4,0 +14,0 @@ |
@@ -1,533 +0,1 @@ | ||
import { STATUS_CODES, METHODS, createServer } from 'http'; | ||
import rg from 'regexparam'; | ||
import { parse } from 'url'; | ||
import parseRange from 'range-parser'; | ||
import proxyAddr from 'proxy-addr'; | ||
import Accepts from 'es-accepts'; | ||
import fresh from 'es-fresh'; | ||
import { sign } from '@tinyhttp/cookie-signature'; | ||
import { lookup } from 'es-mime-types'; | ||
import { serialize } from '@tinyhttp/cookie'; | ||
import { format, parse as parse$1 } from 'es-content-type'; | ||
import etag from '@tinyhttp/etag'; | ||
const compileTrust = (val) => { | ||
if (typeof val === 'function') | ||
return val; | ||
if (val === true) { | ||
// Support plain true/false | ||
return function () { | ||
return true; | ||
}; | ||
} | ||
if (typeof val === 'number') { | ||
// Support trusting hop count | ||
return (_, i) => { | ||
if (val) { | ||
return i < val; | ||
} | ||
}; | ||
} | ||
if (typeof val === 'string') { | ||
// Support comma-separated values | ||
val = val.split(/ *, */); | ||
} | ||
return proxyAddr.compile(val || []); | ||
}; | ||
const rgExec = (path, result) => { | ||
let i = 0, out = {}; | ||
let matches = result.pattern.exec(path); | ||
while (i < result.keys.length) { | ||
out[result.keys[i]] = (matches === null || matches === void 0 ? void 0 : matches[++i]) || null; | ||
} | ||
return out; | ||
}; | ||
const getQueryParams = (url = '/') => { | ||
return parse(url, true).query; | ||
}; | ||
const getURLParams = (reqUrl = '/', url = '/') => { | ||
return rgExec(reqUrl, rg(url)); | ||
}; | ||
const getRouteFromApp = (app, handler) => { | ||
return app.middleware.find((h) => h.handler.name === handler.name); | ||
}; | ||
const getProtocol = (req) => { | ||
const proto = req.connection.encrypted ? 'https' : 'http'; | ||
if (!compileTrust(req.connection.remoteAddress)) { | ||
return proto; | ||
} | ||
const header = req.headers['X-Forwarded-Proto'] || proto; | ||
const index = header.indexOf(','); | ||
return index !== -1 ? header.substring(0, index).trim() : header.trim(); | ||
}; | ||
const getRequestHeader = (req) => (header) => { | ||
const lc = header.toLowerCase(); | ||
switch (lc) { | ||
case 'referer': | ||
case 'referrer': | ||
return req.headers.referrer || req.headers.referer; | ||
default: | ||
return req.headers[lc]; | ||
} | ||
}; | ||
const setRequestHeader = (req) => (field, value) => { | ||
return (req.headers[field.toLowerCase()] = value); | ||
}; | ||
const getRangeFromHeader = (req) => (size, options) => { | ||
const range = req.get('Range'); | ||
if (!range) | ||
return; | ||
return parseRange(size, range, options); | ||
}; | ||
const checkIfXMLHttpRequest = (req) => { | ||
if (req.headers['X-Requested-With'] === 'XMLHttpRequest') { | ||
return true; | ||
} | ||
else { | ||
return false; | ||
} | ||
}; | ||
const getHostname = (req) => { | ||
let host = req.get('X-Forwarded-Host'); | ||
if (!host || !compileTrust(req.connection.remoteAddress)) { | ||
host = req.get('Host'); | ||
} | ||
if (!host) | ||
return; | ||
// IPv6 literal support | ||
const offset = host[0] === '[' ? host.indexOf(']') + 1 : 0; | ||
const index = host.indexOf(':', offset); | ||
return index !== -1 ? host.substring(0, index) : host; | ||
}; | ||
const getIP = (req) => { | ||
return proxyAddr(req, compileTrust); | ||
}; | ||
// export const getRequestIs = (types: string | string[], ...args: string[]) => (req: Request) => { | ||
// let arr = types | ||
// if (!Array.isArray(types)) { | ||
// arr = new Array(args.length) | ||
// for (let i = 0; i < arr.length; i++) { | ||
// arr[i] = args[i] | ||
// } | ||
// } | ||
// } | ||
const getFreshOrStale = (req, res) => { | ||
const method = req.method; | ||
const status = res.statusCode; | ||
// GET or HEAD for weak freshness validation only | ||
if (method !== 'GET' && method !== 'HEAD') | ||
return false; | ||
// 2xx or 304 as per rfc2616 14.26 | ||
if ((status >= 200 && status < 300) || 304 === status) { | ||
const resHeaders = { | ||
etag: res.get('ETag'), | ||
'last-modified': res.get('Last-Modified'), | ||
}; | ||
return fresh(req.headers, resHeaders); | ||
} | ||
return false; | ||
}; | ||
const getAccepts = (req) => (...types) => { | ||
return new Accepts(req).types(types); | ||
}; | ||
const onErrorHandler = (err, _req, res) => { | ||
const code = (res.statusCode = err.code || err.status || 500); | ||
if (typeof err === 'string' || Buffer.isBuffer(err)) | ||
res.end(err); | ||
else | ||
res.end(err.message || STATUS_CODES[code]); | ||
}; | ||
const isAsync = (fn) => fn[Symbol.toStringTag] === 'AsyncFunction'; | ||
const createMiddlewareFromRoute = ({ path, handler, method, }) => ({ | ||
method, | ||
handler: handler || path, | ||
path: typeof path === 'string' ? path : '/', | ||
}); | ||
const pushMiddleware = (mw) => ({ path, handler, method, handlers, type, }) => { | ||
const m = createMiddlewareFromRoute({ path, handler, method, type }); | ||
const waresFromHandlers = handlers.map((handler) => ({ | ||
handler, | ||
})); | ||
for (const mdw of [m, ...waresFromHandlers]) { | ||
mw.push({ ...mdw, type }); | ||
} | ||
}; | ||
class Router { | ||
get(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'GET', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
post(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'POST', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
put(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'PUT', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
patch(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'PATCH', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
head(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'HEAD', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
delete(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'DELETE', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
options(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
handlers, | ||
method: 'OPTIONS', | ||
type: 'route', | ||
}); | ||
return this; | ||
} | ||
all(path, handler, ...handlers) { | ||
for (const method of METHODS) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler, | ||
method, | ||
handlers, | ||
type: 'route', | ||
}); | ||
} | ||
return this; | ||
} | ||
use(path, handler, ...handlers) { | ||
pushMiddleware(this.middleware)({ | ||
path, | ||
handler: typeof path === 'string' ? handler : path, | ||
handlers, | ||
type: 'mw', | ||
}); | ||
return this; | ||
} | ||
} | ||
const createETag = (body, encoding) => { | ||
const buf = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body; | ||
return etag(buf, { weak: true }); | ||
}; | ||
function setCharset(type, charset) { | ||
const parsed = parse$1(type); | ||
parsed.parameters.charset = charset; | ||
return format(parsed); | ||
} | ||
const json = (_req, res) => (body, ...args) => { | ||
res.setHeader('Content-Type', 'application/json'); | ||
if (typeof body === 'object' && body != null) { | ||
res.end(JSON.stringify(body, null, 2), ...args); | ||
} | ||
else if (typeof body === 'string') { | ||
res.end(body, ...args); | ||
} | ||
return res; | ||
}; | ||
const send = (req, res) => (body) => { | ||
let bodyToSend = body; | ||
// in case of object - turn it to json | ||
if (typeof body === 'object' && body !== null) { | ||
bodyToSend = JSON.stringify(body, null, 2); | ||
} | ||
else { | ||
if (typeof body === 'string') { | ||
// reflect this in content-type | ||
const type = res.getHeader('Content-Type'); | ||
if (typeof type === 'string') { | ||
res.setHeader('Content-Type', setCharset(type, 'utf-8')); | ||
} | ||
} | ||
} | ||
// Set encoding | ||
const encoding = 'utf8'; | ||
// populate ETag | ||
let etag; | ||
if (!res.getHeader('etag') && (etag = createETag(bodyToSend, encoding))) { | ||
res.setHeader('etag', etag); | ||
} | ||
// strip irrelevant headers | ||
if (res.statusCode === 204 || res.statusCode === 304) { | ||
res.removeHeader('Content-Type'); | ||
res.removeHeader('Content-Length'); | ||
res.removeHeader('Transfer-Encoding'); | ||
bodyToSend = ''; | ||
} | ||
if (req.method === 'HEAD') { | ||
res.end(''); | ||
} | ||
if (typeof body === 'object') { | ||
if (body === null) { | ||
res.end(''); | ||
} | ||
else if (Buffer.isBuffer(body)) { | ||
if (!res.getHeader('Content-Type')) { | ||
res.setHeader('content-type', 'application/octet-stream'); | ||
} | ||
} | ||
else { | ||
json(req, res)(bodyToSend, encoding) | ||
; | ||
} | ||
} | ||
else { | ||
{ | ||
// respond with encoding | ||
res.end(bodyToSend, encoding); | ||
} | ||
} | ||
return res; | ||
}; | ||
const status = (_req, res) => (status) => { | ||
res.statusCode = status; | ||
return res; | ||
}; | ||
const setCookie = (req, res) => (name, value, options) => { | ||
const secret = req.secret; | ||
const signed = options.signed; | ||
if (signed && !secret) { | ||
throw new Error('cookieParser("secret") required for signed cookies'); | ||
} | ||
let val = typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value); | ||
if (signed) { | ||
val = 's:' + sign(val, secret); | ||
} | ||
if (options.maxAge) { | ||
options.expires = new Date(Date.now() + options.maxAge); | ||
options.maxAge /= 1000; | ||
} | ||
if (options.path == null) { | ||
options.path = '/'; | ||
} | ||
res.setHeader('Set-Cookie', serialize(name, String(val), options)); | ||
return res; | ||
}; | ||
const clearCookie = (req, res) => (name, options) => { | ||
const opts = Object.assign({}, { expires: new Date(1), path: '/' }, options); | ||
return setCookie(req, res)(name, '', opts); | ||
}; | ||
const charsetRegExp = /;\s*charset\s*=/; | ||
const setHeader = (_req, res) => (field, val) => { | ||
if (typeof field === 'string') { | ||
let value = Array.isArray(val) ? val.map(String) : String(val); | ||
// add charset to content-type | ||
if (field.toLowerCase() === 'content-type') { | ||
if (Array.isArray(value)) { | ||
throw new TypeError('Content-Type cannot be set to an Array'); | ||
} | ||
if (!charsetRegExp.test(value)) { | ||
const charset = lookup(value.split(';')[0]); | ||
if (charset) | ||
value += '; charset=' + charset.toLowerCase(); | ||
} | ||
} | ||
res.setHeader(field, value); | ||
} | ||
else { | ||
for (const key in field) { | ||
res.setHeader(key, field[key]); | ||
} | ||
} | ||
return res; | ||
}; | ||
const setLocationHeader = (req, res) => (url) => { | ||
let loc = url; | ||
// "back" is an alias for the referrer | ||
if (url === 'back') { | ||
loc = req.get('Referrer') || '/'; | ||
} | ||
// set location | ||
res.setHeader('Location', encodeURIComponent(loc)); | ||
return res; | ||
}; | ||
const getResponseHeader = (_req, res) => (field) => { | ||
return res.getHeader(field); | ||
}; | ||
const setLinksHeader = (_req, res) => (links) => { | ||
let link = res.get('Link') || ''; | ||
if (link) | ||
link += ', '; | ||
return res.set('Link', link + | ||
Object.keys(links) | ||
.map((rel) => '<' + links[rel] + '>; rel="' + rel + '"') | ||
.join(', ')); | ||
}; | ||
const sendStatus = (_req, res) => (statusCode) => { | ||
const body = STATUS_CODES[statusCode] || String(statusCode); | ||
res.statusCode = statusCode; | ||
res.set('Content-Type', 'text/plain'); | ||
return res.send(body); | ||
}; | ||
const extendMiddleware = ({ networkExtensions, freshnessTesting, }) => (req, res) => { | ||
/// Define extensions | ||
res.get = getResponseHeader(req, res); | ||
/* | ||
Request extensions | ||
*/ | ||
if (networkExtensions) { | ||
const proto = getProtocol(req); | ||
const secure = proto === 'https'; | ||
req.protocol = proto; | ||
req.secure = secure; | ||
req.connection = Object.assign(req.socket, { | ||
encrypted: secure, | ||
}); | ||
req.hostname = getHostname(req); | ||
} | ||
req.query = getQueryParams(req.url); | ||
if (freshnessTesting) { | ||
req.fresh = getFreshOrStale(req, res); | ||
req.stale = !req.fresh; | ||
} | ||
req.get = getRequestHeader(req); | ||
req.set = setRequestHeader(req); | ||
req.range = getRangeFromHeader(req); | ||
req.accepts = getAccepts(req); | ||
req.xhr = checkIfXMLHttpRequest(req); | ||
/* | ||
Response extensions | ||
*/ | ||
res.header = res.set = setHeader(req, res); | ||
res.send = send(req, res); | ||
res.json = json(req, res); | ||
res.status = status(req, res); | ||
res.sendStatus = sendStatus(req, res); | ||
res.location = setLocationHeader(req, res); | ||
res.links = setLinksHeader(req, res); | ||
res.cookie = setCookie(req, res); | ||
res.clearCookie = clearCookie(req, res); | ||
}; | ||
const applyHandler = (h) => async (req, res, next) => { | ||
if (isAsync(h)) { | ||
await h(req, res, next); | ||
} | ||
else { | ||
h(req, res, next); | ||
} | ||
}; | ||
class App extends Router { | ||
constructor(options = {}) { | ||
super(); | ||
this.locals = Object.create(null); | ||
this.middleware = []; | ||
this.onError = (options === null || options === void 0 ? void 0 : options.onError) || onErrorHandler; | ||
this.noMatchHandler = | ||
(options === null || options === void 0 ? void 0 : options.noMatchHandler) || this.onError.bind(null, { code: 404 }); | ||
this.settings = options.settings || {}; | ||
} | ||
async handler(req, res) { | ||
const mw = this.middleware; | ||
extendMiddleware(this.settings)(req, res); | ||
const noMatchMW = { | ||
handler: this.noMatchHandler, | ||
type: 'mw', | ||
path: '/', | ||
}; | ||
if (!mw.includes(noMatchMW)) | ||
mw.push(noMatchMW); | ||
let idx = 0; | ||
const len = mw.length - 1; | ||
const next = (err) => { | ||
if (err) { | ||
this.onError(err, req, res); | ||
} | ||
else { | ||
loop(); | ||
} | ||
}; | ||
const handle = (mw) => async (req, res, next) => { | ||
const { path, method, handler, type } = mw; | ||
if (type === 'route') { | ||
if (req.method === method) { | ||
// strip query parameters for req.params | ||
const queryParamStart = req.url.lastIndexOf('?'); | ||
const reqUrlWithoutParams = req.url.slice(0, queryParamStart === -1 ? req.url.length : queryParamStart); | ||
if (rg(path).pattern.test(reqUrlWithoutParams)) { | ||
req.params = getURLParams(req.url, path); | ||
req.route = getRouteFromApp(this, handler); | ||
// route found, send Success 200 | ||
res.statusCode = 200; | ||
applyHandler(handler)(req, res, next); | ||
} | ||
else { | ||
loop(); | ||
} | ||
} | ||
} | ||
else { | ||
if (req.url.startsWith(path)) { | ||
applyHandler(handler)(req, res, next); | ||
} | ||
else { | ||
loop(); | ||
} | ||
} | ||
}; | ||
if (mw.length === 1) | ||
handle(mw[0])(req, res); | ||
const loop = () => { | ||
if (!res.writableEnded) { | ||
if (idx < len) { | ||
handle(mw[idx++])(req, res, next); | ||
} | ||
} | ||
}; | ||
loop(); | ||
} | ||
listen(port, cb, host = 'localhost', backlog) { | ||
const server = createServer((req, res) => { | ||
this.handler(req, res); | ||
}); | ||
return server.listen(port, host, backlog, cb); | ||
} | ||
} | ||
export { App, Router, applyHandler, checkIfXMLHttpRequest, clearCookie, extendMiddleware, getAccepts, getFreshOrStale, getHostname, getIP, getProtocol, getQueryParams, getRangeFromHeader, getRequestHeader, getResponseHeader, getRouteFromApp, getURLParams, json, send, sendStatus, setCookie, setHeader, setLinksHeader, setLocationHeader, setRequestHeader, status }; | ||
import{STATUS_CODES as t,METHODS as e,createServer as r}from"http";import n from"regexparam";import{parse as o}from"url";import s from"range-parser";import i from"proxy-addr";import f from"es-accepts";import h from"es-fresh";import{sign as p}from"@tinyhttp/cookie-signature";import{lookup as a}from"es-mime-types";import{serialize as l}from"@tinyhttp/cookie";import{format as u,parse as c}from"es-content-type";import d from"@tinyhttp/etag";const compileTrust=t=>{if("function"==typeof t)return t;if(!0===t)return function(){return!0};if("number"==typeof t)return(e,r)=>{if(t)return r<t};if("string"==typeof t)t=t.split(/ *, */);return i.compile(t||[])},getQueryParams=(t="/")=>o(t,!0).t,getURLParams=(t="/",e="/")=>((t,e)=>{let r=0,n={},o=e.pattern.exec(t);for(;r<e.keys.length;)n[e.keys[r]]=(null==o?void 0:o[++r])||null;return n})(t,n(e)),getRouteFromApp=(t,e)=>t.o.find(t=>t.s.name===e.name),getProtocol=t=>{const e=t.connection.i?"https":"http";if(!compileTrust(t.connection.h))return e;const r=t.headers["p"]||e,n=r.indexOf(",");return-1!==n?r.substring(0,n).trim():r.trim()},getRequestHeader=t=>e=>{const r=e.toLowerCase();switch(r){case"referer":case"referrer":return t.headers.referrer||t.headers.l;default:return t.headers[r]}},setRequestHeader=t=>(e,r)=>t.headers[e.toLowerCase()]=r,getRangeFromHeader=t=>(e,r)=>{const n=t.get("Range");if(n)return s(e,n,r)},checkIfXMLHttpRequest=t=>{if("XMLHttpRequest"===t.headers["u"])return!0;else return!1},getHostname=t=>{let e=t.get("X-Forwarded-Host");if(!e||!compileTrust(t.connection.h))e=t.get("Host");if(!e)return;const r="["===e[0]?e.indexOf("]")+1:0,n=e.indexOf(":",r);return-1!==n?e.substring(0,n):e},getIP=t=>i(t,compileTrust),getFreshOrStale=(t,e)=>{const r=t.method,n=e.m;if("GET"!==r&&"HEAD"!==r)return!1;if(n>=200&&n<300||304===n){const r={g:e.get("ETag"),T:e.get("Last-Modified")};return h(t.headers,r)}return!1},getAccepts=t=>(...e)=>new f(t).types(e),onErrorHandler=(e,r,n)=>{const o=n.m=e.code||e.status||500;if("string"==typeof e||Buffer.isBuffer(e))n.end(e);else n.end(e.message||t[o])},pushMiddleware=t=>({path:e,s:r,method:n,S:o,type:s})=>{const i=(({path:t,s:e,method:r})=>({method:r,s:e||t,path:"string"==typeof t?t:"/"}))({path:e,s:r,method:n,type:s}),f=o.map(t=>({s:t}));for(const e of[i,...f])t.push({...e,type:s})};class Router{get(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"GET",type:"route"});return this}C(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"POST",type:"route"});return this}put(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"PUT",type:"route"});return this}j(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"PATCH",type:"route"});return this}head(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"HEAD",type:"route"});return this}delete(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"DELETE",type:"route"});return this}options(t,e,...r){pushMiddleware(this.o)({path:t,s:e,S:r,method:"OPTIONS",type:"route"});return this}all(t,r,...n){for(const o of e)pushMiddleware(this.o)({path:t,s:r,method:o,S:n,type:"route"});return this}k(t,e,...r){pushMiddleware(this.o)({path:t,s:"string"==typeof t?e:t,S:r,type:"mw"});return this}}const createETag=(t,e)=>{const r=!Buffer.isBuffer(t)?Buffer.from(t,e):t;return d(r,{A:!0})};const json=(t,e)=>(t,...r)=>{e.O("Content-Type","application/json");if("object"==typeof t&&null!=t)e.end(JSON.stringify(t,null,2),...r);else if("string"==typeof t)e.end(t,...r);return e},send=(t,e)=>r=>{let n=r;if("object"==typeof r&&null!==r)n=JSON.stringify(r,null,2);else if("string"==typeof r){const t=e.D("Content-Type");if("string"==typeof t)e.O("Content-Type",function(t,e){const r=c(t);r.H.charset=e;return u(r)}(t,"utf-8"))}let o;if(!e.D("etag")&&(o=createETag(n,"utf8")))e.O("etag",o);if(204===e.m||304===e.m){e.L("Content-Type");e.L("Content-Length");e.L("Transfer-Encoding");n=""}if("HEAD"===t.method)e.end("");if("object"==typeof r)if(null===r)e.end("");else if(Buffer.isBuffer(r)){if(!e.D("Content-Type"))e.O("content-type","application/octet-stream")}else json(0,e)(n,"utf8");else e.end(n,"utf8");return e},status=(t,e)=>t=>{e.m=t;return e},setCookie=(t,e)=>(r,n,o)=>{const s=t.R,i=o.P;if(i&&!s)throw new Error('cookieParser("secret") required for signed cookies');let f="object"==typeof n?"j:"+JSON.stringify(n):String(n);if(i)f="s:"+p(f,s);if(o.B){o.N=new Date(Date.now()+o.B);o.B/=1e3}if(null==o.path)o.path="/";e.O("Set-Cookie",l(r,String(f),o));return e},clearCookie=(t,e)=>(r,n)=>{const o=Object.assign({},{N:new Date(1),path:"/"},n);return setCookie(t,e)(r,"",o)},y=/;\s*charset\s*=/,setHeader=(t,e)=>(t,r)=>{if("string"==typeof t){let n=Array.isArray(r)?r.map(String):String(r);if("content-type"===t.toLowerCase()){if(Array.isArray(n))throw new TypeError("Content-Type cannot be set to an Array");if(!y.test(n)){const t=a(n.split(";")[0]);if(t)n+="; charset="+t.toLowerCase()}}e.O(t,n)}else for(const r in t)e.O(r,t[r]);return e},setLocationHeader=(t,e)=>r=>{let n=r;if("back"===r)n=t.get("Referrer")||"/";e.O("Location",encodeURIComponent(n));return e},getResponseHeader=(t,e)=>t=>e.D(t),setLinksHeader=(t,e)=>t=>{let r=e.get("Link")||"";if(r)r+=", ";return e.set("Link",r+Object.keys(t).map(e=>"<"+t[e]+'>; rel="'+e+'"').join(", "))},sendStatus=(e,r)=>e=>{const n=t[e]||String(e);r.m=e;r.set("Content-Type","text/plain");return r.send(n)},extendMiddleware=({v:t,J:e})=>(r,n)=>{n.get=getResponseHeader(0,n);if(t){const t=getProtocol(r),e="https"===t;r.protocol=t;r.q=e;r.connection=Object.assign(r.F,{i:e});r.hostname=getHostname(r)}r.t=getQueryParams(r.url);if(e){r.G=getFreshOrStale(r,n);r.I=!r.G}r.get=getRequestHeader(r);r.set=setRequestHeader(r);r.range=getRangeFromHeader(r);r.M=getAccepts(r);r.U=checkIfXMLHttpRequest(r);n.X=n.set=setHeader(0,n);n.send=send(r,n);n.json=json(0,n);n.status=status(0,n);n.K=sendStatus(0,n);n.location=setLocationHeader(r,n);n.links=setLinksHeader(0,n);n.cookie=setCookie(r,n);n.V=clearCookie(r,n)},applyHandler=t=>async(e,r,n)=>{if("AsyncFunction"===t[Symbol.toStringTag])await t(e,r,n);else t(e,r,n)};class App extends Router{constructor(t={}){super();this.W=Object.create(null);this.o=[];this.Y=(null==t?void 0:t.Y)||onErrorHandler;this.Z=(null==t?void 0:t.Z)||this.Y.bind(null,{code:404});this.$=t.$||{}}async s(t,e){const r=this.o;extendMiddleware(this.$)(t,e);const o={s:this.Z,type:"mw",path:"/"};if(!r.includes(o))r.push(o);let s=0;const i=r.length-1,next=r=>{if(r)this.Y(r,t,e);else loop()},handle=t=>async(e,r,o)=>{const{path:s,method:i,s:f,type:h}=t;if("route"===h){if(e.method===i){const t=e.url.lastIndexOf("?"),i=e.url.slice(0,-1===t?e.url.length:t);if(n(s).pattern.test(i)){e._=getURLParams(e.url,s);e.tt=getRouteFromApp(this,f);r.m=200;applyHandler(f)(e,r,o)}else loop()}}else if(e.url.startsWith(s))applyHandler(f)(e,r,o);else loop()};if(1===r.length)handle(r[0])(t,e);const loop=()=>{if(!e.et)if(s<i)handle(r[s++])(t,e,next)};loop()}rt(t,e,n="localhost",o){return r((t,e)=>{this.s(t,e)}).rt(t,n,o,e)}}export{App,Router,applyHandler,checkIfXMLHttpRequest,clearCookie,extendMiddleware,getAccepts,getFreshOrStale,getHostname,getIP,getProtocol,getQueryParams,getRangeFromHeader,getRequestHeader,getResponseHeader,getRouteFromApp,getURLParams,json,send,sendStatus,setCookie,setHeader,setLinksHeader,setLocationHeader,setRequestHeader,status}; |
import { Request } from './request'; | ||
import { Response } from './response'; | ||
export declare type NextFunction = (err?: any) => void; | ||
export declare type SyncHandler = (req: Request, res: Response, next?: NextFunction | undefined) => void; | ||
export declare type AsyncHandler = (req: Request, res: Response, next?: NextFunction | undefined) => Promise<void>; | ||
export declare type NextFunction = (err?: any) => void | undefined; | ||
export declare type SyncHandler = (req: Request, res: Response, next?: NextFunction) => void; | ||
export declare type AsyncHandler = (req: Request, res: Response, next?: NextFunction) => Promise<void>; | ||
export declare type Handler = AsyncHandler | SyncHandler; | ||
@@ -7,0 +7,0 @@ export declare type ErrorHandler = (err: any, req: Request, res: Response) => void; |
{ | ||
"name": "@tinyhttp/app", | ||
"version": "0.2.5", | ||
"version": "0.2.6", | ||
"description": "tinyhttp core with App, Request, Response and Router", | ||
@@ -47,5 +47,5 @@ "type": "module", | ||
"dependencies": { | ||
"@tinyhttp/cookie": "0.1.1", | ||
"@tinyhttp/cookie-signature": "0.1.1", | ||
"@tinyhttp/etag": "0.2.1", | ||
"@tinyhttp/cookie": "0.1.2", | ||
"@tinyhttp/cookie-signature": "0.1.2", | ||
"@tinyhttp/etag": "0.2.2", | ||
"es-accepts": "^0.0.12", | ||
@@ -52,0 +52,0 @@ "es-content-type": "^0.0.5", |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
30178
211
2
3
+ Added@tinyhttp/cookie@0.1.2(transitive)
+ Added@tinyhttp/cookie-signature@0.1.2(transitive)
+ Added@tinyhttp/etag@0.2.2(transitive)
- Removed@tinyhttp/cookie@0.1.1(transitive)
- Removed@tinyhttp/cookie-signature@0.1.1(transitive)
- Removed@tinyhttp/etag@0.2.1(transitive)
Updated@tinyhttp/cookie@0.1.2
Updated@tinyhttp/etag@0.2.2