attay 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Harshdeep Singh Hura
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 ADDED
@@ -0,0 +1,190 @@
1
+ # Attay (ਅਤੈ / and)
2
+
3
+ Attay is intentionally personal.
4
+
5
+ It exists because I got tired of bending code around other people’s opinions. Instead, Attay codifies a workflow that already works well and makes it reusable.
6
+
7
+ Attay is meant to sit **next to your code**, not above it. It’s _`and`_, not `instead of`.
8
+
9
+ ## What Attay Is
10
+
11
+ Attay is a small, opinionated toolkit built around:
12
+
13
+ - **Bun** on the server
14
+ - **Preact** on the client
15
+ - Filesystem-driven routing
16
+ - Minimal configuration
17
+ - Explicit control over runtime behavior
18
+
19
+ It favors:
20
+
21
+ - Composition over magic
22
+ - Plain platform primitives over wrappers
23
+ - Code you can read in one sitting
24
+
25
+ ## What Attay Is Not
26
+
27
+ - It is not a "universal" framework
28
+ - It is not designed to please every use case
29
+ - It does not attempt to abstract away the platform
30
+ - It does not follow whatever is popular this year
31
+
32
+ ---
33
+
34
+ ## Server
35
+
36
+ The server side of Attay is a **route calculator** for Bun.
37
+
38
+ You define routes using a filesystem structure. Attay converts that structure into a `routes` object that Bun understands. You still own:
39
+
40
+ - `Bun.serve`
41
+ - request handling
42
+ - server lifecycle
43
+
44
+ Attay simply removes the boring glue.
45
+
46
+ ```js
47
+ import attayRoutes from "attay/server";
48
+
49
+ const autoRoutes = await attayRoutes({ dir: "./api", prefix: "/pre" });
50
+ const server = Bun.serve({
51
+ routes: {
52
+ ...autoRoutes,
53
+ },
54
+ });
55
+ ```
56
+
57
+ You can mix calculated routes and manual routes freely.
58
+
59
+ ### Route Prefix
60
+
61
+ Attay supports an optional `prefix` option that is prepended to **every calculated API route**.
62
+
63
+ This is useful when you want to mount your API under a specific base path without changing your filesystem structure.
64
+
65
+ ```js
66
+ await attayRoutes({ dir: "./api" });
67
+ ```
68
+
69
+ ```
70
+ api/GET.ts -> /
71
+ api/users/GET.ts -> /users
72
+ ```
73
+
74
+ ```js
75
+ await attayRoutes({ dir: "./api", prefix: "/pre" });
76
+ ```
77
+
78
+ ```
79
+ api/GET.ts -> /pre/
80
+ api/users/GET.ts -> /pre/users
81
+ ```
82
+
83
+ The prefix:
84
+
85
+ - Defaults to empty (`""`)
86
+ - Is normalized automatically (leading slash added, trailing slash removed)
87
+ - Applies only to API routes (client routes are not prefixed)
88
+
89
+ ### Middleware
90
+
91
+ Attay provides a small middleware helper for the server: `withMiddleware`.
92
+
93
+ Middleware exists to share logic across routes without inventing a new request lifecycle. It is deliberately minimal.
94
+
95
+ ```js
96
+ import { withMiddleware } from "attay/server";
97
+ import logMethodMiddleware from "@/middleware/logMethodMiddleware";
98
+
99
+ /**
100
+ * @param {Request} request
101
+ */
102
+ async function handler(request) {
103
+ return new Response(
104
+ JSON.stringify({ message: "Hello from GET /api/example" }),
105
+ { headers: { "Content-Type": "application/json" } }
106
+ );
107
+ }
108
+
109
+ export default withMiddleware(logMethodMiddleware, handler);
110
+ ```
111
+
112
+ Each middleware function may:
113
+
114
+ - Return a `Response` to stop execution
115
+ - Return a new `Request` to continue with a modified request
116
+ - Return nothing to pass the request through unchanged
117
+
118
+ The final handler **must** return a `Response`.
119
+
120
+ ---
121
+
122
+ ## Client
123
+
124
+ The client side of Attay provides a file-based router for **Preact**, built on `preact-iso`.
125
+
126
+ Pages are discovered using Vite’s `import.meta.glob`, lazy-loaded, and mapped to routes using simple conventions.
127
+
128
+ ```jsx
129
+ import { render } from "preact";
130
+ import { LocationProvider } from "preact-iso";
131
+ import RouterView from "attay/client";
132
+
133
+ render(
134
+ <LocationProvider>
135
+ <RouterView />
136
+ </LocationProvider>,
137
+ document.getElementById("app")!
138
+ );
139
+ ```
140
+
141
+ By default, pages live in `src/pages`, but you can fully control discovery by passing your own glob map.
142
+
143
+ #### Custom pages directory
144
+
145
+ If you don’t want to use `src/pages`, you can pass your own Vite glob map to `RouterView`.
146
+
147
+ ```jsx
148
+ import { render } from "preact";
149
+ import { LocationProvider } from "preact-iso";
150
+ import RouterView from "attay/client";
151
+
152
+ const pages = import.meta.glob("/src/features/blog/pages/**/!(_)*.{tsx,jsx}");
153
+
154
+ render(
155
+ <LocationProvider>
156
+ <RouterView pages={pages} />
157
+ </LocationProvider>,
158
+ document.getElementById("app")!
159
+ );
160
+ ```
161
+
162
+ This keeps page discovery fully static and bundler-friendly, while letting you organize your app however you want.
163
+
164
+ ### useRouter()
165
+
166
+ `useRouter()` is a small convenience hook built on top of `preact-iso`.
167
+
168
+ It exposes the current routing state and a simple navigation helper without hiding how routing actually works.
169
+
170
+ ```js
171
+ import { useRouter } from "attay/client";
172
+
173
+ export default function UserPage() {
174
+ const { params, query, push } = useRouter();
175
+
176
+ return (
177
+ <div>
178
+ <p>User ID: {params.id}</p>
179
+ <button onClick={() => push("/?from=user")}>Go home</button>
180
+ </div>
181
+ );
182
+ }
183
+ ```
184
+
185
+ What it gives you:
186
+
187
+ - `params` — dynamic route parameters
188
+ - `query` — parsed query string values
189
+ - `push(url, replace?)` — programmatic navigation
190
+ - `currentPath` and `url` for introspection
@@ -0,0 +1,28 @@
1
+ import { ComponentType, JSX } from 'preact';
2
+
3
+ type AnyComponent = ComponentType<any>;
4
+ type PageModule = {
5
+ default: AnyComponent;
6
+ } & Record<string, unknown>;
7
+ type Loader = () => Promise<PageModule>;
8
+ type PagesGlob = Record<string, Loader>;
9
+ interface RouterViewProps {
10
+ pages?: PagesGlob;
11
+ }
12
+ declare function RouterView({ pages }: RouterViewProps): JSX.Element;
13
+
14
+ interface RouterLike {
15
+ push: (url: string, replace?: boolean) => void;
16
+ query: Record<string, string>;
17
+ params: Record<string, string>;
18
+ currentPath: string;
19
+ url: string;
20
+ }
21
+ /**
22
+ * Router hook backed by preact-iso.
23
+ *
24
+ * @returns {RouterLike}
25
+ */
26
+ declare function useRouter(): RouterLike;
27
+
28
+ export { type PagesGlob, type RouterLike, RouterView, type RouterViewProps, RouterView as default, useRouter };
@@ -0,0 +1,60 @@
1
+ // src/client/RouterView.tsx
2
+ import { ErrorBoundary, Router, Route, lazy } from "preact-iso";
3
+ import { jsx, jsxs } from "preact/jsx-runtime";
4
+ var DEFAULT_PAGES = import.meta.glob(
5
+ "/src/pages/**/!(_)*.{tsx,jsx}"
6
+ );
7
+ function pathToIsoPattern(key) {
8
+ let routePath = key.replace(/^\.\.\/pages/, "").replace(/\.(t|j)sx$/, "");
9
+ if (routePath.endsWith("/index")) {
10
+ routePath = routePath.replace(/\/index$/, "") || "/";
11
+ }
12
+ routePath = routePath.replace(/\[\.\.\.([^/\]]+)\]/g, ":$1*");
13
+ routePath = routePath.replace(/\[([^/\]]+)\]/g, ":$1");
14
+ return routePath;
15
+ }
16
+ function toLazyModule(loader) {
17
+ return async () => {
18
+ const mod = await loader();
19
+ return { default: mod.default };
20
+ };
21
+ }
22
+ function RouterView({ pages = DEFAULT_PAGES }) {
23
+ const entries = Object.entries(pages).filter(
24
+ ([key]) => !key.includes("/pages/api/")
25
+ );
26
+ const notFoundEntry = entries.find(([key]) => /\/404\.(t|j)sx$/.test(key));
27
+ const routes = entries.filter(([key]) => !/\/404\.(t|j)sx$/.test(key)).map(([key, loader]) => {
28
+ const path = pathToIsoPattern(key);
29
+ const Component = lazy(toLazyModule(loader));
30
+ return /* @__PURE__ */ jsx(Route, { path, component: Component }, key);
31
+ });
32
+ const NotFound = notFoundEntry ? lazy(toLazyModule(notFoundEntry[1])) : function NotFoundFallback() {
33
+ return /* @__PURE__ */ jsx("p", { children: "no route found" });
34
+ };
35
+ return /* @__PURE__ */ jsx(ErrorBoundary, { children: /* @__PURE__ */ jsxs(Router, { children: [
36
+ routes,
37
+ /* @__PURE__ */ jsx(Route, { default: true, component: NotFound })
38
+ ] }) });
39
+ }
40
+ var RouterView_default = RouterView;
41
+
42
+ // src/client/router.tsx
43
+ import { useLocation, useRoute } from "preact-iso";
44
+ function useRouter() {
45
+ const location = useLocation();
46
+ const route = useRoute();
47
+ return {
48
+ push: (url, replace) => location.route(url, replace),
49
+ query: route.query,
50
+ params: route.params,
51
+ currentPath: route.path,
52
+ url: location.url
53
+ };
54
+ }
55
+ export {
56
+ RouterView_default as RouterView,
57
+ RouterView_default as default,
58
+ useRouter
59
+ };
60
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/RouterView.tsx","../../src/client/router.tsx"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport { ErrorBoundary, Router, Route, lazy } from \"preact-iso\";\nimport type { ComponentType, JSX } from \"preact\";\n\ntype AnyComponent = ComponentType<any>;\n\ntype PageModule = { default: AnyComponent } & Record<string, unknown>;\n\ntype Loader = () => Promise<PageModule>;\n\nexport type PagesGlob = Record<string, Loader>;\n\nexport interface RouterViewProps {\n pages?: PagesGlob;\n}\n\nconst DEFAULT_PAGES = import.meta.glob(\n \"/src/pages/**/!(_)*.{tsx,jsx}\",\n) as PagesGlob;\n\nfunction pathToIsoPattern(key: string): string {\n let routePath = key.replace(/^\\.\\.\\/pages/, \"\").replace(/\\.(t|j)sx$/, \"\");\n\n if (routePath.endsWith(\"/index\")) {\n routePath = routePath.replace(/\\/index$/, \"\") || \"/\";\n }\n\n routePath = routePath.replace(/\\[\\.\\.\\.([^/\\]]+)\\]/g, \":$1*\");\n routePath = routePath.replace(/\\[([^/\\]]+)\\]/g, \":$1\");\n\n return routePath;\n}\n\nfunction toLazyModule(loader: Loader): () => Promise<{ default: AnyComponent }> {\n return async () => {\n const mod = await loader();\n return { default: mod.default };\n };\n}\n\nfunction RouterView({ pages = DEFAULT_PAGES }: RouterViewProps): JSX.Element {\n const entries = Object.entries(pages).filter(\n ([key]) => !key.includes(\"/pages/api/\"),\n );\n\n const notFoundEntry = entries.find(([key]) => /\\/404\\.(t|j)sx$/.test(key));\n\n const routes = entries\n .filter(([key]) => !/\\/404\\.(t|j)sx$/.test(key))\n .map(([key, loader]) => {\n const path = pathToIsoPattern(key);\n const Component = lazy(toLazyModule(loader));\n return <Route key={key} path={path} component={Component} />;\n });\n\n const NotFound = notFoundEntry\n ? lazy(toLazyModule(notFoundEntry[1]))\n : function NotFoundFallback() {\n return <p>no route found</p>;\n };\n\n return (\n <ErrorBoundary>\n <Router>\n {routes}\n <Route default component={NotFound} />\n </Router>\n </ErrorBoundary>\n );\n}\n\nexport default RouterView;\n","import { useLocation, useRoute } from \"preact-iso\";\n\nexport interface RouterLike {\n push: (url: string, replace?: boolean) => void;\n query: Record<string, string>;\n params: Record<string, string>;\n currentPath: string;\n url: string;\n}\n\n/**\n * Router hook backed by preact-iso.\n *\n * @returns {RouterLike}\n */\nexport function useRouter(): RouterLike {\n const location = useLocation();\n const route = useRoute();\n\n return {\n push: (url, replace) => location.route(url, replace),\n query: route.query,\n params: route.params,\n currentPath: route.path,\n url: location.url,\n };\n}\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E;AAAA;AAAA,IACD,oBAAC,SAAM,SAAO,MAAC,WAAW,UAAU;AAAA,KACtC,GACF;AAEJ;AAEA,IAAO,qBAAQ;;;ACvEf,SAAS,aAAa,gBAAgB;AAe/B,SAAS,YAAwB;AACtC,QAAM,WAAW,YAAY;AAC7B,QAAM,QAAQ,SAAS;AAEvB,SAAO;AAAA,IACL,MAAM,CAAC,KAAK,YAAY,SAAS,MAAM,KAAK,OAAO;AAAA,IACnD,OAAO,MAAM;AAAA,IACb,QAAQ,MAAM;AAAA,IACd,aAAa,MAAM;AAAA,IACnB,KAAK,SAAS;AAAA,EAChB;AACF;","names":[]}
@@ -0,0 +1,30 @@
1
+ type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
2
+ type RouteHandler = (req: Request) => Response | Promise<Response>;
3
+ type MiddlewareResult = Response | Request | void;
4
+ type Middleware = (req: Request) => MiddlewareResult | Promise<MiddlewareResult>;
5
+ type MethodHandlers = Partial<Record<HttpMethod, RouteHandler>>;
6
+ type BunRouteValue = Response | ReturnType<typeof Bun.file> | RouteHandler | MethodHandlers;
7
+ type BunRoutes = Record<string, BunRouteValue>;
8
+ interface AttayRoutesOptions {
9
+ /** Directory that contains your API route files. Defaults to `${process.cwd()}/api`. */
10
+ dir?: string;
11
+ /** Vite build output directory (usually `./client/dist`). If provided, Attay serves assets + SPA fallback. */
12
+ client?: string;
13
+ }
14
+ /**
15
+ * Wrap a final route handler with one or more middleware functions.
16
+ *
17
+ * Each middleware can:
18
+ * - return a Response to end the chain
19
+ * - return a Request to continue with a modified request
20
+ * - return void to pass the current request through
21
+ */
22
+ declare function withMiddleware(...fns: [...Middleware[], RouteHandler]): RouteHandler;
23
+ /**
24
+ * Create a Bun `routes` table by scanning an API directory and (optionally) wiring up
25
+ * Vite client static assets + SPA fallback.
26
+ */
27
+ declare function attayRoutes(options?: AttayRoutesOptions): Promise<BunRoutes>;
28
+ declare const attayRoutesAsync: typeof attayRoutes;
29
+
30
+ export { type AttayRoutesOptions, type BunRouteValue, type BunRoutes, type HttpMethod, type MethodHandlers, type Middleware, type MiddlewareResult, type RouteHandler, attayRoutesAsync, attayRoutes as default, withMiddleware };
@@ -0,0 +1,139 @@
1
+ // src/server/index.ts
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ import { pathToFileURL } from "url";
5
+ function withMiddleware(...fns) {
6
+ return async (req) => {
7
+ let current = req;
8
+ for (let i = 0; i < fns.length - 1; i++) {
9
+ const r = await fns[i](current);
10
+ if (r instanceof Response) return r;
11
+ if (r instanceof Request) current = r;
12
+ }
13
+ const final = await fns[fns.length - 1](current);
14
+ if (!(final instanceof Response)) {
15
+ throw new Error("Final handler must return Response");
16
+ }
17
+ return final;
18
+ };
19
+ }
20
+ var MIME_TYPES = {
21
+ ".html": "text/html; charset=utf-8",
22
+ ".js": "text/javascript; charset=utf-8",
23
+ ".mjs": "text/javascript; charset=utf-8",
24
+ ".css": "text/css; charset=utf-8",
25
+ ".json": "application/json; charset=utf-8",
26
+ ".png": "image/png",
27
+ ".jpg": "image/jpeg",
28
+ ".jpeg": "image/jpeg",
29
+ ".gif": "image/gif",
30
+ ".svg": "image/svg+xml",
31
+ ".ico": "image/x-icon",
32
+ ".woff": "font/woff",
33
+ ".woff2": "font/woff2",
34
+ ".ttf": "font/ttf"
35
+ };
36
+ function isHttpMethod(x) {
37
+ return x === "GET" || x === "POST" || x === "PUT" || x === "DELETE" || x === "PATCH";
38
+ }
39
+ function normalizeRouteSegment(seg) {
40
+ const m1 = seg.match(/^\[([^\]/]+)\]$/);
41
+ if (m1) return `:${m1[1]}`;
42
+ const m2 = seg.match(/^\[\.\.\.([^\]/]+)\]$/);
43
+ if (m2) return "*";
44
+ return seg;
45
+ }
46
+ function toRoutePath(routeBase) {
47
+ const clean = routeBase.replace(/^\/+/, "").replace(/\/+$/, "");
48
+ if (!clean) return "/";
49
+ const parts = clean.split("/").filter(Boolean).map(normalizeRouteSegment);
50
+ return "/" + parts.join("/");
51
+ }
52
+ async function fileExists(filePath) {
53
+ try {
54
+ const stat = await fs.stat(filePath);
55
+ return stat.isFile();
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ function contentTypeFor(filePath) {
61
+ const ext = path.extname(filePath);
62
+ return MIME_TYPES[ext] || "application/octet-stream";
63
+ }
64
+ async function attayRoutes(options = {}) {
65
+ const routes = {};
66
+ const dir = options.dir ? path.isAbsolute(options.dir) ? options.dir : path.join(process.cwd(), options.dir) : path.join(process.cwd(), "api");
67
+ const clientDir = options.client ? path.isAbsolute(options.client) ? options.client : path.join(process.cwd(), options.client) : null;
68
+ async function registerApi(dirPath, routeBase = "") {
69
+ let entries;
70
+ try {
71
+ entries = await fs.readdir(dirPath, { withFileTypes: true });
72
+ } catch {
73
+ return;
74
+ }
75
+ for (const entry of entries) {
76
+ const entryPath = path.join(dirPath, entry.name);
77
+ if (entry.isDirectory()) {
78
+ await registerApi(entryPath, routeBase + "/" + entry.name);
79
+ continue;
80
+ }
81
+ if (!/\.(ts|js)$/.test(entry.name)) continue;
82
+ if (entry.name.startsWith("_")) continue;
83
+ const name = path.basename(entry.name).replace(/\.(ts|js)$/, "");
84
+ const upper = name.toUpperCase();
85
+ if (!isHttpMethod(upper)) continue;
86
+ const mod = await import(pathToFileURL(entryPath).href);
87
+ const handler = mod?.default;
88
+ if (typeof handler !== "function") continue;
89
+ const routePath = toRoutePath(routeBase);
90
+ const existing = routes[routePath];
91
+ if (existing && typeof existing === "object" && !(existing instanceof Response)) {
92
+ const asMethods = existing;
93
+ if ("GET" in asMethods || "POST" in asMethods || "PUT" in asMethods || "DELETE" in asMethods || "PATCH" in asMethods) {
94
+ asMethods[upper] = handler;
95
+ routes[routePath] = asMethods;
96
+ continue;
97
+ }
98
+ }
99
+ routes[routePath] = { [upper]: handler };
100
+ }
101
+ }
102
+ await registerApi(dir);
103
+ if (clientDir) {
104
+ const indexHtmlPath = path.join(clientDir, "index.html");
105
+ const serveClient = async (req) => {
106
+ const url = new URL(req.url);
107
+ const pathname = url.pathname;
108
+ const method = req.method.toUpperCase();
109
+ if (method !== "GET" && method !== "HEAD") {
110
+ return new Response("Not found", { status: 404 });
111
+ }
112
+ const safePath = pathname.replace(/^\/+/, "");
113
+ const filePath = safePath === "" ? indexHtmlPath : path.join(clientDir, safePath);
114
+ if (await fileExists(filePath)) {
115
+ const file = Bun.file(filePath);
116
+ return new Response(file, {
117
+ headers: {
118
+ "Content-Type": contentTypeFor(filePath)
119
+ }
120
+ });
121
+ }
122
+ const indexFile = Bun.file(indexHtmlPath);
123
+ return new Response(indexFile, {
124
+ headers: {
125
+ "Content-Type": "text/html; charset=utf-8"
126
+ }
127
+ });
128
+ };
129
+ routes["/*"] = serveClient;
130
+ }
131
+ return routes;
132
+ }
133
+ var attayRoutesAsync = attayRoutes;
134
+ export {
135
+ attayRoutesAsync,
136
+ attayRoutes as default,
137
+ withMiddleware
138
+ };
139
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/index.ts"],"sourcesContent":["import fs from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\nexport type RouteHandler = (req: Request) => Response | Promise<Response>;\n\nexport type MiddlewareResult = Response | Request | void;\nexport type Middleware = (\n req: Request\n) => MiddlewareResult | Promise<MiddlewareResult>;\n\nexport type MethodHandlers = Partial<Record<HttpMethod, RouteHandler>>;\n\n// Bun's `routes` accepts values like Response, Bun.file(), handler functions, or per-method handlers.\n// We keep this intentionally broad so Attay can return what Bun expects.\nexport type BunRouteValue =\n | Response\n | ReturnType<typeof Bun.file>\n | RouteHandler\n | MethodHandlers;\nexport type BunRoutes = Record<string, BunRouteValue>;\n\nexport interface AttayRoutesOptions {\n /** Directory that contains your API route files. Defaults to `${process.cwd()}/api`. */\n dir?: string;\n /** Vite build output directory (usually `./client/dist`). If provided, Attay serves assets + SPA fallback. */\n client?: string;\n}\n\n/**\n * Wrap a final route handler with one or more middleware functions.\n *\n * Each middleware can:\n * - return a Response to end the chain\n * - return a Request to continue with a modified request\n * - return void to pass the current request through\n */\nexport function withMiddleware(\n ...fns: [...Middleware[], RouteHandler]\n): RouteHandler {\n return async (req: Request) => {\n let current: Request = req;\n\n for (let i = 0; i < fns.length - 1; i++) {\n const r = await fns[i](current);\n if (r instanceof Response) return r;\n if (r instanceof Request) current = r;\n }\n\n const final = await fns[fns.length - 1](current);\n if (!(final instanceof Response)) {\n throw new Error(\"Final handler must return Response\");\n }\n return final;\n };\n}\n\n/** Very small mime map for common frontend assets. */\nconst MIME_TYPES: Record<string, string> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n};\n\nfunction isHttpMethod(x: string): x is HttpMethod {\n return (\n x === \"GET\" ||\n x === \"POST\" ||\n x === \"PUT\" ||\n x === \"DELETE\" ||\n x === \"PATCH\"\n );\n}\n\nfunction normalizeRouteSegment(seg: string): string {\n // [id] -> :id\n const m1 = seg.match(/^\\[([^\\]/]+)\\]$/);\n if (m1) return `:${m1[1]}`;\n\n // [...slug] -> * (Bun wildcard)\n const m2 = seg.match(/^\\[\\.\\.\\.([^\\]/]+)\\]$/);\n if (m2) return \"*\";\n\n return seg;\n}\n\nfunction toRoutePath(routeBase: string): string {\n // routeBase comes in like \"\" or \"/users/[id]\"\n const clean = routeBase.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (!clean) return \"/\";\n\n const parts = clean.split(\"/\").filter(Boolean).map(normalizeRouteSegment);\n\n return \"/\" + parts.join(\"/\");\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(filePath);\n return stat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction contentTypeFor(filePath: string): string {\n const ext = path.extname(filePath);\n return MIME_TYPES[ext] || \"application/octet-stream\";\n}\n\n/**\n * Create a Bun `routes` table by scanning an API directory and (optionally) wiring up\n * Vite client static assets + SPA fallback.\n */\nexport default async function attayRoutes(\n options: AttayRoutesOptions = {}\n): Promise<BunRoutes> {\n const routes: BunRoutes = {};\n\n const dir = options.dir\n ? path.isAbsolute(options.dir)\n ? options.dir\n : path.join(process.cwd(), options.dir)\n : path.join(process.cwd(), \"api\");\n\n const clientDir = options.client\n ? path.isAbsolute(options.client)\n ? options.client\n : path.join(process.cwd(), options.client)\n : null;\n\n async function registerApi(dirPath: string, routeBase = \"\"): Promise<void> {\n let entries: Array<import(\"fs\").Dirent>;\n try {\n entries = await fs.readdir(dirPath, { withFileTypes: true });\n } catch {\n // dir may not exist; that's ok\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await registerApi(entryPath, routeBase + \"/\" + entry.name);\n continue;\n }\n\n if (!/\\.(ts|js)$/.test(entry.name)) continue;\n if (entry.name.startsWith(\"_\")) continue;\n\n const name = path.basename(entry.name).replace(/\\.(ts|js)$/, \"\");\n const upper = name.toUpperCase();\n if (!isHttpMethod(upper)) continue;\n\n const mod = await import(pathToFileURL(entryPath).href);\n const handler = mod?.default;\n if (typeof handler !== \"function\") continue;\n\n const routePath = toRoutePath(routeBase);\n\n const existing = routes[routePath];\n if (\n existing &&\n typeof existing === \"object\" &&\n !(existing instanceof Response)\n ) {\n const asMethods = existing as MethodHandlers;\n if (\n \"GET\" in asMethods ||\n \"POST\" in asMethods ||\n \"PUT\" in asMethods ||\n \"DELETE\" in asMethods ||\n \"PATCH\" in asMethods\n ) {\n asMethods[upper] = handler as RouteHandler;\n routes[routePath] = asMethods;\n continue;\n }\n }\n\n routes[routePath] = { [upper]: handler as RouteHandler };\n }\n }\n\n await registerApi(dir);\n\n if (clientDir) {\n const indexHtmlPath = path.join(clientDir, \"index.html\");\n\n const serveClient: RouteHandler = async (req: Request) => {\n const url = new URL(req.url);\n const pathname = url.pathname;\n const method = req.method.toUpperCase();\n\n if (method !== \"GET\" && method !== \"HEAD\") {\n return new Response(\"Not found\", { status: 404 });\n }\n\n const safePath = pathname.replace(/^\\/+/, \"\");\n const filePath =\n safePath === \"\" ? indexHtmlPath : path.join(clientDir, safePath);\n\n if (await fileExists(filePath)) {\n const file = Bun.file(filePath);\n return new Response(file, {\n headers: {\n \"Content-Type\": contentTypeFor(filePath),\n },\n });\n }\n\n const indexFile = Bun.file(indexHtmlPath);\n return new Response(indexFile, {\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n },\n });\n };\n\n routes[\"/*\"] = serveClient;\n }\n\n return routes;\n}\n\nexport const attayRoutesAsync = attayRoutes;\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAqCvB,SAAS,kBACX,KACW;AACd,SAAO,OAAO,QAAiB;AAC7B,QAAI,UAAmB;AAEvB,aAAS,IAAI,GAAG,IAAI,IAAI,SAAS,GAAG,KAAK;AACvC,YAAM,IAAI,MAAM,IAAI,CAAC,EAAE,OAAO;AAC9B,UAAI,aAAa,SAAU,QAAO;AAClC,UAAI,aAAa,QAAS,WAAU;AAAA,IACtC;AAEA,UAAM,QAAQ,MAAM,IAAI,IAAI,SAAS,CAAC,EAAE,OAAO;AAC/C,QAAI,EAAE,iBAAiB,WAAW;AAChC,YAAM,IAAI,MAAM,oCAAoC;AAAA,IACtD;AACA,WAAO;AAAA,EACT;AACF;AAGA,IAAM,aAAqC;AAAA,EACzC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ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AAG;AAC3B,YAAM,WAAW,IAAI;AACrB,YAAM,SAAS,IAAI,OAAO,YAAY;AAEtC,UAAI,WAAW,SAAS,WAAW,QAAQ;AACzC,eAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAAA,MAClD;AAEA,YAAM,WAAW,SAAS,QAAQ,QAAQ,EAAE;AAC5C,YAAM,WACJ,aAAa,KAAK,gBAAgB,KAAK,KAAK,WAAW,QAAQ;AAEjE,UAAI,MAAM,WAAW,QAAQ,GAAG;AAC9B,cAAM,OAAO,IAAI,KAAK,QAAQ;AAC9B,eAAO,IAAI,SAAS,MAAM;AAAA,UACxB,SAAS;AAAA,YACP,gBAAgB,eAAe,QAAQ;AAAA,UACzC;AAAA,QACF,CAAC;AAAA,MACH;AAEA,YAAM,YAAY,IAAI,KAAK,aAAa;AACxC,aAAO,IAAI,SAAS,WAAW;AAAA,QAC7B,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO,IAAI,IAAI;AAAA,EACjB;AAEA,SAAO;AACT;AAEO,IAAM,mBAAmB;","names":[]}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "attay",
3
+ "version": "0.0.1",
4
+ "description": "Helper utilities for Preact and Bun",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "author": {
8
+ "name": "Harshdeep Singh Hura",
9
+ "url": "https://harshdeephura.com"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/kinngh/attay/issues"
13
+ },
14
+ "homepage": "https://github.com/kinngh/attay#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/kinngh/attay.git"
18
+ },
19
+ "exports": {
20
+ "./client": {
21
+ "types": "./dist/client/index.d.ts",
22
+ "import": "./dist/client/index.js"
23
+ },
24
+ "./server": {
25
+ "types": "./dist/server/index.d.ts",
26
+ "import": "./dist/server/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "peerDependencies": {
33
+ "preact": "^10.0.0",
34
+ "preact-iso": "^2.0.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/bun": "^1.3.5",
38
+ "@types/node": "^25.0.3",
39
+ "preact": "^10.0.0",
40
+ "preact-iso": "^2.0.0",
41
+ "prettier": "^3.7.4",
42
+ "tsup": "^8.5.1",
43
+ "typescript": "^5.0.0",
44
+ "vite": "^7.3.0"
45
+ },
46
+ "scripts": {
47
+ "clean": "bun -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
48
+ "typecheck": "tsc --noEmit",
49
+ "build": "bun run clean; bun run typecheck; tsup",
50
+ "pretty": "prettier --write ./"
51
+ }
52
+ }