Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: Update path-to-regex to v8.1.0 #189

Merged
merged 5 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions lib/layer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { parse: parseUrl, format: formatUrl } = require('node:url');

const { pathToRegexp, compile, parse } = require('path-to-regexp');
const { pathToRegexp, compile, parse, stringify } = require('path-to-regexp');

Check warning on line 3 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

'stringify' is assigned a value but never used.

Check warning on line 3 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

'stringify' is assigned a value but never used.

Check warning on line 3 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

'stringify' is assigned a value but never used.

module.exports = class Layer {
/**
Expand Down Expand Up @@ -41,7 +41,14 @@
}

this.path = path;
this.regexp = pathToRegexp(path, this.paramNames, this.opts);

if (this.opts.pathIsRegexp === true) {
this.regexp = new RegExp(path);
} else if (this.path) {
const { regexp: regex, keys } = pathToRegexp(this.path, this.opts);
this.regexp = regex;
this.paramNames = keys;
}
}

/**
Expand Down Expand Up @@ -107,7 +114,7 @@
const url = this.path.replace(/\(\.\*\)/g, '');

if (typeof params !== 'object') {
args = Array.prototype.slice.call(arguments);

Check warning on line 117 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 117 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 117 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Use the rest parameters instead of 'arguments'.
if (typeof args[args.length - 1] === 'object') {
options = args[args.length - 1];
args = args.slice(0, -1);
Expand All @@ -116,20 +123,25 @@

const toPath = compile(url, { encode: encodeURIComponent, ...options });
let replaced;

const tokens = parse(url);
const { tokens } = parse(url);
let replace = {};

if (Array.isArray(args)) {
for (let len = tokens.length, i = 0, j = 0; i < len; i++) {
if (tokens[i].name) replace[tokens[i].name] = args[j++];
if (tokens[i].name) {
replace[tokens[i].name] = args[j++];
}
}
} else if (tokens.some((token) => token.name)) {
replace = params;
} else if (!options) {
options = params;
}

for (const [key, value] of Object.entries(replace)) {
replace[key] = String(value);
}

replaced = toPath(replace);

if (options && options.query) {
Expand Down Expand Up @@ -185,7 +197,7 @@
const x = names.indexOf(param);
if (x > -1) {
// iterate through the stack, to figure out where to place the handler fn
stack.some((fn, i) => {

Check warning on line 200 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Array.prototype.some() expects a value to be returned at the end of arrow function.

Check warning on line 200 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Array.prototype.some() expects a value to be returned at the end of arrow function.

Check warning on line 200 in lib/layer.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Array.prototype.some() expects a value to be returned at the end of arrow function.
// param handlers are always first, so when we find an fn w/o a param property, stop here
// if the param handler at this part of the stack comes after the one we are adding, stop here
if (!fn.param || names.indexOf(fn.param) > x) {
Expand All @@ -212,8 +224,13 @@
this.path !== '/' || this.opts.strict === true
? `${prefix}${this.path}`
: prefix;
this.paramNames = [];
this.regexp = pathToRegexp(this.path, this.paramNames, this.opts);
if (this.opts.pathIsRegexp === true || prefix instanceof RegExp) {
this.regexp = new RegExp(this.path);
} else if (this.path) {
const { regexp: regex, keys } = pathToRegexp(this.path, this.opts);
this.regexp = regex;
this.paramNames = keys;
}
}

return this;
Expand Down
37 changes: 25 additions & 12 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') {
const arrPaths = middleware[0];
for (const p of arrPaths) {
router.use.apply(router, [p, ...middleware.slice(1)]);

Check warning on line 129 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Unnecessary '.apply()'.

Check warning on line 129 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Unnecessary '.apply()'.

Check warning on line 129 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Unnecessary '.apply()'.
}

return this;
Expand Down Expand Up @@ -165,14 +165,14 @@
}
}
} else {
const keys = [];
pathToRegexp(router.opts.prefix || '', keys);
const { keys } = pathToRegexp(router.opts.prefix || '', router.opts);
const routerPrefixHasParam = Boolean(
router.opts.prefix && keys.length > 0
);
router.register(path || '([^/]*)', [], m, {
end: false,
ignoreCaptures: !hasPath && !routerPrefixHasParam
ignoreCaptures: !hasPath && !routerPrefixHasParam,
pathIsRegexp: true
});
}
}
Expand Down Expand Up @@ -228,7 +228,7 @@
ctx.routerPath;
const matched = router.match(path, ctx.method);
if (ctx.matched) {
ctx.matched.push.apply(ctx.matched, matched.path);

Check warning on line 231 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Use the spread operator instead of '.apply()'.

Check warning on line 231 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Use the spread operator instead of '.apply()'.

Check warning on line 231 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Use the spread operator instead of '.apply()'.
} else {
ctx.matched = matched.path;
}
Expand All @@ -246,7 +246,7 @@

const layerChain = (
router.exclusive ? [mostSpecificLayer] : matchedLayers
).reduce((memo, layer) => {

Check warning on line 249 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

`Array#reduce()` is not allowed

Check warning on line 249 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

`Array#reduce()` is not allowed

Check warning on line 249 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

`Array#reduce()` is not allowed
memo.push((ctx, next) => {
ctx.captures = layer.captures(path, ctx.captures);
ctx.request.params = layer.params(path, ctx.captures, ctx.params);
Expand Down Expand Up @@ -380,10 +380,10 @@
* @returns {Router}
*/
all(name, path, middleware) {
if (typeof path === 'string') {
if (typeof path === 'string' || path instanceof RegExp) {
middleware = Array.prototype.slice.call(arguments, 2);

Check warning on line 384 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 384 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 384 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Use the rest parameters instead of 'arguments'.
} else {
middleware = Array.prototype.slice.call(arguments, 1);

Check warning on line 386 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 386 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Use the rest parameters instead of 'arguments'.

Check warning on line 386 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Use the rest parameters instead of 'arguments'.
path = name;
name = null;
}
Expand All @@ -396,7 +396,12 @@
)
throw new Error('You have to provide a path when adding an all handler');

this.register(path, methods, middleware, { name });
const opts = {
name,
pathIsRegexp: path instanceof RegExp
};

this.register(path, methods, middleware, { ...this.opts, ...opts });

return this;
}
Expand Down Expand Up @@ -455,14 +460,14 @@
* @returns {Layer}
* @private
*/
register(path, methods, middleware, opts = {}) {
register(path, methods, middleware, newOpts = {}) {
const router = this;
const { stack } = this;

const opts = { ...this.opts, ...newOpts };
// support array of paths
if (Array.isArray(path)) {
for (const curPath of path) {
router.register.call(router, curPath, methods, middleware, opts);

Check warning on line 470 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Unnecessary '.call()'.

Check warning on line 470 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Unnecessary '.call()'.

Check warning on line 470 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Unnecessary '.call()'.
}

return this;
Expand All @@ -472,12 +477,15 @@
const route = new Layer(path, methods, middleware, {
end: opts.end === false ? opts.end : true,
name: opts.name,
sensitive: opts.sensitive || this.opts.sensitive || false,
strict: opts.strict || this.opts.strict || false,
prefix: opts.prefix || this.opts.prefix || '',
ignoreCaptures: opts.ignoreCaptures
sensitive: opts.sensitive || false,
strict: opts.strict || false,
prefix: opts.prefix || '',
ignoreCaptures: opts.ignoreCaptures,
pathIsRegexp: opts.pathIsRegexp,
trailing: opts.trailing
});

// if parent prefix exists, add prefix to new route
if (this.opts.prefix) {
route.setPrefix(this.opts.prefix);
}
Expand Down Expand Up @@ -547,7 +555,7 @@
*/
url(name, ...args) {
const route = this.route(name);
if (route) return route.url.apply(route, args);

Check warning on line 558 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 18 on ubuntu-latest

Use the spread operator instead of '.apply()'.

Check warning on line 558 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 20 on ubuntu-latest

Use the spread operator instead of '.apply()'.

Check warning on line 558 in lib/router.js

View workflow job for this annotation

GitHub Actions / Node 22 on ubuntu-latest

Use the spread operator instead of '.apply()'.

return new Error(`No route found for name: ${String(name)}`);
}
Expand Down Expand Up @@ -812,8 +820,13 @@
`You have to provide a path when adding a ${method} handler`
);

this.register(path, [method], middleware, { name });
const opts = {
name,
pathIsRegexp: path instanceof RegExp
};

// pass opts to register call on verb methods
this.register(path, [method], middleware, { ...this.opts, ...opts });
return this;
};
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"dependencies": {
"http-errors": "^2.0.0",
"koa-compose": "^4.1.0",
"path-to-regexp": "^6.3.0"
"path-to-regexp": "^8.1.0"
},
"devDependencies": {
"@commitlint/cli": "^17.7.2",
Expand Down
32 changes: 18 additions & 14 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,13 @@ describe('Router', () => {
const router = new Router();

router
.get('user_page', '/user/(.*).jsx', (ctx) => {
.get('user_page', '/user/{*any}.jsx', (ctx) => {
ctx.body = { order: 1 };
})
.all('app', '/app/(.*).jsx', (ctx) => {
.all('app', '/app/{*any}.jsx', (ctx) => {
ctx.body = { order: 2 };
})
.all('view', '(.*).jsx', (ctx) => {
.all('view', '{*any}.jsx', (ctx) => {
ctx.body = { order: 3 };
});

Expand All @@ -244,7 +244,7 @@ describe('Router', () => {
const router = new Router();

router
.get('users_single', '/users/:id(.*)', (ctx, next) => {
.get('users_single', '/users/:id{/*path}', (ctx, next) => {
ctx.body = { single: true };
next();
})
Expand All @@ -268,10 +268,14 @@ describe('Router', () => {
const router = new Router({ exclusive: true });

router
.get('users_single', '/users/:id(.*)', (ctx, next) => {
ctx.body = { single: true };
next();
})
.get(
'users_single',
new RegExp('/users/:id(.*)'), // eslint-disable-line prefer-regex-literals
(ctx, next) => {
ctx.body = { single: true };
next();
}
)
.get('users_all', '/users/all', (ctx, next) => {
ctx.body = { ...ctx.body, all: true };
next();
Expand All @@ -293,7 +297,7 @@ describe('Router', () => {

router.get(
'user_page',
'/user/(.*).jsx',
'/user/{*any}.jsx',
() => {
// no next()
},
Expand Down Expand Up @@ -458,7 +462,7 @@ it('matches corresponding requests with optional route parameter', async () => {
});
const id = '10';
const ext = '.json';
router.get('/resources/:id{.:ext}?', (ctx) => {
router.get('/resources/:id{.:ext}', (ctx) => {
assert.strictEqual('params' in ctx, true);
assert.strictEqual(ctx.params.id, id);
if (ctx.params.ext) assert.strictEqual(ctx.params.ext, ext.slice(1));
Expand Down Expand Up @@ -1653,7 +1657,7 @@ describe('Router#opts', () => {
it('responds with 200', async () => {
const app = new Koa();
const router = new Router({
strict: true
trailing: false
});
router.get('/info', (ctx) => {
ctx.body = 'hello';
Expand Down Expand Up @@ -1685,7 +1689,7 @@ describe('Router#opts', () => {
it('responds with 404 when has a trailing slash', async () => {
const app = new Koa();
const router = new Router({
strict: true
trailing: false
});
router.get('/info', (ctx) => {
ctx.body = 'hello';
Expand All @@ -1700,7 +1704,7 @@ describe('use middleware with opts', () => {
it('responds with 200', async () => {
const app = new Koa();
const router = new Router({
strict: true
trailing: false
});
router.get('/info', (ctx) => {
ctx.body = 'hello';
Expand All @@ -1716,7 +1720,7 @@ describe('use middleware with opts', () => {
it('responds with 404 when has a trailing slash', async () => {
const app = new Koa();
const router = new Router({
strict: true
trailing: false
});
router.get('/info', (ctx) => {
ctx.body = 'hello';
Expand Down
Loading