@constela/router 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Constela 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.
@@ -0,0 +1,79 @@
1
+ import { CompiledProgram } from '@constela/compiler';
2
+
3
+ /**
4
+ * Router - Main routing implementation
5
+ */
6
+
7
+ interface RouteContext {
8
+ path: string;
9
+ params: Record<string, string>;
10
+ query: URLSearchParams;
11
+ }
12
+ interface RouteDef {
13
+ path: string;
14
+ program: CompiledProgram;
15
+ title?: string | ((ctx: RouteContext) => string);
16
+ }
17
+ interface RouterOptions {
18
+ routes: RouteDef[];
19
+ basePath?: string;
20
+ fallback?: CompiledProgram;
21
+ onRouteChange?: (ctx: RouteContext) => void;
22
+ }
23
+ interface RouterInstance {
24
+ mount(el: HTMLElement): {
25
+ destroy(): void;
26
+ };
27
+ navigate(to: string, opts?: {
28
+ replace?: boolean;
29
+ }): void;
30
+ getContext(): RouteContext;
31
+ }
32
+ declare function createRouter(options: RouterOptions): RouterInstance;
33
+
34
+ /**
35
+ * Router helper functions
36
+ */
37
+
38
+ /**
39
+ * Binds an anchor element to use the router for navigation
40
+ *
41
+ * @param router - Router instance
42
+ * @param anchor - Anchor element to bind
43
+ * @param to - Path to navigate to (optional, uses href if not provided)
44
+ * @returns Cleanup function to remove the binding
45
+ */
46
+ declare function bindLink(router: RouterInstance, anchor: HTMLAnchorElement, to?: string): () => void;
47
+ /**
48
+ * Creates a link element bound to the router
49
+ *
50
+ * @param router - Router instance
51
+ * @param to - Path to navigate to
52
+ * @param text - Link text content
53
+ * @returns Object with element and destroy function
54
+ */
55
+ declare function createLink(router: RouterInstance, to: string, text: string): {
56
+ element: HTMLAnchorElement;
57
+ destroy: () => void;
58
+ };
59
+
60
+ /**
61
+ * Route matching utilities
62
+ */
63
+ interface MatchResult {
64
+ params: Record<string, string>;
65
+ }
66
+ /**
67
+ * Matches a URL path against a route pattern
68
+ *
69
+ * @param pattern - Route pattern (e.g., "/users/:id")
70
+ * @param path - URL path to match (e.g., "/users/123")
71
+ * @returns Match result with params, or null if no match
72
+ */
73
+ declare function matchRoute(pattern: string, path: string): MatchResult | null;
74
+ /**
75
+ * Parses URL params from a matched route
76
+ */
77
+ declare function parseParams(pattern: string, path: string): Record<string, string>;
78
+
79
+ export { type RouteContext, type RouteDef, type RouterInstance, type RouterOptions, bindLink, createLink, createRouter, matchRoute, parseParams };
package/dist/index.js ADDED
@@ -0,0 +1,172 @@
1
+ // src/router.ts
2
+ import { createApp } from "@constela/runtime";
3
+
4
+ // src/matcher.ts
5
+ function matchRoute(pattern, path) {
6
+ const normalizedPattern = pattern === "/" ? "/" : pattern.replace(/\/+$/, "");
7
+ const normalizedPath = path === "/" ? "/" : path.replace(/\/+$/, "");
8
+ if (normalizedPattern === "/") {
9
+ return normalizedPath === "/" ? { params: {} } : null;
10
+ }
11
+ const patternParts = normalizedPattern.split("/").filter(Boolean);
12
+ const pathParts = normalizedPath.split("/").filter(Boolean);
13
+ if (patternParts.length !== pathParts.length) {
14
+ return null;
15
+ }
16
+ const params = {};
17
+ for (let i = 0; i < patternParts.length; i++) {
18
+ const patternPart = patternParts[i];
19
+ const pathPart = pathParts[i];
20
+ if (patternPart.startsWith(":")) {
21
+ const paramName = patternPart.slice(1);
22
+ params[paramName] = decodeURIComponent(pathPart);
23
+ } else if (patternPart !== pathPart) {
24
+ return null;
25
+ }
26
+ }
27
+ return { params };
28
+ }
29
+ function parseParams(pattern, path) {
30
+ const match = matchRoute(pattern, path);
31
+ return match?.params ?? {};
32
+ }
33
+
34
+ // src/router.ts
35
+ function createRouter(options) {
36
+ const { routes, basePath = "", fallback, onRouteChange } = options;
37
+ const normalizedBasePath = basePath.replace(/\/+$/, "");
38
+ let mountElement = null;
39
+ let currentApp = null;
40
+ let currentContext = {
41
+ path: "",
42
+ params: {},
43
+ query: new URLSearchParams()
44
+ };
45
+ let destroyed = false;
46
+ function normalizePath(path) {
47
+ const [pathPart, queryPart] = path.split("?");
48
+ const cleanPath = pathPart.startsWith("/") ? pathPart : "/" + pathPart;
49
+ const fullPath = normalizedBasePath ? normalizedBasePath + cleanPath : cleanPath;
50
+ return queryPart ? `${fullPath}?${queryPart}` : fullPath;
51
+ }
52
+ function parseCurrentUrl() {
53
+ const rawPathname = window.location.pathname;
54
+ const [pathnameWithoutQuery, embeddedQuery] = rawPathname.split("?");
55
+ const pathname = pathnameWithoutQuery;
56
+ const queryString = window.location.search || (embeddedQuery ? `?${embeddedQuery}` : "");
57
+ const path = normalizedBasePath ? pathname.replace(new RegExp(`^${normalizedBasePath}`), "") || "/" : pathname;
58
+ const query = new URLSearchParams(queryString);
59
+ return { path, query };
60
+ }
61
+ function findMatchingRoute(path) {
62
+ for (const route of routes) {
63
+ const match = matchRoute(route.path, path);
64
+ if (match) {
65
+ return { route, params: match.params };
66
+ }
67
+ }
68
+ return { route: null, params: {} };
69
+ }
70
+ function renderRoute() {
71
+ if (!mountElement) return;
72
+ if (currentApp) {
73
+ currentApp.destroy();
74
+ currentApp = null;
75
+ }
76
+ const { path, query } = parseCurrentUrl();
77
+ const { route, params } = findMatchingRoute(path);
78
+ currentContext = {
79
+ path,
80
+ params,
81
+ query
82
+ };
83
+ const program = route?.program ?? fallback;
84
+ if (!program) {
85
+ throw new Error(`No route matched for path: ${path} and no fallback provided`);
86
+ }
87
+ currentApp = createApp(program, mountElement);
88
+ if (route?.title) {
89
+ const title = typeof route.title === "function" ? route.title(currentContext) : route.title;
90
+ document.title = title;
91
+ }
92
+ if (onRouteChange) {
93
+ onRouteChange(currentContext);
94
+ }
95
+ }
96
+ function handlePopState() {
97
+ if (destroyed || !mountElement) return;
98
+ try {
99
+ renderRoute();
100
+ } catch (error) {
101
+ console.error("Router error during navigation:", error);
102
+ }
103
+ }
104
+ return {
105
+ mount(el) {
106
+ mountElement = el;
107
+ window.addEventListener("popstate", handlePopState);
108
+ renderRoute();
109
+ return {
110
+ destroy() {
111
+ if (destroyed) return;
112
+ destroyed = true;
113
+ window.removeEventListener("popstate", handlePopState);
114
+ if (currentApp) {
115
+ currentApp.destroy();
116
+ currentApp = null;
117
+ }
118
+ mountElement = null;
119
+ }
120
+ };
121
+ },
122
+ navigate(to, opts) {
123
+ if (!mountElement) return;
124
+ const fullPath = normalizePath(to);
125
+ if (opts?.replace) {
126
+ window.history.replaceState({}, "", fullPath);
127
+ } else {
128
+ window.history.pushState({}, "", fullPath);
129
+ }
130
+ renderRoute();
131
+ },
132
+ getContext() {
133
+ return { ...currentContext };
134
+ }
135
+ };
136
+ }
137
+
138
+ // src/helpers.ts
139
+ function bindLink(router, anchor, to) {
140
+ const targetPath = to ?? anchor.getAttribute("href") ?? "/";
141
+ function handleClick(event) {
142
+ if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
143
+ return;
144
+ }
145
+ if (event.button !== 0) {
146
+ return;
147
+ }
148
+ event.preventDefault();
149
+ router.navigate(targetPath);
150
+ }
151
+ anchor.addEventListener("click", handleClick);
152
+ return () => {
153
+ anchor.removeEventListener("click", handleClick);
154
+ };
155
+ }
156
+ function createLink(router, to, text) {
157
+ const anchor = document.createElement("a");
158
+ anchor.href = to;
159
+ anchor.textContent = text;
160
+ const cleanup = bindLink(router, anchor, to);
161
+ return {
162
+ element: anchor,
163
+ destroy: cleanup
164
+ };
165
+ }
166
+ export {
167
+ bindLink,
168
+ createLink,
169
+ createRouter,
170
+ matchRoute,
171
+ parseParams
172
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@constela/router",
3
+ "version": "0.1.0",
4
+ "description": "Client-side routing for Constela applications",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "dependencies": {},
18
+ "peerDependencies": {
19
+ "@constela/compiler": "^0.1.0",
20
+ "@constela/runtime": "^0.1.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^20.10.0",
24
+ "jsdom": "^25.0.0",
25
+ "tsup": "^8.0.0",
26
+ "typescript": "^5.3.0",
27
+ "vitest": "^2.0.0",
28
+ "@constela/runtime": "0.2.0",
29
+ "@constela/compiler": "0.2.0"
30
+ },
31
+ "engines": {
32
+ "node": ">=20.0.0"
33
+ },
34
+ "license": "MIT",
35
+ "scripts": {
36
+ "build": "tsup src/index.ts --format esm --dts --clean",
37
+ "type-check": "tsc --noEmit",
38
+ "test": "vitest run",
39
+ "test:watch": "vitest",
40
+ "clean": "rm -rf dist"
41
+ }
42
+ }