itty-router
Advanced tools
Comparing version 4.0.11 to 4.0.12
@@ -1,66 +0,1 @@ | ||
// Create CORS function with default options. | ||
const createCors = (options = {}) => { | ||
// Destructure and set defaults for options. | ||
const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options; | ||
let allowOrigin; | ||
// Initial response headers. | ||
const rHeaders = { | ||
'content-type': 'application/json', | ||
'Access-Control-Allow-Methods': methods.join(', '), | ||
...headers, | ||
}; | ||
// Set max age if provided. | ||
if (maxAge) | ||
rHeaders['Access-Control-Max-Age'] = maxAge; | ||
// Pre-flight function. | ||
const preflight = (r) => { | ||
// Use methods set. | ||
const useMethods = [...new Set(['OPTIONS', ...methods])]; | ||
const origin = r.headers.get('origin') || ''; | ||
// Set allowOrigin globally. | ||
allowOrigin = (origins.includes(origin) || origins.includes('*')) && { | ||
'Access-Control-Allow-Origin': origin, | ||
}; | ||
// Check if method is OPTIONS. | ||
if (r.method === 'OPTIONS') { | ||
const reqHeaders = { | ||
...rHeaders, | ||
'Access-Control-Allow-Methods': useMethods.join(', '), | ||
'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'), | ||
...allowOrigin, | ||
}; | ||
// Handle CORS pre-flight request. | ||
return new Response(null, { | ||
headers: r.headers.get('Origin') && | ||
r.headers.get('Access-Control-Request-Method') && | ||
r.headers.get('Access-Control-Request-Headers') | ||
? reqHeaders | ||
: { Allow: useMethods.join(', ') }, | ||
}); | ||
} | ||
}; | ||
// Corsify function. | ||
const corsify = (response) => { | ||
if (!response) | ||
throw new Error('No fetch handler responded and no upstream to proxy to specified.'); | ||
const { headers, status, body } = response; | ||
// Bypass for protocol shifts or redirects, or if CORS is already set. | ||
if ([101, 301, 302, 308].includes(status) || | ||
headers.get('access-control-allow-origin')) | ||
return response; | ||
// Return new response with CORS headers. | ||
return new Response(body, { | ||
status, | ||
headers: { | ||
...Object.fromEntries(headers), | ||
...rHeaders, | ||
...allowOrigin, | ||
'content-type': headers.get('content-type'), | ||
}, | ||
}); | ||
}; | ||
// Return corsify and preflight methods. | ||
return { corsify, preflight }; | ||
}; | ||
export { createCors }; | ||
"use strict";exports.createCors=(e={})=>{const{origins:s=["*"],maxAge:o,methods:t=["GET"],headers:n={}}=e;let r;const c={"content-type":"application/json","Access-Control-Allow-Methods":t.join(", "),...n};o&&(c["Access-Control-Max-Age"]=o);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:s,status:o,body:t}=e;return[101,301,302,308].includes(o)||s.get("access-control-allow-origin")?e:new Response(t,{status:o,headers:{...Object.fromEntries(s),...c,...r,"content-type":s.get("content-type")}})},preflight:e=>{const o=[...new Set(["OPTIONS",...t])],n=e.headers.get("origin")||"";if(r=(s.includes(n)||s.includes("*"))&&{"Access-Control-Allow-Origin":n},"OPTIONS"===e.method){const s={...c,"Access-Control-Allow-Methods":o.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...r};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?s:{Allow:o.join(", ")}})}}}}; |
@@ -1,14 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
export { createResponse }; | ||
"use strict";exports.createResponse=(e="text/plain; charset=utf-8",t)=>(s,n={})=>{const{headers:r={},...o}=n;return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})}; |
43
error.js
@@ -1,42 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const json = createResponse('application/json; charset=utf-8', JSON.stringify); | ||
const getMessage = (code) => { | ||
return ({ | ||
400: 'Bad Request', | ||
401: 'Unauthorized', | ||
403: 'Forbidden', | ||
404: 'Not Found', | ||
500: 'Internal Server Error', | ||
}[code] || 'Unknown Error'); | ||
}; | ||
const error = (a = 500, b) => { | ||
// handle passing an Error | StatusError directly in | ||
if (a instanceof Error) { | ||
const { message, ...err } = a; | ||
a = a.status || 500; | ||
b = { | ||
error: message || getMessage(a), | ||
...err, | ||
}; | ||
} | ||
b = { | ||
status: a, | ||
...(typeof b === 'object' ? b : { error: b || getMessage(a) }), | ||
}; | ||
return json(b, { status: a }); | ||
}; | ||
export { error }; | ||
"use strict";const r=((r="text/plain; charset=utf-8",e)=>(t,s={})=>{const{headers:n={},...o}=s;return"Response"===t?.constructor.name?t:new Response(e?e(t):t,{headers:{"content-type":r,...n},...o})})("application/json; charset=utf-8",JSON.stringify),e=r=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[r]||"Unknown Error");exports.error=(t=500,s)=>{if(t instanceof Error){const{message:r,...n}=t;t=t.status||500,s={error:r||e(t),...n}}return s={status:t,..."object"==typeof s?s:{error:s||e(t)}},r(s,{status:t})}; |
17
html.js
@@ -1,16 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const html = createResponse('text/html'); | ||
export { html }; | ||
"use strict";const t=((t="text/plain; charset=utf-8",e)=>(s,n={})=>{const{headers:r={},...o}=n;return"Response"===s?.constructor.name?s:new Response(e?e(s):s,{headers:{"content-type":t,...r},...o})})("text/html");exports.html=t; |
190
index.js
@@ -1,189 +0,1 @@ | ||
const Router = ({ base = '', routes = [] } = {}) => | ||
// @ts-expect-error TypeScript doesn't know that Proxy makes this work | ||
({ | ||
__proto__: new Proxy({}, { | ||
// @ts-expect-error (we're adding an expected prop "path" to the get) | ||
get: (target, prop, receiver, path) => (route, ...handlers) => routes.push([ | ||
prop.toUpperCase(), | ||
RegExp(`^${(path = (base + '/' + route).replace(/\/+(\/|$)/g, '$1')) // strip double & trailing splash | ||
.replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))') // greedy params | ||
.replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))') // named params and image format | ||
.replace(/\./g, '\\.') // dot in path | ||
.replace(/(\/?)\*/g, '($1.*)?') // wildcard | ||
}/*$`), | ||
handlers, | ||
path, // embed clean route path | ||
]) && receiver | ||
}), | ||
routes, | ||
async handle(request, ...args) { | ||
let response, match, url = new URL(request.url), query = request.query = { __proto__: null }; | ||
for (let [k, v] of url.searchParams) { | ||
query[k] = query[k] === undefined ? v : [query[k], v].flat(); | ||
} | ||
for (let [method, regex, handlers, path] of routes) { | ||
if ((method === request.method || method === 'ALL') && (match = url.pathname.match(regex))) { | ||
request.params = match.groups || {}; // embed params in request | ||
request.route = path; // embed route path in request | ||
for (let handler of handlers) { | ||
if ((response = await handler(request.proxy || request, ...args)) !== undefined) | ||
return response; | ||
} | ||
} | ||
} | ||
} | ||
}); | ||
class StatusError extends Error { | ||
status; | ||
constructor(status = 500, body) { | ||
super(typeof body === 'object' ? body.error : body); | ||
typeof body === 'object' && Object.assign(this, body); | ||
this.status = status; | ||
} | ||
} | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const json = createResponse('application/json; charset=utf-8', JSON.stringify); | ||
const getMessage = (code) => { | ||
return ({ | ||
400: 'Bad Request', | ||
401: 'Unauthorized', | ||
403: 'Forbidden', | ||
404: 'Not Found', | ||
500: 'Internal Server Error', | ||
}[code] || 'Unknown Error'); | ||
}; | ||
const error = (a = 500, b) => { | ||
// handle passing an Error | StatusError directly in | ||
if (a instanceof Error) { | ||
const { message, ...err } = a; | ||
a = a.status || 500; | ||
b = { | ||
error: message || getMessage(a), | ||
...err, | ||
}; | ||
} | ||
b = { | ||
status: a, | ||
...(typeof b === 'object' ? b : { error: b || getMessage(a) }), | ||
}; | ||
return json(b, { status: a }); | ||
}; | ||
const status = (status) => new Response(null, { status }); | ||
const text = (message, options) => new Response(message, options); | ||
const html = createResponse('text/html'); | ||
const jpeg = createResponse('image/jpeg'); | ||
const png = createResponse('image/png'); | ||
const webp = createResponse('image/webp'); | ||
// withContent - embeds any request body as request.content | ||
const withContent = async (request) => { | ||
if (request.headers.get('content-type')?.includes('json')) | ||
request.content = await request.json(); | ||
}; | ||
// withCookies - embeds cookies object into the request | ||
const withCookies = (r) => { | ||
r.cookies = (r.headers.get('Cookie') || '') | ||
.split(/;\s*/) | ||
.map((p) => p.split(/=(.+)/)) | ||
.reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {}); | ||
}; | ||
const withParams = (request) => { | ||
request.proxy = new Proxy(request.proxy || request, { | ||
get: (obj, prop) => { | ||
let p; | ||
if ((p = obj[prop]) !== undefined) | ||
return p.bind?.(request) || p; | ||
return obj?.params?.[prop]; | ||
}, | ||
}); | ||
}; | ||
// Create CORS function with default options. | ||
const createCors = (options = {}) => { | ||
// Destructure and set defaults for options. | ||
const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options; | ||
let allowOrigin; | ||
// Initial response headers. | ||
const rHeaders = { | ||
'content-type': 'application/json', | ||
'Access-Control-Allow-Methods': methods.join(', '), | ||
...headers, | ||
}; | ||
// Set max age if provided. | ||
if (maxAge) | ||
rHeaders['Access-Control-Max-Age'] = maxAge; | ||
// Pre-flight function. | ||
const preflight = (r) => { | ||
// Use methods set. | ||
const useMethods = [...new Set(['OPTIONS', ...methods])]; | ||
const origin = r.headers.get('origin') || ''; | ||
// Set allowOrigin globally. | ||
allowOrigin = (origins.includes(origin) || origins.includes('*')) && { | ||
'Access-Control-Allow-Origin': origin, | ||
}; | ||
// Check if method is OPTIONS. | ||
if (r.method === 'OPTIONS') { | ||
const reqHeaders = { | ||
...rHeaders, | ||
'Access-Control-Allow-Methods': useMethods.join(', '), | ||
'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'), | ||
...allowOrigin, | ||
}; | ||
// Handle CORS pre-flight request. | ||
return new Response(null, { | ||
headers: r.headers.get('Origin') && | ||
r.headers.get('Access-Control-Request-Method') && | ||
r.headers.get('Access-Control-Request-Headers') | ||
? reqHeaders | ||
: { Allow: useMethods.join(', ') }, | ||
}); | ||
} | ||
}; | ||
// Corsify function. | ||
const corsify = (response) => { | ||
if (!response) | ||
throw new Error('No fetch handler responded and no upstream to proxy to specified.'); | ||
const { headers, status, body } = response; | ||
// Bypass for protocol shifts or redirects, or if CORS is already set. | ||
if ([101, 301, 302, 308].includes(status) || | ||
headers.get('access-control-allow-origin')) | ||
return response; | ||
// Return new response with CORS headers. | ||
return new Response(body, { | ||
status, | ||
headers: { | ||
...Object.fromEntries(headers), | ||
...rHeaders, | ||
...allowOrigin, | ||
'content-type': headers.get('content-type'), | ||
}, | ||
}); | ||
}; | ||
// Return corsify and preflight methods. | ||
return { corsify, preflight }; | ||
}; | ||
export { Router, StatusError, createCors, createResponse, error, html, jpeg, json, png, status, text, webp, withContent, withCookies, withParams }; | ||
"use strict";class e extends Error{status;constructor(e=500,t){super("object"==typeof t?t.error:t),"object"==typeof t&&Object.assign(this,t),this.status=e}}const t=(e="text/plain; charset=utf-8",t)=>(s,o={})=>{const{headers:r={},...n}=o;return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...n})},s=t("application/json; charset=utf-8",JSON.stringify),o=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),r=t("text/html"),n=t("image/jpeg"),a=t("image/png"),c=t("image/webp");exports.Router=({base:e="",routes:t=[]}={})=>({__proto__:new Proxy({},{get:(s,o,r,n)=>(s,...a)=>t.push([o.toUpperCase(),RegExp(`^${(n=(e+"/"+s).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&r}),routes:t,async handle(e,...s){let o,r,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=void 0===a[e]?t:[a[e],t].flat();for(let[a,c,p,i]of t)if((a===e.method||"ALL"===a)&&(r=n.pathname.match(c))){e.params=r.groups||{},e.route=i;for(let t of p)if(void 0!==(o=await t(e.proxy||e,...s)))return o}}}),exports.StatusError=e,exports.createCors=(e={})=>{const{origins:t=["*"],maxAge:s,methods:o=["GET"],headers:r={}}=e;let n;const a={"content-type":"application/json","Access-Control-Allow-Methods":o.join(", "),...r};s&&(a["Access-Control-Max-Age"]=s);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:t,status:s,body:o}=e;return[101,301,302,308].includes(s)||t.get("access-control-allow-origin")?e:new Response(o,{status:s,headers:{...Object.fromEntries(t),...a,...n,"content-type":t.get("content-type")}})},preflight:e=>{const s=[...new Set(["OPTIONS",...o])],r=e.headers.get("origin")||"";if(n=(t.includes(r)||t.includes("*"))&&{"Access-Control-Allow-Origin":r},"OPTIONS"===e.method){const t={...a,"Access-Control-Allow-Methods":s.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...n};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?t:{Allow:s.join(", ")}})}}}},exports.createResponse=t,exports.error=(e=500,t)=>{if(e instanceof Error){const{message:s,...r}=e;e=e.status||500,t={error:s||o(e),...r}}return t={status:e,..."object"==typeof t?t:{error:t||o(e)}},s(t,{status:e})},exports.html=r,exports.jpeg=n,exports.json=s,exports.png=a,exports.status=e=>new Response(null,{status:e}),exports.text=(e,t)=>new Response(e,t),exports.webp=c,exports.withContent=async e=>{e.headers.get("content-type")?.includes("json")&&(e.content=await e.json())},exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,s])=>s?(e[t]=s,e):e),{})},exports.withParams=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,s)=>{let o;return void 0!==(o=t[s])?o.bind?.(e)||o:t?.params?.[s]}})}; |
17
jpeg.js
@@ -1,16 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const jpeg = createResponse('image/jpeg'); | ||
export { jpeg }; | ||
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,n={})=>{const{headers:r={},...o}=n;return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})})("image/jpeg");exports.jpeg=e; |
17
json.js
@@ -1,16 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const json = createResponse('application/json; charset=utf-8', JSON.stringify); | ||
export { json }; | ||
"use strict";const t=((t="text/plain; charset=utf-8",e)=>(s,n={})=>{const{headers:o={},...r}=n;return"Response"===s?.constructor.name?s:new Response(e?e(s):s,{headers:{"content-type":t,...o},...r})})("application/json; charset=utf-8",JSON.stringify);exports.json=t; |
119
package.json
{ | ||
"name": "itty-router", | ||
"version": "4.0.11", | ||
"version": "4.0.12", | ||
"description": "A tiny, zero-dependency router, designed to make beautiful APIs in any environment.", | ||
"type": "module", | ||
"main": "./cjs/index.js", | ||
"module": "./index.js", | ||
"main": "./index.js", | ||
"module": "./index.mjs", | ||
"types": "./index.d.ts", | ||
"exports": { | ||
".": { | ||
"import": "./index.mjs", | ||
"require": "./index.js", | ||
"types": "./index.d.ts" | ||
}, | ||
"./createCors": { | ||
"import": "./createCors.mjs", | ||
"require": "./createCors.js", | ||
"types": "./createCors.d.ts" | ||
}, | ||
"./createResponse": { | ||
"import": "./createResponse.mjs", | ||
"require": "./createResponse.js", | ||
"types": "./createResponse.d.ts" | ||
}, | ||
"./error": { | ||
"import": "./error.mjs", | ||
"require": "./error.js", | ||
"types": "./error.d.ts" | ||
}, | ||
"./html": { | ||
"import": "./html.mjs", | ||
"require": "./html.js", | ||
"types": "./html.d.ts" | ||
}, | ||
"./jpeg": { | ||
"import": "./jpeg.mjs", | ||
"require": "./jpeg.js", | ||
"types": "./jpeg.d.ts" | ||
}, | ||
"./json": { | ||
"import": "./json.mjs", | ||
"require": "./json.js", | ||
"types": "./json.d.ts" | ||
}, | ||
"./png": { | ||
"import": "./png.mjs", | ||
"require": "./png.js", | ||
"types": "./png.d.ts" | ||
}, | ||
"./Router": { | ||
"import": "./Router.mjs", | ||
"require": "./Router.js", | ||
"types": "./Router.d.ts" | ||
}, | ||
"./status": { | ||
"import": "./status.mjs", | ||
"require": "./status.js", | ||
"types": "./status.d.ts" | ||
}, | ||
"./StatusError": { | ||
"import": "./StatusError.mjs", | ||
"require": "./StatusError.js", | ||
"types": "./StatusError.d.ts" | ||
}, | ||
"./text": { | ||
"import": "./text.mjs", | ||
"require": "./text.js", | ||
"types": "./text.d.ts" | ||
}, | ||
"./webp": { | ||
"import": "./webp.mjs", | ||
"require": "./webp.js", | ||
"types": "./webp.d.ts" | ||
}, | ||
"./websocket": { | ||
"import": "./websocket.mjs", | ||
"require": "./websocket.js", | ||
"types": "./websocket.d.ts" | ||
}, | ||
"./withContent": { | ||
"import": "./withContent.mjs", | ||
"require": "./withContent.js", | ||
"types": "./withContent.d.ts" | ||
}, | ||
"./withCookies": { | ||
"import": "./withCookies.mjs", | ||
"require": "./withCookies.js", | ||
"types": "./withCookies.d.ts" | ||
}, | ||
"./withParams": { | ||
"import": "./withParams.mjs", | ||
"require": "./withParams.js", | ||
"types": "./withParams.d.ts" | ||
} | ||
}, | ||
"keywords": [ | ||
@@ -33,2 +119,3 @@ "api", | ||
"prerelease": "yarn verify", | ||
"prerelease:next": "yarn verify", | ||
"prebuild": "rimraf dist && mkdir dist", | ||
@@ -57,18 +144,18 @@ "build": "rollup -c", | ||
"@skypack/package-check": "^0.2.2", | ||
"@types/node": "^20.2.5", | ||
"@typescript-eslint/eslint-plugin": "^5.59.8", | ||
"@typescript-eslint/parser": "^5.59.8", | ||
"@types/node": "^20.3.1", | ||
"@typescript-eslint/eslint-plugin": "^5.60.0", | ||
"@typescript-eslint/parser": "^5.60.0", | ||
"@vitejs/plugin-vue": "^4.2.3", | ||
"@vitest/coverage-c8": "^0.31.3", | ||
"@whatwg-node/server": "^0.8.1", | ||
"@vitest/coverage-c8": "^0.32.2", | ||
"@whatwg-node/server": "^0.8.12", | ||
"coveralls": "^3.1.1", | ||
"eslint": "^8.41.0", | ||
"eslint": "^8.43.0", | ||
"eslint-config-prettier": "^8.8.0", | ||
"fetch-mock": "^9.11.0", | ||
"fs-extra": "^11.1.1", | ||
"globby": "^13.1.4", | ||
"globby": "^13.2.0", | ||
"gzip-size": "^7.0.0", | ||
"http": "^0.0.1-security", | ||
"isomorphic-fetch": "^3.0.0", | ||
"itty-router": "^4.0.10-next.4", | ||
"itty-router": "^4.0.11", | ||
"jsdom": "^22.1.0", | ||
@@ -78,3 +165,3 @@ "npm-run-all": "^4.1.5", | ||
"rimraf": "^5.0.1", | ||
"rollup": "^3.23.0", | ||
"rollup": "^3.25.1", | ||
"rollup-plugin-bundle-size": "^1.0.3", | ||
@@ -84,8 +171,8 @@ "rollup-plugin-copy": "^3.4.0", | ||
"ts-node": "^10.9.1", | ||
"typescript": "^5.0.4", | ||
"typescript": "^5.1.3", | ||
"vite": "^4.3.9", | ||
"vitest": "^0.31.3", | ||
"vitest": "^0.32.2", | ||
"yarn": "^1.22.19", | ||
"yarn-release": "^1.10.5" | ||
"yarn-release": "^1.10.6" | ||
} | ||
} |
17
png.js
@@ -1,16 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const png = createResponse('image/png'); | ||
export { png }; | ||
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(n,s={})=>{const{headers:r={},...o}=s;return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...r},...o})})("image/png");exports.png=e; |
@@ -1,37 +0,1 @@ | ||
const Router = ({ base = '', routes = [] } = {}) => | ||
// @ts-expect-error TypeScript doesn't know that Proxy makes this work | ||
({ | ||
__proto__: new Proxy({}, { | ||
// @ts-expect-error (we're adding an expected prop "path" to the get) | ||
get: (target, prop, receiver, path) => (route, ...handlers) => routes.push([ | ||
prop.toUpperCase(), | ||
RegExp(`^${(path = (base + '/' + route).replace(/\/+(\/|$)/g, '$1')) // strip double & trailing splash | ||
.replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))') // greedy params | ||
.replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))') // named params and image format | ||
.replace(/\./g, '\\.') // dot in path | ||
.replace(/(\/?)\*/g, '($1.*)?') // wildcard | ||
}/*$`), | ||
handlers, | ||
path, // embed clean route path | ||
]) && receiver | ||
}), | ||
routes, | ||
async handle(request, ...args) { | ||
let response, match, url = new URL(request.url), query = request.query = { __proto__: null }; | ||
for (let [k, v] of url.searchParams) { | ||
query[k] = query[k] === undefined ? v : [query[k], v].flat(); | ||
} | ||
for (let [method, regex, handlers, path] of routes) { | ||
if ((method === request.method || method === 'ALL') && (match = url.pathname.match(regex))) { | ||
request.params = match.groups || {}; // embed params in request | ||
request.route = path; // embed route path in request | ||
for (let handler of handlers) { | ||
if ((response = await handler(request.proxy || request, ...args)) !== undefined) | ||
return response; | ||
} | ||
} | ||
} | ||
} | ||
}); | ||
export { Router }; | ||
"use strict";exports.Router=({base:e="",routes:r=[]}={})=>({__proto__:new Proxy({},{get:(o,t,a,p)=>(o,...l)=>r.push([t.toUpperCase(),RegExp(`^${(p=(e+"/"+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,p])&&a}),routes:r,async handle(e,...o){let t,a,p=new URL(e.url),l=e.query={__proto__:null};for(let[e,r]of p.searchParams)l[e]=void 0===l[e]?r:[l[e],r].flat();for(let[l,s,u,$]of r)if((l===e.method||"ALL"===l)&&(a=p.pathname.match(s))){e.params=a.groups||{},e.route=$;for(let r of u)if(void 0!==(t=await r(e.proxy||e,...o)))return t}}}); |
@@ -1,3 +0,1 @@ | ||
const status = (status) => new Response(null, { status }); | ||
export { status }; | ||
"use strict";exports.status=s=>new Response(null,{status:s}); |
@@ -1,10 +0,1 @@ | ||
class StatusError extends Error { | ||
status; | ||
constructor(status = 500, body) { | ||
super(typeof body === 'object' ? body.error : body); | ||
typeof body === 'object' && Object.assign(this, body); | ||
this.status = status; | ||
} | ||
} | ||
export { StatusError }; | ||
"use strict";class t extends Error{status;constructor(t=500,s){super("object"==typeof s?s.error:s),"object"==typeof s&&Object.assign(this,s),this.status=t}}exports.StatusError=t; |
@@ -1,3 +0,1 @@ | ||
const text = (message, options) => new Response(message, options); | ||
export { text }; | ||
"use strict";exports.text=(e,s)=>new Response(e,s); |
17
webp.js
@@ -1,16 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const webp = createResponse('image/webp'); | ||
export { webp }; | ||
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,n={})=>{const{headers:r={},...o}=n;return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})})("image/webp");exports.webp=e; |
@@ -1,20 +0,1 @@ | ||
const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => { | ||
const { headers = {}, ...rest } = options; | ||
if (body?.constructor.name === 'Response') | ||
return body; | ||
return new Response(transform ? transform(body) : body, { | ||
headers: { | ||
'content-type': format, | ||
...headers, | ||
}, | ||
...rest, | ||
}); | ||
}; | ||
const websocket = (client, options = {}) => createResponse()(null, { | ||
status: 101, | ||
webSocket: client, | ||
...options, | ||
}); | ||
export { websocket }; | ||
"use strict";exports.websocket=(e,t={})=>((e="text/plain; charset=utf-8",t)=>(s,n={})=>{const{headers:o={},...r}=n;return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...o},...r})})()(null,{status:101,webSocket:e,...t}); |
@@ -1,7 +0,1 @@ | ||
// withContent - embeds any request body as request.content | ||
const withContent = async (request) => { | ||
if (request.headers.get('content-type')?.includes('json')) | ||
request.content = await request.json(); | ||
}; | ||
export { withContent }; | ||
"use strict";exports.withContent=async t=>{t.headers.get("content-type")?.includes("json")&&(t.content=await t.json())}; |
@@ -1,9 +0,1 @@ | ||
// withCookies - embeds cookies object into the request | ||
const withCookies = (r) => { | ||
r.cookies = (r.headers.get('Cookie') || '') | ||
.split(/;\s*/) | ||
.map((p) => p.split(/=(.+)/)) | ||
.reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {}); | ||
}; | ||
export { withCookies }; | ||
"use strict";exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[s,i])=>i?(e[s]=i,e):e),{})}; |
@@ -1,12 +0,1 @@ | ||
const withParams = (request) => { | ||
request.proxy = new Proxy(request.proxy || request, { | ||
get: (obj, prop) => { | ||
let p; | ||
if ((p = obj[prop]) !== undefined) | ||
return p.bind?.(request) || p; | ||
return obj?.params?.[prop]; | ||
}, | ||
}); | ||
}; | ||
export { withParams }; | ||
"use strict";exports.withParams=r=>{r.proxy=new Proxy(r.proxy||r,{get:(t,e)=>{let o;return void 0!==(o=t[e])?o.bind?.(r)||o:t?.params?.[e]}})}; |
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
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
33466
54
191
No