extreme-router 1.1.0 → 1.2.0

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.
@@ -1,130 +1,130 @@
1
- ```html
2
- <!DOCTYPE html>
3
- <html lang="en">
4
- <head>
5
- <meta charset="UTF-8" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>Extreme Router Browser Example</title>
8
- <script type="module">
9
- // Dynamically determine the latest version or use a specific one
10
- const version = 'latest'; // Or specify a version like '1.0.0'
11
- const importUrl = `https://cdn.jsdelivr.net/npm/extreme-router@${version}/dist/index.js`;
12
-
13
- // Ensure the output div exists before trying to set its text content
14
- window.addEventListener('DOMContentLoaded', () => {
15
- const outputDiv = document.getElementById('output');
16
- if (outputDiv) {
17
- outputDiv.textContent = `Loading Extreme Router from ${importUrl}...`;
18
- } else {
19
- console.error('Output div not found on DOMContentLoaded');
20
- }
21
- initializeRouter();
22
- });
23
-
24
- async function initializeRouter() {
25
- const outputDiv = document.getElementById('output');
26
-
27
- try {
28
- const extremeRouterModule = await import(importUrl);
29
-
30
- const Extreme = extremeRouterModule.default;
31
- const param = extremeRouterModule.param;
32
- const wildcard = extremeRouterModule.wildcard;
33
-
34
- // 1. Initialize the router
35
- const router = new Extreme();
36
-
37
- // 2. Register plugins
38
- router.use(param).use(wildcard);
39
-
40
- // 3. Define handlers
41
- const homeHandler = () => {
42
- if (outputDiv) outputDiv.textContent = 'Welcome Home!';
43
- };
44
-
45
- const userHandler = (params) => {
46
- if (outputDiv) outputDiv.textContent = `User ID: ${params.userId}`;
47
- };
48
-
49
- const fileHandler = (params) => {
50
- if (outputDiv) outputDiv.textContent = `File path: ${params['*']}`;
51
- };
52
-
53
- const notFoundHandler = () => {
54
- if (outputDiv) outputDiv.textContent = '404 - Page Not Found';
55
- };
56
-
57
- // 4. Register routes
58
- router.register('/').handler = homeHandler;
59
- router.register('/users/:userId').handler = userHandler;
60
- router.register('/files/*').handler = fileHandler;
61
-
62
- // 5. Function to match and execute handler
63
- function handleRouteChange() {
64
- const path = window.location.hash.substring(1) || '/';
65
- console.log(`Hash changed. Attempting to match route: ${path}`);
66
- const match = router.match(path);
67
-
68
- if (match && match.handler) {
69
- if (match.params) {
70
- match.handler(match.params);
71
- } else {
72
- match.handler();
73
- }
74
- } else {
75
- notFoundHandler();
76
- }
77
- }
78
-
79
- // 6. Listen to hash changes and initial load
80
- window.addEventListener('hashchange', handleRouteChange);
81
- // The 'load' event for the window might have already fired if script is deferred or DOMContentLoaded is used.
82
- // We call handleRouteChange directly after setup.
83
- handleRouteChange(); // Initial route handling
84
-
85
- document.getElementById('goHome').addEventListener('click', () => (window.location.hash = '#/'));
86
- document.getElementById('goUser123').addEventListener('click', () => (window.location.hash = '#/users/123'));
87
- document
88
- .getElementById('goFile')
89
- .addEventListener('click', () => (window.location.hash = '#/files/docs/report.pdf'));
90
- document
91
- .getElementById('goNonExistent')
92
- .addEventListener('click', () => (window.location.hash = '#/nonexistent'));
93
- console.log('Event listeners for navigation buttons set up.');
94
- if (outputDiv && !outputDiv.textContent.startsWith('Error:')) {
95
- outputDiv.textContent = 'Extreme Router initialized. Navigate using buttons or by changing the URL hash.';
96
- }
97
- } catch (error) {
98
- const errorMsg = `Failed to load or initialize Extreme Router: ${error.message}. See console for more details.`;
99
- console.error(errorMsg, error);
100
- if (outputDiv) outputDiv.textContent = errorMsg;
101
- }
102
- }
103
- </script>
104
- </head>
105
- <body>
106
- <h1>Extreme Router Browser Example</h1>
107
- <p>
108
- Navigate using the links below (changes URL hash) or type directly into the address bar (e.g.,
109
- <code>#/users/456</code>).
110
- </p>
111
- <nav>
112
- <button id="goHome">Home (/)</button>
113
- <button id="goUser123">User 123 (/users/123)</button>
114
- <button id="goFile">File (/files/docs/report.pdf)</button>
115
- <button id="goNonExistent">Non Existent (/nonexistent)</button>
116
- </nav>
117
- <hr />
118
- <h2>Current Route Output:</h2>
119
- <div id="output" style="font-family: monospace; background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc;">
120
- Loading...
121
- </div>
122
-
123
- <p>Check the browser console for more detailed logs.</p>
124
- <p>
125
- This example loads Extreme Router from JSDelivr:
126
- <code>https://cdn.jsdelivr.net/npm/extreme-router@latest/dist/index.js</code>
127
- </p>
128
- </body>
129
- </html>
130
- ```
1
+ ```html
2
+ <!DOCTYPE html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Extreme Router Browser Example</title>
8
+ <script type="module">
9
+ // Dynamically determine the latest version or use a specific one
10
+ const version = 'latest'; // Or specify a version like '1.0.0'
11
+ const importUrl = `https://cdn.jsdelivr.net/npm/extreme-router@${version}/dist/index.js`;
12
+
13
+ // Ensure the output div exists before trying to set its text content
14
+ window.addEventListener('DOMContentLoaded', () => {
15
+ const outputDiv = document.getElementById('output');
16
+ if (outputDiv) {
17
+ outputDiv.textContent = `Loading Extreme Router from ${importUrl}...`;
18
+ } else {
19
+ console.error('Output div not found on DOMContentLoaded');
20
+ }
21
+ initializeRouter();
22
+ });
23
+
24
+ async function initializeRouter() {
25
+ const outputDiv = document.getElementById('output');
26
+
27
+ try {
28
+ const extremeRouterModule = await import(importUrl);
29
+
30
+ const Extreme = extremeRouterModule.default;
31
+ const param = extremeRouterModule.param;
32
+ const wildcard = extremeRouterModule.wildcard;
33
+
34
+ // 1. Initialize the router
35
+ const router = new Extreme();
36
+
37
+ // 2. Register plugins
38
+ router.use(param).use(wildcard);
39
+
40
+ // 3. Define handlers
41
+ const homeHandler = () => {
42
+ if (outputDiv) outputDiv.textContent = 'Welcome Home!';
43
+ };
44
+
45
+ const userHandler = (params) => {
46
+ if (outputDiv) outputDiv.textContent = `User ID: ${params.userId}`;
47
+ };
48
+
49
+ const fileHandler = (params) => {
50
+ if (outputDiv) outputDiv.textContent = `File path: ${params['*']}`;
51
+ };
52
+
53
+ const notFoundHandler = () => {
54
+ if (outputDiv) outputDiv.textContent = '404 - Page Not Found';
55
+ };
56
+
57
+ // 4. Register routes
58
+ router.register('/').handler = homeHandler;
59
+ router.register('/users/:userId').handler = userHandler;
60
+ router.register('/files/*').handler = fileHandler;
61
+
62
+ // 5. Function to match and execute handler
63
+ function handleRouteChange() {
64
+ const path = window.location.hash.substring(1) || '/';
65
+ console.log(`Hash changed. Attempting to match route: ${path}`);
66
+ const match = router.match(path);
67
+
68
+ if (match && match.handler) {
69
+ if (match.params) {
70
+ match.handler(match.params);
71
+ } else {
72
+ match.handler();
73
+ }
74
+ } else {
75
+ notFoundHandler();
76
+ }
77
+ }
78
+
79
+ // 6. Listen to hash changes and initial load
80
+ window.addEventListener('hashchange', handleRouteChange);
81
+ // The 'load' event for the window might have already fired if script is deferred or DOMContentLoaded is used.
82
+ // We call handleRouteChange directly after setup.
83
+ handleRouteChange(); // Initial route handling
84
+
85
+ document.getElementById('goHome').addEventListener('click', () => (window.location.hash = '#/'));
86
+ document.getElementById('goUser123').addEventListener('click', () => (window.location.hash = '#/users/123'));
87
+ document
88
+ .getElementById('goFile')
89
+ .addEventListener('click', () => (window.location.hash = '#/files/docs/report.pdf'));
90
+ document
91
+ .getElementById('goNonExistent')
92
+ .addEventListener('click', () => (window.location.hash = '#/nonexistent'));
93
+ console.log('Event listeners for navigation buttons set up.');
94
+ if (outputDiv && !outputDiv.textContent.startsWith('Error:')) {
95
+ outputDiv.textContent = 'Extreme Router initialized. Navigate using buttons or by changing the URL hash.';
96
+ }
97
+ } catch (error) {
98
+ const errorMsg = `Failed to load or initialize Extreme Router: ${error.message}. See console for more details.`;
99
+ console.error(errorMsg, error);
100
+ if (outputDiv) outputDiv.textContent = errorMsg;
101
+ }
102
+ }
103
+ </script>
104
+ </head>
105
+ <body>
106
+ <h1>Extreme Router Browser Example</h1>
107
+ <p>
108
+ Navigate using the links below (changes URL hash) or type directly into the address bar (e.g.,
109
+ <code>#/users/456</code>).
110
+ </p>
111
+ <nav>
112
+ <button id="goHome">Home (/)</button>
113
+ <button id="goUser123">User 123 (/users/123)</button>
114
+ <button id="goFile">File (/files/docs/report.pdf)</button>
115
+ <button id="goNonExistent">Non Existent (/nonexistent)</button>
116
+ </nav>
117
+ <hr />
118
+ <h2>Current Route Output:</h2>
119
+ <div id="output" style="font-family: monospace; background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc;">
120
+ Loading...
121
+ </div>
122
+
123
+ <p>Check the browser console for more detailed logs.</p>
124
+ <p>
125
+ This example loads Extreme Router from JSDelivr:
126
+ <code>https://cdn.jsdelivr.net/npm/extreme-router@latest/dist/index.js</code>
127
+ </p>
128
+ </body>
129
+ </html>
130
+ ```
@@ -1,73 +1,73 @@
1
- ```typescript
2
- // server.bun.ts
3
- import Extreme, { param, wildcard } from 'extreme-router';
4
-
5
- // Define the type for your route store, mapping methods to handlers
6
- type MethodHandler = (req: Request, params?: Record<string, string>) => Response;
7
- type RouteStore = {
8
- [method: string]: MethodHandler; // e.g., GET, POST
9
- };
10
-
11
- // Initialize the router
12
- const router = new Extreme<RouteStore>();
13
-
14
- // Register plugins (chaining supported)
15
- router.use(param).use(wildcard);
16
-
17
- // --- Define Handlers ---
18
- const homeHandler: MethodHandler = () => new Response('Welcome Home! (GET)');
19
- const createUserHandler: MethodHandler = async (req) => {
20
- const body = await req.text();
21
- return new Response(`Creating user... (POST) Data: ${body}`, { status: 201 });
22
- };
23
- const userHandler: MethodHandler = (req, params) => new Response(`User ID: ${params?.userId} (GET)`);
24
- const updateUserHandler: MethodHandler = async (req, params) => {
25
- const body = await req.text();
26
- return new Response(`Updating user ${params?.userId}... (PUT) Data: ${body}`);
27
- };
28
- const fileHandler: MethodHandler = (req, params) => new Response(`File path: ${params?.['*']} (GET)`);
29
- const notFoundHandler: MethodHandler = () => new Response('Not Found', { status: 404 });
30
- const methodNotAllowedHandler: MethodHandler = () => new Response('Method Not Allowed', { status: 405 });
31
-
32
- // --- Register Routes and Methods ---
33
- router.register('/').GET = homeHandler; // Assign handler to GET method
34
-
35
- const userRoute = router.register('/users/:userId');
36
- userRoute.GET = userHandler;
37
- userRoute.PUT = updateUserHandler;
38
-
39
- router.register('/users').POST = createUserHandler; // POST to collection
40
-
41
- router.register('/files/*').GET = fileHandler;
42
-
43
- // Create Bun server
44
- Bun.serve({
45
- port: 3000,
46
- fetch(req) {
47
- const url = new URL(req.url);
48
- const match = router.match(url.pathname);
49
-
50
- if (match) {
51
- // Check if a handler exists for the request method
52
- const handler = match[req.method as keyof RouteStore];
53
- if (handler) {
54
- if ('params' in match && match.params) {
55
- // Dynamic route match
56
- return handler(req, match.params);
57
- } else {
58
- // Static route match
59
- return handler(req);
60
- }
61
- } else {
62
- // Path matched, but method not allowed
63
- return methodNotAllowedHandler(req);
64
- }
65
- }
66
-
67
- // No path match found
68
- return notFoundHandler(req);
69
- },
70
- });
71
-
72
- console.log('Bun server listening on http://localhost:3000');
73
- ```
1
+ ```typescript
2
+ // server.bun.ts
3
+ import Extreme, { param, wildcard } from 'extreme-router';
4
+
5
+ // Define the type for your route store, mapping methods to handlers
6
+ type MethodHandler = (req: Request, params?: Record<string, string>) => Response;
7
+ type RouteStore = {
8
+ [method: string]: MethodHandler; // e.g., GET, POST
9
+ };
10
+
11
+ // Initialize the router
12
+ const router = new Extreme<RouteStore>();
13
+
14
+ // Register plugins (chaining supported)
15
+ router.use(param).use(wildcard);
16
+
17
+ // --- Define Handlers ---
18
+ const homeHandler: MethodHandler = () => new Response('Welcome Home! (GET)');
19
+ const createUserHandler: MethodHandler = async (req) => {
20
+ const body = await req.text();
21
+ return new Response(`Creating user... (POST) Data: ${body}`, { status: 201 });
22
+ };
23
+ const userHandler: MethodHandler = (req, params) => new Response(`User ID: ${params?.userId} (GET)`);
24
+ const updateUserHandler: MethodHandler = async (req, params) => {
25
+ const body = await req.text();
26
+ return new Response(`Updating user ${params?.userId}... (PUT) Data: ${body}`);
27
+ };
28
+ const fileHandler: MethodHandler = (req, params) => new Response(`File path: ${params?.['*']} (GET)`);
29
+ const notFoundHandler: MethodHandler = () => new Response('Not Found', { status: 404 });
30
+ const methodNotAllowedHandler: MethodHandler = () => new Response('Method Not Allowed', { status: 405 });
31
+
32
+ // --- Register Routes and Methods ---
33
+ router.register('/').GET = homeHandler; // Assign handler to GET method
34
+
35
+ const userRoute = router.register('/users/:userId');
36
+ userRoute.GET = userHandler;
37
+ userRoute.PUT = updateUserHandler;
38
+
39
+ router.register('/users').POST = createUserHandler; // POST to collection
40
+
41
+ router.register('/files/*').GET = fileHandler;
42
+
43
+ // Create Bun server
44
+ Bun.serve({
45
+ port: 3000,
46
+ fetch(req) {
47
+ const url = new URL(req.url);
48
+ const match = router.match(url.pathname);
49
+
50
+ if (match) {
51
+ // Check if a handler exists for the request method
52
+ const handler = match[req.method as keyof RouteStore];
53
+ if (handler) {
54
+ if ('params' in match && match.params) {
55
+ // Dynamic route match
56
+ return handler(req, match.params);
57
+ } else {
58
+ // Static route match
59
+ return handler(req);
60
+ }
61
+ } else {
62
+ // Path matched, but method not allowed
63
+ return methodNotAllowedHandler(req);
64
+ }
65
+ }
66
+
67
+ // No path match found
68
+ return notFoundHandler(req);
69
+ },
70
+ });
71
+
72
+ console.log('Bun server listening on http://localhost:3000');
73
+ ```
@@ -1,71 +1,71 @@
1
- ```typescript
2
- // server.deno.ts
3
- // @deno-types="npm:extreme-router/dist/index.d.ts"
4
- import Extreme, { param, wildcard } from 'npm:extreme-router';
5
-
6
- // Define the type for your route store, mapping methods to handlers
7
- type MethodHandler = (req: Request, params?: Record<string, string>) => Response | Promise<Response>;
8
- type RouteStore = {
9
- [method: string]: MethodHandler; // e.g., GET, POST
10
- };
11
-
12
- // Initialize the router
13
- const router = new Extreme<RouteStore>();
14
-
15
- // Register plugins (chaining supported)
16
- router.use(param).use(wildcard);
17
-
18
- // --- Define Handlers ---
19
- const homeHandler: MethodHandler = () => new Response('Welcome Home! (GET)');
20
- const createUserHandler: MethodHandler = async (req) => {
21
- const body = await req.text();
22
- return new Response(`Creating user... (POST) Data: ${body}`, { status: 201 });
23
- };
24
- const userHandler: MethodHandler = (req, params) => new Response(`User ID: ${params?.userId} (GET)`);
25
- const updateUserHandler: MethodHandler = async (req, params) => {
26
- const body = await req.text();
27
- return new Response(`Updating user ${params?.userId}... (PUT) Data: ${body}`);
28
- };
29
- const fileHandler: MethodHandler = (req, params) => new Response(`File path: ${params?.['*']} (GET)`);
30
- const notFoundHandler: MethodHandler = () => new Response('Not Found', { status: 404 });
31
- const methodNotAllowedHandler: MethodHandler = () => new Response('Method Not Allowed', { status: 405 });
32
-
33
- // --- Register Routes and Methods ---
34
- router.register('/').GET = homeHandler;
35
-
36
- const userRoute = router.register('/users/:userId');
37
- userRoute.GET = userHandler;
38
- userRoute.PUT = updateUserHandler;
39
-
40
- router.register('/users').POST = createUserHandler;
41
-
42
- router.register('/files/*').GET = fileHandler;
43
-
44
- // Create Deno server
45
- Deno.serve({ port: 3000 }, (req) => {
46
- const url = new URL(req.url);
47
- const match = router.match(url.pathname);
48
-
49
- if (match) {
50
- // Check if a handler exists for the request method
51
- const handler = match[req.method as keyof RouteStore];
52
- if (handler) {
53
- if ('params' in match && match.params) {
54
- // Dynamic route match
55
- return handler(req, match.params);
56
- } else {
57
- // Static route match
58
- return handler(req);
59
- }
60
- } else {
61
- // Path matched, but method not allowed
62
- return methodNotAllowedHandler(req);
63
- }
64
- }
65
-
66
- // No path match found
67
- return notFoundHandler(req);
68
- });
69
-
70
- console.log('Deno server listening on http://localhost:3000');
71
- ```
1
+ ```typescript
2
+ // server.deno.ts
3
+ // @deno-types="npm:extreme-router/dist/index.d.ts"
4
+ import Extreme, { param, wildcard } from 'npm:extreme-router';
5
+
6
+ // Define the type for your route store, mapping methods to handlers
7
+ type MethodHandler = (req: Request, params?: Record<string, string>) => Response | Promise<Response>;
8
+ type RouteStore = {
9
+ [method: string]: MethodHandler; // e.g., GET, POST
10
+ };
11
+
12
+ // Initialize the router
13
+ const router = new Extreme<RouteStore>();
14
+
15
+ // Register plugins (chaining supported)
16
+ router.use(param).use(wildcard);
17
+
18
+ // --- Define Handlers ---
19
+ const homeHandler: MethodHandler = () => new Response('Welcome Home! (GET)');
20
+ const createUserHandler: MethodHandler = async (req) => {
21
+ const body = await req.text();
22
+ return new Response(`Creating user... (POST) Data: ${body}`, { status: 201 });
23
+ };
24
+ const userHandler: MethodHandler = (req, params) => new Response(`User ID: ${params?.userId} (GET)`);
25
+ const updateUserHandler: MethodHandler = async (req, params) => {
26
+ const body = await req.text();
27
+ return new Response(`Updating user ${params?.userId}... (PUT) Data: ${body}`);
28
+ };
29
+ const fileHandler: MethodHandler = (req, params) => new Response(`File path: ${params?.['*']} (GET)`);
30
+ const notFoundHandler: MethodHandler = () => new Response('Not Found', { status: 404 });
31
+ const methodNotAllowedHandler: MethodHandler = () => new Response('Method Not Allowed', { status: 405 });
32
+
33
+ // --- Register Routes and Methods ---
34
+ router.register('/').GET = homeHandler;
35
+
36
+ const userRoute = router.register('/users/:userId');
37
+ userRoute.GET = userHandler;
38
+ userRoute.PUT = updateUserHandler;
39
+
40
+ router.register('/users').POST = createUserHandler;
41
+
42
+ router.register('/files/*').GET = fileHandler;
43
+
44
+ // Create Deno server
45
+ Deno.serve({ port: 3000 }, (req) => {
46
+ const url = new URL(req.url);
47
+ const match = router.match(url.pathname);
48
+
49
+ if (match) {
50
+ // Check if a handler exists for the request method
51
+ const handler = match[req.method as keyof RouteStore];
52
+ if (handler) {
53
+ if ('params' in match && match.params) {
54
+ // Dynamic route match
55
+ return handler(req, match.params);
56
+ } else {
57
+ // Static route match
58
+ return handler(req);
59
+ }
60
+ } else {
61
+ // Path matched, but method not allowed
62
+ return methodNotAllowedHandler(req);
63
+ }
64
+ }
65
+
66
+ // No path match found
67
+ return notFoundHandler(req);
68
+ });
69
+
70
+ console.log('Deno server listening on http://localhost:3000');
71
+ ```