{"name":"find-my-way","version":"2.2.4","description":"Crazy fast http radix based router","main":"index.js","typings":"index.d.ts","scripts":{"bench":"node bench.js","test:lint":"standard","test:typescript":"tsc --project ./test/types/tsconfig.json","test":"standard && tap -J test/*.test.js && npm run test:typescript","test:report":"tap -J test/*.test.js --cov --coverage-report=html --coverage-report=cobertura | tee out.tap","test:reporter":"tap-mocha-reporter xunit < out.tap > test/junit-testresults.xml"},"repository":{"type":"git","url":"git+https://github.com/delvedor/find-my-way.git"},"keywords":["http","router","radix","fast","speed"],"engines":{"node":">=6"},"author":{"name":"Tomas Della Vedova - @delvedor","url":"http://delved.org"},"license":"MIT","bugs":{"url":"https://github.com/delvedor/find-my-way/issues"},"homepage":"https://github.com/delvedor/find-my-way#readme","devDependencies":{"@types/node":"^11.9.4","benchmark":"^2.1.4","pre-commit":"^1.2.2","request":"^2.88.0","standard":"^12.0.1","tap":"^12.5.3","tap-mocha-reporter":"^3.0.9","typescript":"^3.3.3"},"dependencies":{"fast-decode-uri-component":"^1.0.0","safe-regex2":"^2.0.0","semver-store":"^0.3.0"},"readme":"# find-my-way\n\n[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)  [![Build Status](https://dev.azure.com/delvedor/find-my-way/_apis/build/status/delvedor.find-my-way?branchName=master)](https://dev.azure.com/delvedor/find-my-way/_build/latest?definitionId=1&branchName=master) [![Coverage Status](https://img.shields.io/azure-devops/coverage/delvedor/find-my-way/1.svg)](https://dev.azure.com/delvedor/find-my-way) [![NPM downloads](https://img.shields.io/npm/dm/find-my-way.svg?style=flat)](https://www.npmjs.com/package/find-my-way)\n\nA crazy fast HTTP router, internally uses an highly performant [Radix Tree](https://en.wikipedia.org/wiki/Radix_tree) (aka compact [Prefix Tree](https://en.wikipedia.org/wiki/Trie)), supports route params, wildcards, and it's framework independent.\n\nIf you want to see a benchmark comparison with the most commonly used routers, see [here](https://github.com/delvedor/router-benchmark).<br>\nDo you need a real-world example that uses this router? Check out [Fastify](https://github.com/fastify/fastify) or [Restify](https://github.com/restify/node-restify).\n\n<a name=\"install\"></a>\n## Install\n```\nnpm i find-my-way --save\n```\n\n<a name=\"usage\"></a>\n## Usage\n```js\nconst http = require('http')\nconst router = require('find-my-way')()\n\nrouter.on('GET', '/', (req, res, params) => {\n  res.end('{\"message\":\"hello world\"}')\n})\n\nconst server = http.createServer((req, res) => {\n  router.lookup(req, res)\n})\n\nserver.listen(3000, err => {\n  if (err) throw err\n  console.log('Server listening on: http://localhost:3000')\n})\n```\n\n<a name=\"api\"></a>\n## API\n<a name=\"constructor\"></a>\n#### FindMyway([options])\nInstance a new router.<br>\nYou can pass a default route with the option `defaultRoute`.\n```js\nconst router = require('find-my-way')({\n  defaultRoute: (req, res) => {\n    res.statusCode = 404\n    res.end()\n  }\n})\n```\n\nIn case of a badly formatted url *(eg: `/hello/%world`)*, by default `find-my-way` will invoke the `defaultRoute`, unless you specify the `onBadUrl` option:\n```js\nconst router = require('find-my-way')({\n  onBadUrl: (path, req, res) => {\n    res.statusCode = 400\n    res.end(`Bad path: ${path}`)\n  }\n})\n```\n\nTrailing slashes can be ignored by supplying the `ignoreTrailingSlash` option:\n```js\nconst router = require('find-my-way')({\n  ignoreTrailingSlash: true\n})\nfunction handler (req, res, params) {\n  res.end('foo')\n}\n// maps \"/foo/\" and \"/foo\" to `handler`\nrouter.on('GET', '/foo/', handler)\n```\n\nYou can set a custom length for parameters in parametric *(standard, regex and multi)* routes by using `maxParamLength` option, the default value is 100 characters.<br/>\n*If the maximum length limit is reached, the default route will be invoked.*\n```js\nconst router = require('find-my-way')({\n  maxParamLength: 500\n})\n```\n\nIf you are using a regex based route, `find-my-way` will throw an error if detects potentially catastrophic exponential-time regular expressions *(internally uses [`safe-regex2`](https://github.com/fastify/safe-regex2))*.<br/>\nIf you want to disable this behavior, pass the option `allowUnsafeRegex`.\n```js\nconst router = require('find-my-way')({\n  allowUnsafeRegex: true\n})\n```\n\nAccording to [RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1), find-my-way is case sensitive by default.\nYou can disable this by setting the `caseSensitive` option to `false`:\nin that case, all paths will be matched as lowercase, but the route parameters or wildcards will maintain their original letter casing. You can turn off case sensitivity with:\n\n```js\nconst router = require('find-my-way')({\n  caseSensitive: false\n})\n```\n\n<a name=\"custom-versioning\"></a>\nBy default `find-my-way` uses [accept-version](./lib/accept-version.js) strategy to match requests with different versions of the handlers. The matching logic of that strategy is explained [below](#semver). It is possible to define the alternative strategy:\n```js\nconst customVersioning = {\n  // storage factory\n  storage: function () {\n    let versions = {}\n    return {\n      get: (version) => { return versions[version] || null },\n      set: (version, store) => { versions[version] = store },\n      del: (version) => { delete versions[version] },\n      empty: () => { versions = {} }\n    }\n  },\n  deriveVersion: (req, ctx) => {\n    return req.headers['accept']\n  }\n}\n\nconst router = FindMyWay({ versioning: customVersioning });\n```\n\nThe custom strategy object should contain next properties:\n* `storage` - the factory function for the Storage of the handlers based on their version.\n* `deriveVersion` - the function to determine the version based on the request\n\nThe signature of the functions and objects must match the one from the example above.\n\n\n*Please, be aware, if you use custom versioning strategy - you use it on your own risk. This can lead both to the performance degradation and bugs which are not related to `find-my-way` itself*\n\n<a name=\"on\"></a>\n#### on(method, path, [opts], handler, [store])\nRegister a new route.\n```js\nrouter.on('GET', '/example', (req, res, params) => {\n  // your code\n})\n```\nLast argument, `store` is used to pass an object that you can access later inside the handler function. If needed, `store` can be updated.\n```js\nrouter.on('GET', '/example', (req, res, params, store) => {\n  assert.equal(store, { message: 'hello world' })\n}, { message: 'hello world' })\n```\n\n##### Versioned routes\n\nIf needed you can provide a `version` option, which will allow you to declare multiple versions of the same route.\n\n###### default\n<a name=\"semver\"></a>\nDefault versioning strategy is called `accept-version` and it follows the [semver](https://semver.org/) specification.<br/>\nWhen using `lookup`, `find-my-way` will automatically detect the `Accept-Version` header and route the request accordingly.<br/>\nInternally `find-my-way` uses the [`semver-store`](https://github.com/delvedor/semver-store) to get the correct version of the route; *advanced ranges* and *pre-releases* currently are not supported.<br/>\n*Be aware that using this feature will cause a degradation of the overall performances of the router.*\n```js\nrouter.on('GET', '/example', { version: '1.2.0' }, (req, res, params) => {\n  res.end('Hello from 1.2.0!')\n})\n\nrouter.on('GET', '/example', { version: '2.4.0' }, (req, res, params) => {\n  res.end('Hello from 2.4.0!')\n})\n\n// The 'Accept-Version' header could be '1.2.0' as well as '*', '2.x' or '2.4.x'\n```\nIf you declare multiple versions with the same *major* or *minor* `find-my-way` will always choose the highest compatible with the `Accept-Version` header value.\n\n###### custom\nIt's also possible to define a [custom versioning strategy](#custom-versioning) during the `find-my-way` initialization. In this case the logic of matching the request to the specific handler depends on the versioning strategy you use.\n\n##### on(methods[], path, [opts], handler, [store])\nRegister a new route for each method specified in the `methods` array.\nIt comes handy when you need to declare multiple routes with the same handler but different methods.\n```js\nrouter.on(['GET', 'POST'], '/example', (req, res, params) => {\n  // your code\n})\n```\n\n<a name=\"supported-path-formats\"></a>\n##### Supported path formats\nTo register a **parametric** path, use the *colon* before the parameter name. For **wildcard** use the *star*.\n*Remember that static routes are always inserted before parametric and wildcard.*\n\n```js\n// parametric\nrouter.on('GET', '/example/:userId', (req, res, params) => {}))\nrouter.on('GET', '/example/:userId/:secretToken', (req, res, params) => {}))\n\n// wildcard\nrouter.on('GET', '/example/*', (req, res, params) => {}))\n```\n\nRegular expression routes are supported as well, but pay attention, RegExp are very expensive in term of performance!<br>\nIf you want to declare a regular expression route, you must put the regular expression inside round parenthesis after the parameter name.\n```js\n// parametric with regexp\nrouter.on('GET', '/example/:file(^\\\\d+).png', () => {}))\n```\n\nIt's possible to define more than one parameter within the same couple of slash (\"/\"). Such as:\n```js\nrouter.on('GET', '/example/near/:lat-:lng/radius/:r', (req, res, params) => {}))\n```\n*Remember in this case to use the dash (\"-\") as parameters separator.*\n\nFinally it's possible to have multiple parameters with RegExp.\n```js\nrouter.on('GET', '/example/at/:hour(^\\\\d{2})h:minute(^\\\\d{2})m', (req, res, params) => {}))\n```\nIn this case as parameter separator it's possible to use whatever character is not matched by the regular expression.\n\nHaving a route with multiple parameters may affect negatively the performance, so prefer single parameter approach whenever possible, especially on routes which are on the hot path of your application.\n\n<a name=\"match-order\"></a>\n##### Match order\n\nThe routing algorithm matches one chunk at a time (where the chunk is a string between two slashes),\nthis means that it cannot know if a route is static or dynamic until it finishes to match the URL.\n\nThe chunks are matched in the following order:\n\n1. static\n1. parametric\n1. wildcards\n1. parametric(regex)\n1. multi parametric(regex)\n\nSo if you declare the following routes\n\n- `/:userId/foo/bar`\n- `/33/:a(^.*$)/:b`\n\nand the URL of the incoming request is /33/foo/bar,\nthe second route will be matched because the first chunk (33) matches the static chunk.\nIf the URL would have been /32/foo/bar, the first route would have been matched.\n\n<a name=\"supported-methods\"></a>\n##### Supported methods\nThe router is able to route all HTTP methods defined by [`http` core module](https://nodejs.org/api/http.html#http_http_methods).\n\n<a name=\"off\"></a>\n#### off(method, path)\nDeregister a route.\n```js\nrouter.off('GET', '/example')\n// => { handler: Function, params: Object, store: Object}\n// => null\n```\n\n##### off(methods[], path, handler, [store])\nDeregister a route for each method specified in the `methods` array.\nIt comes handy when you need to deregister multiple routes with the same path but different methods.\n```js\nrouter.off(['GET', 'POST'], '/example')\n// => [{ handler: Function, params: Object, store: Object}]\n// => null\n```\n\n<a name=\"reset\"></a>\n#### reset()\nEmpty router.\n```js\nrouter.reset()\n```\n\n##### Caveats\n* It's not possible to register two routes which differs only for their parameters, because internally they would be seen as the same route. In a such case you'll get an early error during the route registration phase. An example is worth thousand words:\n```js\nconst findMyWay = FindMyWay({\n  defaultRoute: (req, res) => {}\n})\n\nfindMyWay.on('GET', '/user/:userId(^\\\\d+)', (req, res, params) => {})\n\nfindMyWay.on('GET', '/user/:username(^[a-z]+)', (req, res, params) => {})\n// Method 'GET' already declared for route ':'\n```\n\n<a name=\"shorthand-methods\"></a>\n##### Shorthand methods\nIf you want an even nicer api, you can also use the shorthand methods to declare your routes.\n\nFor each HTTP supported method, there's the shorthand method. For example:\n```js\nrouter.get(path, handler [, store])\nrouter.delete(path, handler [, store])\nrouter.head(path, handler [, store])\nrouter.patch(path, handler [, store])\nrouter.post(path, handler [, store])\nrouter.put(path, handler [, store])\nrouter.options(path, handler [, store])\n// ...\n```\n\nIf you need a route that supports *all* methods you can use the `all` api.\n```js\nrouter.all(path, handler [, store])\n```\n\n<a name=\"lookup\"></a>\n#### lookup(request, response, [context])\nStart a new search, `request` and `response` are the server req/res objects.<br>\nIf a route is found it will automatically call the handler, otherwise the default route will be called.<br>\nThe url is sanitized internally, all the parameters and wildcards are decoded automatically.\n```js\nrouter.lookup(req, res)\n```\n\n`lookup` accepts an optional context which will be the value of `this` when executing a handler\n```js\nrouter.on('GET', '*', function(req, res) {\n  res.end(this.greeting);\n})\nrouter.lookup(req, res, { greeting: 'Hello, World!' })\n```\n\n<a name=\"find\"></a>\n#### find(method, path [, version])\nReturn (if present) the route registered in *method:path*.<br>\nThe path must be sanitized, all the parameters and wildcards are decoded automatically.<br/>\nYou can also pass an optional version string. In case of the default versioning strategy it should be conform to the [semver](https://semver.org/) specification.\n```js\nrouter.find('GET', '/example')\n// => { handler: Function, params: Object, store: Object}\n// => null\n\nrouter.find('GET', '/example', '1.x')\n// => { handler: Function, params: Object, store: Object}\n// => null\n```\n\n<a name=\"pretty-print\"></a>\n#### prettyPrint()\nPrints the representation of the internal radix tree, useful for debugging.\n```js\nfindMyWay.on('GET', '/test', () => {})\nfindMyWay.on('GET', '/test/hello', () => {})\nfindMyWay.on('GET', '/hello/world', () => {})\n\nconsole.log(findMyWay.prettyPrint())\n// └── /\n//   ├── test (GET)\n//   │   └── /hello (GET)\n//   └── hello/world (GET)\n```\n\n<a name=\"routes\"></a>\n#### routes\nReturn the all routes **registered** at moment, useful for debugging.\n\n```js\nconst findMyWay = require('find-my-way')()\n\nfindMyWay.on('GET', '/test', () => {})\nfindMyWay.on('GET', '/test/hello', () => {})\n\nconsole.log(findMyWay.routes)\n// Will print\n// [\n//   {\n//     method: 'GET',\n//     path: '/test',\n//     opts: {},\n//     handler: [Function],\n//     store: undefined\n//   },\n//   {\n//     method: 'GET',\n//     path: '/test/hello',\n//     opts: {},\n//     handler: [Function],\n//     store: undefined\n//   }\n// ]\n```\n\n<a name=\"acknowledgements\"></a>\n## Acknowledgements\n\nIt is inspired by the [echo](https://github.com/labstack/echo) router, some parts have been extracted from [trekjs](https://github.com/trekjs) router.\n\n<a name=\"sponsor\"></a>\n#### Past sponsor\n\n- [LetzDoIt](http://www.letzdoitapp.com/)\n\n<a name=\"license\"></a>\n## License\n**[find-my-way - MIT](https://github.com/delvedor/find-my-way/blob/master/LICENSE)**<br>\n**[trekjs/router - MIT](https://github.com/trekjs/router/blob/master/LICENSE)**\n\nCopyright © 2017-2019 Tomas Della Vedova\n","readmeFilename":"README.md","gitHead":"1bcedc7d19e7ab321cb4ab9ab11d4f4089f179e3","_id":"find-my-way@2.2.4","_nodeVersion":"12.18.1","_npmVersion":"6.14.8","_npmUser":{"name":"matteo.collina","email":"hello@matteocollina.com"},"dist":{"integrity":"sha512-GYP5M6SS6Tblv4fNgADLmrWIgaWK62WiTn+rEWhEGZtU1ZhVfClaFFQwdkXgZ/tmZY4+BpkKIXrqh0Iv9iP4dg==","shasum":"cbda5ade45fe221529ca064f76c3086fdf09e8c4","tarball":"http://registry-npm.ywwl.com/find-my-way/download/find-my-way-2.2.4.tgz","fileCount":46,"unpackedSize":171359,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfQ4NdCRA9TVsSAnZWagAAczoQAKTiME57MdatMNz71lrQ\n9t/IYqpAMN3JldYCBLL8SlsPi579l4NyKl+aKYWj1zo+l5WfHb5qO38Ht2/B\nvXvG2R1DsXPFVHqOYVBH/MkE7ignUxx+HJVkBCrVN7gtWmbbXOU82b8iQrvC\nQMwXiXzUai2ilo+kChQmBmAHZf7rZzPQS5O/M4kHewCVfnoQx70izVe+EaWC\nKW49VhyIQ/4EzJK5u1WXac6MT1zgjTPP8a8H151AUumKEGE2wxiWQ5uhz0um\n1bvZtRNRjeTBN7gyH2NKdFl5cszguegjc4TEG7SDmHPlNmCvEa+I04Byx4w0\nlmyHWD1NLqj8eFw7r0R/2pwL2QlOJmAtbrmmo8268Phd1DghzdwdKMKdiNSs\nNXebKBWW98XxfocRBj6CyoTKeoY+Yw2rgajAv/7y7ovh0V0uLJbBR5GVhfJw\nhHY65w6aNyn2e+cAlyCHVVQmhMAH3CdaDG8S15MuK17daRuezaiqJCHh0AbO\nqibZH6uT7JBCaTjsZGF/OCYHhjh6AYDHGBOiTwwDEng2eP+zixFvlIi4VE2U\nLusD948DGTjQe/IX4qA17KvYwcjlNLGya0dmXIPDwYRdJYRhJDuDhueGeivc\nQwZMWdoRvG9aQkeiBv8qkLMgyJpj2ThN0eB/vqYp0VFIjaLmTD3v8bVr6Lys\nxogk\r\n=FhHD\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICLAOcOIVkJr9mVlYDh2anK7C3zHDdCWtlQkAsayOGX+AiEAwKmRUKbearXFIbu99fAl+1bFD2Ao2RF68V7Gelmm5+I="}],"size":27441,"noattachment":false,"key":"/find-my-way/-/find-my-way-2.2.4.tgz"},"maintainers":[{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/find-my-way_2.2.4_1598260060888_0.9569457775459524"},"_hasShrinkwrap":false,"publish_time":1598260060994,"_cnpm_publish_time":1598260060994,"dist-tags":{"eight":"8.2.2","four":"4.5.1","latest":"9.10.0","legacy":"2.2.5"}}