@hoajs/tiny-router 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,8 @@
1
- ## v0.1.0 / 2025-10-13
1
+ ## v0.1.1 / 2026-02-12
2
2
 
3
- - init
3
+ - refactor: use tsdown instead of tsup
4
+ - chore(deps): update deps
5
+
6
+ ## v0.1.0 / 2025-10-13
7
+
8
+ - init
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 - present, Hoa contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 - present, Hoa contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,39 +1,39 @@
1
- ## @hoajs/tiny-router
2
-
3
- Tiny router middleware for Hoa.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- $ npm i @hoajs/tiny-router --save
9
- ```
10
-
11
- ## Quick Start
12
-
13
- ```js
14
- import { Hoa } from 'hoa'
15
- import { tinyRouter } from '@hoajs/tiny-router'
16
-
17
- const app = new Hoa()
18
- app.extend(tinyRouter())
19
-
20
- app.get('/users/:name', async (ctx, next) => {
21
- ctx.res.body = `Hello, ${ctx.req.params.name}!`
22
- })
23
-
24
- export default app
25
- ```
26
-
27
- ## Documentation
28
-
29
- The documentation is available on [hoa-js.com](https://hoa-js.com/middleware/router/tiny-router.html)
30
-
31
- ## Test (100% coverage)
32
-
33
- ```sh
34
- $ npm test
35
- ```
36
-
37
- ## License
38
-
39
- MIT
1
+ ## @hoajs/tiny-router
2
+
3
+ Tiny router middleware for Hoa.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ $ npm i @hoajs/tiny-router --save
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```js
14
+ import { Hoa } from 'hoa'
15
+ import { tinyRouter } from '@hoajs/tiny-router'
16
+
17
+ const app = new Hoa()
18
+ app.extend(tinyRouter())
19
+
20
+ app.get('/users/:name', async (ctx, next) => {
21
+ ctx.res.body = `Hello, ${ctx.req.params.name}!`
22
+ })
23
+
24
+ export default app
25
+ ```
26
+
27
+ ## Documentation
28
+
29
+ The documentation is available on [hoa-js.com](https://hoa-js.com/middleware/router/tiny-router.html)
30
+
31
+ ## Test (100% coverage)
32
+
33
+ ```sh
34
+ $ npm test
35
+ ```
36
+
37
+ ## License
38
+
39
+ MIT
@@ -0,0 +1,127 @@
1
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
2
+ let hoa = require("hoa");
3
+
4
+ //#region src/tinyRouter.js
5
+ const methods = [
6
+ "options",
7
+ "head",
8
+ "get",
9
+ "post",
10
+ "put",
11
+ "patch",
12
+ "delete"
13
+ ];
14
+ /**
15
+ * Hoa Tiny Router Extension
16
+ * Adds lightweight routing helpers (get/post/...) to Hoa applications using a minimal path compiler.
17
+ *
18
+ * Options:
19
+ * - sensitive: RegExp case sensitivity. When false (default), add the `i` flag.
20
+ * - trailing: Whether to allow an optional trailing slash (default: true).
21
+ *
22
+ * Returns: Extension function that augments the Hoa app with routing helpers.
23
+ *
24
+ * Example:
25
+ * app.use(tinyRouter({ trailing: true }))
26
+ * app.get('/users/:id', async (ctx) => {
27
+ * ctx.res.body = { id: ctx.req.params.id }
28
+ * })
29
+ *
30
+ * @param {Object} [options] Router configuration options.
31
+ * @param {boolean} [options.sensitive=false] Whether route regexp is case-sensitive. Defaults to insensitive (adds `i` flag).
32
+ * @param {boolean} [options.trailing=true] Whether to allow an optional trailing slash. When true, both `/path` and `/path/` match.
33
+ * @returns {Function} Extension function that augments the Hoa app with routing helpers.
34
+ */
35
+ function tinyRouter(options = {}) {
36
+ return function tinyRouterExtension(app) {
37
+ methods.forEach((method) => {
38
+ app[method] = createRouteMethod(method.toUpperCase());
39
+ });
40
+ app.all = createRouteMethod();
41
+ function createRouteMethod(method) {
42
+ return function(path, ...handlers) {
43
+ if (handlers.length === 0) throw new Error(`Route ${method || "ALL"} ${path} must have at least one handler`);
44
+ const routeMiddleware = createRoute(method, path, handlers, options);
45
+ app.use(routeMiddleware);
46
+ return app;
47
+ };
48
+ }
49
+ };
50
+ }
51
+ /**
52
+ * Create and register a route middleware.
53
+ * Matches the given path and method, parses params, and composes handlers.
54
+ * GET routes also handle HEAD requests as a conventional fallback.
55
+ *
56
+ * @param {string} [method] - HTTP method (uppercase), undefined for all methods
57
+ * @param {string} path - Route path pattern (supports ":name" and greedy ":name+" params, wildcard "*")
58
+ * @param {Function[]} handlers - Route handlers to execute on match
59
+ * @param {Object} options - Compile options passed through to {@link compile}
60
+ * @returns {Function} Route middleware (ctx, next) => Promise<void> | void
61
+ */
62
+ function createRoute(method, path, handlers, options) {
63
+ const regexp = compile(path, options);
64
+ const composed = handlers.length === 1 ? handlers[0] : (0, hoa.compose)(handlers);
65
+ return function routeMiddleware(ctx, next) {
66
+ if (!matches(ctx, method)) return next();
67
+ const m = regexp.exec(ctx.req.pathname);
68
+ if (!m) return next();
69
+ const params = {};
70
+ if (m.groups) for (const [key, value] of Object.entries(m.groups)) params[key] = decode(value);
71
+ ctx.req.params = params;
72
+ ctx.req.routePath = path;
73
+ return composed(ctx, next);
74
+ };
75
+ }
76
+ /**
77
+ * Decode a URL parameter value.
78
+ * Returns undefined for falsy input to preserve optional capture semantics.
79
+ *
80
+ * @param {string} val - Encoded parameter value
81
+ * @returns {string|undefined} Decoded value, or undefined if input is falsy
82
+ */
83
+ function decode(val) {
84
+ if (val) return decodeURIComponent(val);
85
+ }
86
+ /**
87
+ * Check if the request method matches the route method.
88
+ * Also treats HEAD requests as matching GET routes.
89
+ *
90
+ * @param {Object} ctx - Hoa context object containing the request
91
+ * @param {string} [method] - Route method (uppercase); when undefined, matches all methods
92
+ * @returns {boolean} Whether the current request method matches the route
93
+ */
94
+ function matches(ctx, method) {
95
+ if (!method) return true;
96
+ if (ctx.req.method === method) return true;
97
+ if (method === "GET" && ctx.req.method === "HEAD") return true;
98
+ return false;
99
+ }
100
+ /**
101
+ * Compile a path pattern into a RegExp.
102
+ * The compiler supports:
103
+ * - Stripping duplicate and trailing slashes
104
+ * - Greedy parameters (":name+") capturing to the end of the segment
105
+ * - Named parameters (":name") excluding segment boundary ("/" or "." if prefix contains dot)
106
+ * - Dot escaping and wildcard ("*") segments
107
+ * - Optional trailing slash via the `trailing` option
108
+ * - Case-insensitive matching unless `sensitive: true`
109
+ *
110
+ * @param {string} path - Route path pattern
111
+ * @param {Object} [options] - Compile options
112
+ * @param {boolean} [options.sensitive=false] - Case sensitivity (adds `i` flag when false)
113
+ * @param {boolean} [options.trailing=true] - Allow optional trailing slash
114
+ * @returns {RegExp} Compiled RegExp for matching the path
115
+ */
116
+ function compile(path, options) {
117
+ const { sensitive = false, trailing = true } = options;
118
+ const pattern = path.replace(/\/+(\/|$)/g, "$1").replace(/(\/?\.?):(\w+)\+/g, "($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g, "($1(?<$2>[^$1/]+?))").replace(/\./g, "\\.").replace(/(\/?)\*/g, "($1.*)?");
119
+ const patternWithTrailing = trailing ? `${pattern}(?:\\/)?` : pattern;
120
+ const flags = sensitive ? "" : "i";
121
+ return RegExp(`^${patternWithTrailing}$`, flags);
122
+ }
123
+
124
+ //#endregion
125
+ exports.default = tinyRouter;
126
+ exports.tinyRouter = tinyRouter;
127
+ exports.methods = methods;
@@ -0,0 +1,124 @@
1
+ import { compose } from "hoa";
2
+
3
+ //#region src/tinyRouter.js
4
+ const methods = [
5
+ "options",
6
+ "head",
7
+ "get",
8
+ "post",
9
+ "put",
10
+ "patch",
11
+ "delete"
12
+ ];
13
+ /**
14
+ * Hoa Tiny Router Extension
15
+ * Adds lightweight routing helpers (get/post/...) to Hoa applications using a minimal path compiler.
16
+ *
17
+ * Options:
18
+ * - sensitive: RegExp case sensitivity. When false (default), add the `i` flag.
19
+ * - trailing: Whether to allow an optional trailing slash (default: true).
20
+ *
21
+ * Returns: Extension function that augments the Hoa app with routing helpers.
22
+ *
23
+ * Example:
24
+ * app.use(tinyRouter({ trailing: true }))
25
+ * app.get('/users/:id', async (ctx) => {
26
+ * ctx.res.body = { id: ctx.req.params.id }
27
+ * })
28
+ *
29
+ * @param {Object} [options] Router configuration options.
30
+ * @param {boolean} [options.sensitive=false] Whether route regexp is case-sensitive. Defaults to insensitive (adds `i` flag).
31
+ * @param {boolean} [options.trailing=true] Whether to allow an optional trailing slash. When true, both `/path` and `/path/` match.
32
+ * @returns {Function} Extension function that augments the Hoa app with routing helpers.
33
+ */
34
+ function tinyRouter(options = {}) {
35
+ return function tinyRouterExtension(app) {
36
+ methods.forEach((method) => {
37
+ app[method] = createRouteMethod(method.toUpperCase());
38
+ });
39
+ app.all = createRouteMethod();
40
+ function createRouteMethod(method) {
41
+ return function(path, ...handlers) {
42
+ if (handlers.length === 0) throw new Error(`Route ${method || "ALL"} ${path} must have at least one handler`);
43
+ const routeMiddleware = createRoute(method, path, handlers, options);
44
+ app.use(routeMiddleware);
45
+ return app;
46
+ };
47
+ }
48
+ };
49
+ }
50
+ /**
51
+ * Create and register a route middleware.
52
+ * Matches the given path and method, parses params, and composes handlers.
53
+ * GET routes also handle HEAD requests as a conventional fallback.
54
+ *
55
+ * @param {string} [method] - HTTP method (uppercase), undefined for all methods
56
+ * @param {string} path - Route path pattern (supports ":name" and greedy ":name+" params, wildcard "*")
57
+ * @param {Function[]} handlers - Route handlers to execute on match
58
+ * @param {Object} options - Compile options passed through to {@link compile}
59
+ * @returns {Function} Route middleware (ctx, next) => Promise<void> | void
60
+ */
61
+ function createRoute(method, path, handlers, options) {
62
+ const regexp = compile(path, options);
63
+ const composed = handlers.length === 1 ? handlers[0] : compose(handlers);
64
+ return function routeMiddleware(ctx, next) {
65
+ if (!matches(ctx, method)) return next();
66
+ const m = regexp.exec(ctx.req.pathname);
67
+ if (!m) return next();
68
+ const params = {};
69
+ if (m.groups) for (const [key, value] of Object.entries(m.groups)) params[key] = decode(value);
70
+ ctx.req.params = params;
71
+ ctx.req.routePath = path;
72
+ return composed(ctx, next);
73
+ };
74
+ }
75
+ /**
76
+ * Decode a URL parameter value.
77
+ * Returns undefined for falsy input to preserve optional capture semantics.
78
+ *
79
+ * @param {string} val - Encoded parameter value
80
+ * @returns {string|undefined} Decoded value, or undefined if input is falsy
81
+ */
82
+ function decode(val) {
83
+ if (val) return decodeURIComponent(val);
84
+ }
85
+ /**
86
+ * Check if the request method matches the route method.
87
+ * Also treats HEAD requests as matching GET routes.
88
+ *
89
+ * @param {Object} ctx - Hoa context object containing the request
90
+ * @param {string} [method] - Route method (uppercase); when undefined, matches all methods
91
+ * @returns {boolean} Whether the current request method matches the route
92
+ */
93
+ function matches(ctx, method) {
94
+ if (!method) return true;
95
+ if (ctx.req.method === method) return true;
96
+ if (method === "GET" && ctx.req.method === "HEAD") return true;
97
+ return false;
98
+ }
99
+ /**
100
+ * Compile a path pattern into a RegExp.
101
+ * The compiler supports:
102
+ * - Stripping duplicate and trailing slashes
103
+ * - Greedy parameters (":name+") capturing to the end of the segment
104
+ * - Named parameters (":name") excluding segment boundary ("/" or "." if prefix contains dot)
105
+ * - Dot escaping and wildcard ("*") segments
106
+ * - Optional trailing slash via the `trailing` option
107
+ * - Case-insensitive matching unless `sensitive: true`
108
+ *
109
+ * @param {string} path - Route path pattern
110
+ * @param {Object} [options] - Compile options
111
+ * @param {boolean} [options.sensitive=false] - Case sensitivity (adds `i` flag when false)
112
+ * @param {boolean} [options.trailing=true] - Allow optional trailing slash
113
+ * @returns {RegExp} Compiled RegExp for matching the path
114
+ */
115
+ function compile(path, options) {
116
+ const { sensitive = false, trailing = true } = options;
117
+ const pattern = path.replace(/\/+(\/|$)/g, "$1").replace(/(\/?\.?):(\w+)\+/g, "($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g, "($1(?<$2>[^$1/]+?))").replace(/\./g, "\\.").replace(/(\/?)\*/g, "($1.*)?");
118
+ const patternWithTrailing = trailing ? `${pattern}(?:\\/)?` : pattern;
119
+ const flags = sensitive ? "" : "i";
120
+ return RegExp(`^${patternWithTrailing}$`, flags);
121
+ }
122
+
123
+ //#endregion
124
+ export { tinyRouter as default, tinyRouter, methods };
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@hoajs/tiny-router",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Tiny router middleware for Hoa.",
5
- "main": "./dist/cjs/tinyRouter.js",
5
+ "main": "./dist/cjs/tinyRouter.cjs",
6
6
  "type": "module",
7
- "module": "./dist/esm/tinyRouter.js",
7
+ "module": "./dist/esm/tinyRouter.mjs",
8
8
  "types": "./types/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
11
  "types": "./types/index.d.ts",
12
- "import": "./dist/esm/tinyRouter.js",
13
- "require": "./dist/cjs/tinyRouter.js",
14
- "default": "./dist/esm/tinyRouter.js"
12
+ "import": "./dist/esm/tinyRouter.mjs",
13
+ "require": "./dist/cjs/tinyRouter.cjs",
14
+ "default": "./dist/esm/tinyRouter.mjs"
15
15
  }
16
16
  },
17
17
  "files": [
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "scripts": {
23
23
  "lint": "eslint .",
24
- "build": "tsup",
24
+ "build": "tsdown",
25
25
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
26
26
  "prepublishOnly": "npm run lint && npm run test && npm run build",
27
27
  "prepare": "husky"
@@ -41,15 +41,15 @@
41
41
  "router"
42
42
  ],
43
43
  "devDependencies": {
44
- "@commitlint/cli": "20.1.0",
45
- "@commitlint/config-conventional": "20.0.0",
46
- "eslint": "9.37.0",
47
- "globals": "16.4.0",
44
+ "@commitlint/cli": "20.4.1",
45
+ "@commitlint/config-conventional": "20.4.1",
46
+ "eslint": "9.39.2",
47
+ "globals": "17.3.0",
48
48
  "hoa": "*",
49
49
  "husky": "9.1.7",
50
50
  "jest": "30.2.0",
51
51
  "neostandard": "0.12.2",
52
- "tsup": "8.5.0"
52
+ "tsdown": "^0.20.3"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "hoa": "*"
package/types/index.d.ts CHANGED
@@ -1,43 +1,43 @@
1
- // Type definitions for @hoajs/tiny-router
2
- // Project: https://github.com/hoa-js/tiny-router
3
- // Definitions by: nswbmw
4
-
5
- import type { Hoa, HoaMiddleware } from 'hoa'
6
-
7
- export type Method = 'options' | 'head' | 'get' | 'post' | 'put' | 'patch' | 'delete'
8
-
9
- export const methods: readonly Method[]
10
-
11
- export interface TinyRouterOptions {
12
- /** RegExp will be case sensitive (default: false) */
13
- sensitive?: boolean
14
- /** Allows optional trailing slash to match (default: true) */
15
- trailing?: boolean
16
- }
17
-
18
- export declare function tinyRouter (options?: TinyRouterOptions): (app: Hoa) => void
19
-
20
- export default tinyRouter
21
-
22
- /**
23
- * Module augmentation: extend Hoa with routing methods and request params fields
24
- */
25
- declare module 'hoa' {
26
- interface Hoa {
27
- options (path: string, ...handlers: HoaMiddleware[]): Hoa
28
- head (path: string, ...handlers: HoaMiddleware[]): Hoa
29
- get (path: string, ...handlers: HoaMiddleware[]): Hoa
30
- post (path: string, ...handlers: HoaMiddleware[]): Hoa
31
- put (path: string, ...handlers: HoaMiddleware[]): Hoa
32
- patch (path: string, ...handlers: HoaMiddleware[]): Hoa
33
- delete (path: string, ...handlers: HoaMiddleware[]): Hoa
34
- all (path: string, ...handlers: HoaMiddleware[]): Hoa
35
- }
36
-
37
- interface HoaRequest {
38
- /** Parsed route parameters set by @hoajs/tinyRouter */
39
- params?: Record<string, string | undefined>
40
- /** Matched route pattern for the current request */
41
- routePath?: string
42
- }
43
- }
1
+ // Type definitions for @hoajs/tiny-router
2
+ // Project: https://github.com/hoa-js/tiny-router
3
+ // Definitions by: nswbmw
4
+
5
+ import type { Hoa, HoaMiddleware, HoaExtension } from 'hoa'
6
+
7
+ export type Method = 'options' | 'head' | 'get' | 'post' | 'put' | 'patch' | 'delete'
8
+
9
+ export const methods: readonly Method[]
10
+
11
+ export interface TinyRouterOptions {
12
+ /** RegExp will be case sensitive (default: false) */
13
+ sensitive?: boolean
14
+ /** Allows optional trailing slash to match (default: true) */
15
+ trailing?: boolean
16
+ }
17
+
18
+ export declare function tinyRouter (options?: TinyRouterOptions): HoaExtension
19
+
20
+ export default tinyRouter
21
+
22
+ /**
23
+ * Module augmentation: extend Hoa with routing methods and request params fields
24
+ */
25
+ declare module 'hoa' {
26
+ interface Hoa {
27
+ options (path: string, ...handlers: HoaMiddleware[]): Hoa
28
+ head (path: string, ...handlers: HoaMiddleware[]): Hoa
29
+ get (path: string, ...handlers: HoaMiddleware[]): Hoa
30
+ post (path: string, ...handlers: HoaMiddleware[]): Hoa
31
+ put (path: string, ...handlers: HoaMiddleware[]): Hoa
32
+ patch (path: string, ...handlers: HoaMiddleware[]): Hoa
33
+ delete (path: string, ...handlers: HoaMiddleware[]): Hoa
34
+ all (path: string, ...handlers: HoaMiddleware[]): Hoa
35
+ }
36
+
37
+ interface HoaRequest {
38
+ /** Parsed route parameters set by @hoajs/tinyRouter */
39
+ params?: Record<string, string | undefined>
40
+ /** Matched route pattern for the current request */
41
+ routePath?: string
42
+ }
43
+ }
@@ -1,85 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
- var tinyRouter_exports = {};
19
- __export(tinyRouter_exports, {
20
- default: () => tinyRouter_default,
21
- methods: () => methods,
22
- tinyRouter: () => tinyRouter
23
- });
24
- module.exports = __toCommonJS(tinyRouter_exports);
25
- var import_hoa = require("hoa");
26
- const methods = ["options", "head", "get", "post", "put", "patch", "delete"];
27
- function tinyRouter(options = {}) {
28
- return function tinyRouterExtension(app) {
29
- methods.forEach((method) => {
30
- app[method] = createRouteMethod(method.toUpperCase());
31
- });
32
- app.all = createRouteMethod();
33
- function createRouteMethod(method) {
34
- return function(path, ...handlers) {
35
- if (handlers.length === 0) {
36
- throw new Error(`Route ${method || "ALL"} ${path} must have at least one handler`);
37
- }
38
- const routeMiddleware = createRoute(method, path, handlers, options);
39
- app.use(routeMiddleware);
40
- return app;
41
- };
42
- }
43
- };
44
- }
45
- function createRoute(method, path, handlers, options) {
46
- const regexp = compile(path, options);
47
- const composed = handlers.length === 1 ? handlers[0] : (0, import_hoa.compose)(handlers);
48
- return function routeMiddleware(ctx, next) {
49
- if (!matches(ctx, method)) return next();
50
- const m = regexp.exec(ctx.req.pathname);
51
- if (!m) return next();
52
- const params = {};
53
- if (m.groups) {
54
- for (const [key, value] of Object.entries(m.groups)) {
55
- params[key] = decode(value);
56
- }
57
- }
58
- ctx.req.params = params;
59
- ctx.req.routePath = path;
60
- return composed(ctx, next);
61
- };
62
- }
63
- function decode(val) {
64
- if (val) return decodeURIComponent(val);
65
- }
66
- function matches(ctx, method) {
67
- if (!method) return true;
68
- if (ctx.req.method === method) return true;
69
- if (method === "GET" && ctx.req.method === "HEAD") return true;
70
- return false;
71
- }
72
- function compile(path, options) {
73
- const { sensitive = false, trailing = true } = options;
74
- const pattern = path.replace(/\/+(\/|$)/g, "$1").replace(/(\/?\.?):(\w+)\+/g, "($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g, "($1(?<$2>[^$1/]+?))").replace(/\./g, "\\.").replace(/(\/?)\*/g, "($1.*)?");
75
- const patternWithTrailing = trailing ? `${pattern}(?:\\/)?` : pattern;
76
- const flags = sensitive ? "" : "i";
77
- const regexp = RegExp(`^${patternWithTrailing}$`, flags);
78
- return regexp;
79
- }
80
- var tinyRouter_default = tinyRouter;
81
- // Annotate the CommonJS export names for ESM import in node:
82
- 0 && (module.exports = {
83
- methods,
84
- tinyRouter
85
- });
@@ -1,61 +0,0 @@
1
- import { compose } from "hoa";
2
- const methods = ["options", "head", "get", "post", "put", "patch", "delete"];
3
- function tinyRouter(options = {}) {
4
- return function tinyRouterExtension(app) {
5
- methods.forEach((method) => {
6
- app[method] = createRouteMethod(method.toUpperCase());
7
- });
8
- app.all = createRouteMethod();
9
- function createRouteMethod(method) {
10
- return function(path, ...handlers) {
11
- if (handlers.length === 0) {
12
- throw new Error(`Route ${method || "ALL"} ${path} must have at least one handler`);
13
- }
14
- const routeMiddleware = createRoute(method, path, handlers, options);
15
- app.use(routeMiddleware);
16
- return app;
17
- };
18
- }
19
- };
20
- }
21
- function createRoute(method, path, handlers, options) {
22
- const regexp = compile(path, options);
23
- const composed = handlers.length === 1 ? handlers[0] : compose(handlers);
24
- return function routeMiddleware(ctx, next) {
25
- if (!matches(ctx, method)) return next();
26
- const m = regexp.exec(ctx.req.pathname);
27
- if (!m) return next();
28
- const params = {};
29
- if (m.groups) {
30
- for (const [key, value] of Object.entries(m.groups)) {
31
- params[key] = decode(value);
32
- }
33
- }
34
- ctx.req.params = params;
35
- ctx.req.routePath = path;
36
- return composed(ctx, next);
37
- };
38
- }
39
- function decode(val) {
40
- if (val) return decodeURIComponent(val);
41
- }
42
- function matches(ctx, method) {
43
- if (!method) return true;
44
- if (ctx.req.method === method) return true;
45
- if (method === "GET" && ctx.req.method === "HEAD") return true;
46
- return false;
47
- }
48
- function compile(path, options) {
49
- const { sensitive = false, trailing = true } = options;
50
- const pattern = path.replace(/\/+(\/|$)/g, "$1").replace(/(\/?\.?):(\w+)\+/g, "($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g, "($1(?<$2>[^$1/]+?))").replace(/\./g, "\\.").replace(/(\/?)\*/g, "($1.*)?");
51
- const patternWithTrailing = trailing ? `${pattern}(?:\\/)?` : pattern;
52
- const flags = sensitive ? "" : "i";
53
- const regexp = RegExp(`^${patternWithTrailing}$`, flags);
54
- return regexp;
55
- }
56
- var tinyRouter_default = tinyRouter;
57
- export {
58
- tinyRouter_default as default,
59
- methods,
60
- tinyRouter
61
- };