abret 0.1.1 → 0.1.3

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.
@@ -0,0 +1,82 @@
1
+ // @bun
2
+ import {
3
+ runWithContext
4
+ } from "./chunk-xw5b0251.js";
5
+
6
+ // src/index.ts
7
+ var wrapWithMiddleware = (handler, middlewares) => {
8
+ return (req, server) => {
9
+ return runWithContext(() => {
10
+ if (middlewares.length === 0) {
11
+ return handler(req, server);
12
+ }
13
+ let index = 0;
14
+ const next = () => {
15
+ if (index < middlewares.length) {
16
+ const middleware = middlewares[index++];
17
+ if (middleware)
18
+ return middleware(req, server, next);
19
+ }
20
+ return handler(req, server);
21
+ };
22
+ return next();
23
+ });
24
+ };
25
+ };
26
+ var wrapRouteValue = (value, middlewares) => {
27
+ if (middlewares.length === 0) {
28
+ return value;
29
+ }
30
+ if (value instanceof Response) {
31
+ return wrapWithMiddleware(() => value, middlewares);
32
+ }
33
+ if (typeof value === "function") {
34
+ return wrapWithMiddleware(value, middlewares);
35
+ }
36
+ if (typeof value === "object" && value !== null) {
37
+ const wrappedMethods = {};
38
+ for (const [method, methodHandler] of Object.entries(value)) {
39
+ if (methodHandler instanceof Response) {
40
+ wrappedMethods[method] = wrapWithMiddleware(() => methodHandler, middlewares);
41
+ } else if (typeof methodHandler === "function") {
42
+ wrappedMethods[method] = wrapWithMiddleware(methodHandler, middlewares);
43
+ }
44
+ }
45
+ return wrappedMethods;
46
+ }
47
+ return value;
48
+ };
49
+ var createRoute = (path, value, ...middlewares) => {
50
+ const wrappedValue = wrapRouteValue(value, middlewares);
51
+ return { [path]: wrappedValue };
52
+ };
53
+ var createMiddleware = (fn) => fn;
54
+ var composeMiddlewares = (...middlewares) => {
55
+ return (req, server, finalNext) => {
56
+ let index = 0;
57
+ const next = () => {
58
+ if (index < middlewares.length) {
59
+ const middleware = middlewares[index++];
60
+ if (middleware)
61
+ return middleware(req, server, next);
62
+ }
63
+ return finalNext();
64
+ };
65
+ return next();
66
+ };
67
+ };
68
+ var mergeRoutes = (...routes) => {
69
+ return Object.assign({}, ...routes);
70
+ };
71
+ var createRouteGroup = (prefix, middlewares = []) => {
72
+ return (path, value) => {
73
+ let fullPath = `/${prefix}/${path}`.replace(/\/+/g, "/");
74
+ if (fullPath.length > 1 && fullPath.endsWith("/")) {
75
+ fullPath = fullPath.slice(0, -1);
76
+ }
77
+ const normalizedPath = fullPath || "/";
78
+ return createRoute(normalizedPath, value, ...middlewares);
79
+ };
80
+ };
81
+
82
+ export { createRoute, createMiddleware, composeMiddlewares, mergeRoutes, createRouteGroup };
@@ -0,0 +1,58 @@
1
+ // @bun
2
+ // src/jsx/index.ts
3
+ class SafeString {
4
+ value;
5
+ constructor(value) {
6
+ this.value = value;
7
+ }
8
+ toString() {
9
+ return this.value;
10
+ }
11
+ }
12
+
13
+ class AsyncBuffer extends ReadableStream {
14
+ promise;
15
+ constructor(promise) {
16
+ super({
17
+ async start(controller) {
18
+ try {
19
+ const result = await promise;
20
+ controller.enqueue(new TextEncoder().encode(result.toString()));
21
+ controller.close();
22
+ } catch (e) {
23
+ controller.error(e);
24
+ }
25
+ }
26
+ });
27
+ this.promise = promise;
28
+ }
29
+ then(onfulfilled, onrejected) {
30
+ return this.promise.then(onfulfilled, onrejected);
31
+ }
32
+ catch(onrejected) {
33
+ return this.promise.catch(onrejected);
34
+ }
35
+ finally(onfinally) {
36
+ return this.promise.finally(onfinally);
37
+ }
38
+ }
39
+
40
+ class VNode {
41
+ tag;
42
+ props;
43
+ children;
44
+ constructor(tag, props, children) {
45
+ this.tag = tag;
46
+ this.props = props;
47
+ this.children = children;
48
+ }
49
+ }
50
+ var Fragment = Symbol("Fragment");
51
+ function jsx(tag, props) {
52
+ const { children, ...rest } = props || {};
53
+ return new VNode(tag, { ...rest, children }, children);
54
+ }
55
+ var jsxs = jsx;
56
+ var jsxDEV = jsx;
57
+
58
+ export { SafeString, AsyncBuffer, VNode, Fragment, jsx, jsxs, jsxDEV };
@@ -0,0 +1,80 @@
1
+ // @bun
2
+ // src/store.ts
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ var contextStore = new AsyncLocalStorage;
5
+ function createContext(name, ...args) {
6
+ const [defaultValue] = args;
7
+ const id = Symbol(name);
8
+ if (args.length > 0) {
9
+ const Provider = (props) => {
10
+ return props.children;
11
+ };
12
+ Provider._context = { id, defaultValue };
13
+ return {
14
+ id,
15
+ defaultValue,
16
+ Provider
17
+ };
18
+ }
19
+ return id;
20
+ }
21
+ function getContextId(context) {
22
+ if (typeof context === "symbol") {
23
+ return context;
24
+ }
25
+ return context.id;
26
+ }
27
+ function getDefaultValue(context) {
28
+ if (typeof context !== "symbol" && "defaultValue" in context) {
29
+ return context.defaultValue;
30
+ }
31
+ return;
32
+ }
33
+ var setContext = (context, value) => {
34
+ const store = contextStore.getStore();
35
+ if (!store) {
36
+ throw new Error("setContext must be called within a context scope. " + "Ensure you are inside a route handler or use runWithContext.");
37
+ }
38
+ store.set(getContextId(context), value);
39
+ };
40
+ function useContext(context, options) {
41
+ const store = contextStore.getStore();
42
+ const id = getContextId(context);
43
+ const value = store?.get(id);
44
+ if (value !== undefined) {
45
+ return value;
46
+ }
47
+ const defaultVal = getDefaultValue(context);
48
+ if (defaultVal !== undefined) {
49
+ return defaultVal;
50
+ }
51
+ if (options?.required) {
52
+ const name = typeof context === "symbol" ? context.description : context.id.description;
53
+ throw new Error(`Context "${name}" is required but not set`);
54
+ }
55
+ return;
56
+ }
57
+ var hasContext = (context) => {
58
+ const store = contextStore.getStore();
59
+ return store?.has(getContextId(context)) ?? false;
60
+ };
61
+ var clearContext = (context) => {
62
+ const store = contextStore.getStore();
63
+ if (store) {
64
+ store.delete(getContextId(context));
65
+ }
66
+ };
67
+ function runWithContext(fn) {
68
+ const currentStore = contextStore.getStore();
69
+ const newStore = currentStore ? new Map(currentStore) : new Map;
70
+ return contextStore.run(newStore, fn);
71
+ }
72
+ function runWithContextValue(context, value, fn) {
73
+ const currentStore = contextStore.getStore() || new Map;
74
+ const newStore = new Map(currentStore);
75
+ newStore.set(getContextId(context), value);
76
+ return contextStore.run(newStore, fn);
77
+ }
78
+ var getContextStore = () => contextStore;
79
+
80
+ export { createContext, setContext, useContext, hasContext, clearContext, runWithContext, runWithContextValue, getContextStore };
package/dist/html.js CHANGED
@@ -1,137 +1,13 @@
1
1
  // @bun
2
- // src/store.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var contextStore = new AsyncLocalStorage;
5
- function createContext(name, ...args) {
6
- const [defaultValue] = args;
7
- const id = Symbol(name);
8
- if (args.length > 0) {
9
- const Provider = (props) => {
10
- return props.children;
11
- };
12
- Provider._context = { id, defaultValue };
13
- return {
14
- id,
15
- defaultValue,
16
- Provider
17
- };
18
- }
19
- return id;
20
- }
21
- function getContextId(context) {
22
- if (typeof context === "symbol") {
23
- return context;
24
- }
25
- return context.id;
26
- }
27
- function getDefaultValue(context) {
28
- if (typeof context !== "symbol" && "defaultValue" in context) {
29
- return context.defaultValue;
30
- }
31
- return;
32
- }
33
- var setContext = (context, value) => {
34
- const store = contextStore.getStore();
35
- if (!store) {
36
- throw new Error("setContext must be called within a context scope. " + "Ensure you are inside a route handler or use runWithContext.");
37
- }
38
- store.set(getContextId(context), value);
39
- };
40
- function useContext(context, options) {
41
- const store = contextStore.getStore();
42
- const id = getContextId(context);
43
- const value = store?.get(id);
44
- if (value !== undefined) {
45
- return value;
46
- }
47
- const defaultVal = getDefaultValue(context);
48
- if (defaultVal !== undefined) {
49
- return defaultVal;
50
- }
51
- if (options?.required) {
52
- const name = typeof context === "symbol" ? context.description : context.id.description;
53
- throw new Error(`Context "${name}" is required but not set`);
54
- }
55
- return;
56
- }
57
- var hasContext = (context) => {
58
- const store = contextStore.getStore();
59
- return store?.has(getContextId(context)) ?? false;
60
- };
61
- var clearContext = (context) => {
62
- const store = contextStore.getStore();
63
- if (store) {
64
- store.delete(getContextId(context));
65
- }
66
- };
67
- function runWithContext(fn) {
68
- const currentStore = contextStore.getStore();
69
- const newStore = currentStore ? new Map(currentStore) : new Map;
70
- return contextStore.run(newStore, fn);
71
- }
72
- function runWithContextValue(context, value, fn) {
73
- const currentStore = contextStore.getStore() || new Map;
74
- const newStore = new Map(currentStore);
75
- newStore.set(getContextId(context), value);
76
- return contextStore.run(newStore, fn);
77
- }
78
- var getContextStore = () => contextStore;
79
-
80
- // src/jsx/index.ts
81
- class SafeString {
82
- value;
83
- constructor(value) {
84
- this.value = value;
85
- }
86
- toString() {
87
- return this.value;
88
- }
89
- }
90
-
91
- class AsyncBuffer extends ReadableStream {
92
- promise;
93
- constructor(promise) {
94
- super({
95
- async start(controller) {
96
- try {
97
- const result = await promise;
98
- controller.enqueue(new TextEncoder().encode(result.toString()));
99
- controller.close();
100
- } catch (e) {
101
- controller.error(e);
102
- }
103
- }
104
- });
105
- this.promise = promise;
106
- }
107
- then(onfulfilled, onrejected) {
108
- return this.promise.then(onfulfilled, onrejected);
109
- }
110
- catch(onrejected) {
111
- return this.promise.catch(onrejected);
112
- }
113
- finally(onfinally) {
114
- return this.promise.finally(onfinally);
115
- }
116
- }
117
-
118
- class VNode {
119
- tag;
120
- props;
121
- children;
122
- constructor(tag, props, children) {
123
- this.tag = tag;
124
- this.props = props;
125
- this.children = children;
126
- }
127
- }
128
- var Fragment = Symbol("Fragment");
129
- function jsx(tag, props) {
130
- const { children, ...rest } = props || {};
131
- return new VNode(tag, { ...rest, children }, children);
132
- }
133
- var jsxs = jsx;
134
- var jsxDEV = jsx;
2
+ import {
3
+ AsyncBuffer,
4
+ Fragment,
5
+ SafeString,
6
+ VNode
7
+ } from "./chunk-m9t91z6h.js";
8
+ import {
9
+ getContextStore
10
+ } from "./chunk-xw5b0251.js";
135
11
 
136
12
  // src/html.ts
137
13
  class HTMLResponse extends Response {
@@ -402,11 +278,11 @@ function render(node) {
402
278
  const providerCtx = node.tag._context;
403
279
  if (providerCtx) {
404
280
  const value = node.props.value;
405
- const contextStore2 = getContextStore();
406
- const currentStore = contextStore2.getStore() || new Map;
281
+ const contextStore = getContextStore();
282
+ const currentStore = contextStore.getStore() || new Map;
407
283
  const newStore = new Map(currentStore);
408
284
  newStore.set(providerCtx.id, value);
409
- return contextStore2.run(newStore, () => {
285
+ return contextStore.run(newStore, () => {
410
286
  return render(node.props.children);
411
287
  });
412
288
  }
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export type RouteValue<P extends string = string, S = undefined> = Bun.Serve.Bas
33
33
  * );
34
34
  * ```
35
35
  */
36
- export declare const createRoute: <P extends string, S = undefined>(path: P, value: RouteValue<P, S>, ...middlewares: Middleware<P, S>[]) => Record<P, RouteValue<P, S>>;
36
+ export declare const createRoute: <P extends `/${string}`, S = undefined>(path: P, value: RouteValue<P, S>, ...middlewares: Middleware<P, S>[]) => Record<P, RouteValue<P, S>>;
37
37
  /**
38
38
  * Helper to create a middleware function with proper typing
39
39
  *
@@ -100,4 +100,4 @@ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) exten
100
100
  * );
101
101
  * ```
102
102
  */
103
- export declare const createRouteGroup: <Prefix extends string, S = undefined>(prefix: Prefix, middlewares?: Middleware<string, S>[]) => <P extends string>(path: P, value: RouteValue<`${Prefix}${P}`, S>) => Record<`${Prefix}${P}`, RouteValue<`${Prefix}${P}`, S>>;
103
+ export declare const createRouteGroup: <Prefix extends `/${string}`, S = undefined>(prefix: Prefix, middlewares?: Middleware<string, S>[]) => <P extends `/${string}` | "">(path: P, value: RouteValue<string, S>) => Record<`/${string}`, RouteValue<`/${string}`, S>>;
package/dist/index.js CHANGED
@@ -1,153 +1,17 @@
1
1
  // @bun
2
- // src/store.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var contextStore = new AsyncLocalStorage;
5
- function createContext(name, ...args) {
6
- const [defaultValue] = args;
7
- const id = Symbol(name);
8
- if (args.length > 0) {
9
- const Provider = (props) => {
10
- return props.children;
11
- };
12
- Provider._context = { id, defaultValue };
13
- return {
14
- id,
15
- defaultValue,
16
- Provider
17
- };
18
- }
19
- return id;
20
- }
21
- function getContextId(context) {
22
- if (typeof context === "symbol") {
23
- return context;
24
- }
25
- return context.id;
26
- }
27
- function getDefaultValue(context) {
28
- if (typeof context !== "symbol" && "defaultValue" in context) {
29
- return context.defaultValue;
30
- }
31
- return;
32
- }
33
- var setContext = (context, value) => {
34
- const store = contextStore.getStore();
35
- if (!store) {
36
- throw new Error("setContext must be called within a context scope. " + "Ensure you are inside a route handler or use runWithContext.");
37
- }
38
- store.set(getContextId(context), value);
39
- };
40
- function useContext(context, options) {
41
- const store = contextStore.getStore();
42
- const id = getContextId(context);
43
- const value = store?.get(id);
44
- if (value !== undefined) {
45
- return value;
46
- }
47
- const defaultVal = getDefaultValue(context);
48
- if (defaultVal !== undefined) {
49
- return defaultVal;
50
- }
51
- if (options?.required) {
52
- const name = typeof context === "symbol" ? context.description : context.id.description;
53
- throw new Error(`Context "${name}" is required but not set`);
54
- }
55
- return;
56
- }
57
- var hasContext = (context) => {
58
- const store = contextStore.getStore();
59
- return store?.has(getContextId(context)) ?? false;
60
- };
61
- var clearContext = (context) => {
62
- const store = contextStore.getStore();
63
- if (store) {
64
- store.delete(getContextId(context));
65
- }
66
- };
67
- function runWithContext(fn) {
68
- const currentStore = contextStore.getStore();
69
- const newStore = currentStore ? new Map(currentStore) : new Map;
70
- return contextStore.run(newStore, fn);
71
- }
72
- function runWithContextValue(context, value, fn) {
73
- const currentStore = contextStore.getStore() || new Map;
74
- const newStore = new Map(currentStore);
75
- newStore.set(getContextId(context), value);
76
- return contextStore.run(newStore, fn);
77
- }
78
- var getContextStore = () => contextStore;
79
-
80
- // src/index.ts
81
- var wrapWithMiddleware = (handler, middlewares) => {
82
- return (req, server) => {
83
- return runWithContext(() => {
84
- if (middlewares.length === 0) {
85
- return handler(req, server);
86
- }
87
- let index = 0;
88
- const next = () => {
89
- if (index < middlewares.length) {
90
- const middleware = middlewares[index++];
91
- if (middleware)
92
- return middleware(req, server, next);
93
- }
94
- return handler(req, server);
95
- };
96
- return next();
97
- });
98
- };
99
- };
100
- var wrapRouteValue = (value, middlewares) => {
101
- if (middlewares.length === 0) {
102
- return value;
103
- }
104
- if (value instanceof Response) {
105
- return wrapWithMiddleware(() => value, middlewares);
106
- }
107
- if (typeof value === "function") {
108
- return wrapWithMiddleware(value, middlewares);
109
- }
110
- if (typeof value === "object" && value !== null) {
111
- const wrappedMethods = {};
112
- for (const [method, methodHandler] of Object.entries(value)) {
113
- if (methodHandler instanceof Response) {
114
- wrappedMethods[method] = wrapWithMiddleware(() => methodHandler, middlewares);
115
- } else if (typeof methodHandler === "function") {
116
- wrappedMethods[method] = wrapWithMiddleware(methodHandler, middlewares);
117
- }
118
- }
119
- return wrappedMethods;
120
- }
121
- return value;
122
- };
123
- var createRoute = (path, value, ...middlewares) => {
124
- const wrappedValue = wrapRouteValue(value, middlewares);
125
- return { [path]: wrappedValue };
126
- };
127
- var createMiddleware = (fn) => fn;
128
- var composeMiddlewares = (...middlewares) => {
129
- return (req, server, finalNext) => {
130
- let index = 0;
131
- const next = () => {
132
- if (index < middlewares.length) {
133
- const middleware = middlewares[index++];
134
- if (middleware)
135
- return middleware(req, server, next);
136
- }
137
- return finalNext();
138
- };
139
- return next();
140
- };
141
- };
142
- var mergeRoutes = (...routes) => {
143
- return Object.assign({}, ...routes);
144
- };
145
- var createRouteGroup = (prefix, middlewares = []) => {
146
- return (path, value) => {
147
- const fullPath = `${prefix}${path}`;
148
- return createRoute(fullPath, value, ...middlewares);
149
- };
150
- };
2
+ import {
3
+ composeMiddlewares,
4
+ createMiddleware,
5
+ createRoute,
6
+ createRouteGroup,
7
+ mergeRoutes
8
+ } from "./chunk-m2mdqvmd.js";
9
+ import {
10
+ createContext,
11
+ runWithContext,
12
+ runWithContextValue,
13
+ useContext
14
+ } from "./chunk-xw5b0251.js";
151
15
  export {
152
16
  useContext,
153
17
  runWithContextValue,
@@ -1,59 +1,13 @@
1
1
  // @bun
2
- // src/jsx/index.ts
3
- class SafeString {
4
- value;
5
- constructor(value) {
6
- this.value = value;
7
- }
8
- toString() {
9
- return this.value;
10
- }
11
- }
12
-
13
- class AsyncBuffer extends ReadableStream {
14
- promise;
15
- constructor(promise) {
16
- super({
17
- async start(controller) {
18
- try {
19
- const result = await promise;
20
- controller.enqueue(new TextEncoder().encode(result.toString()));
21
- controller.close();
22
- } catch (e) {
23
- controller.error(e);
24
- }
25
- }
26
- });
27
- this.promise = promise;
28
- }
29
- then(onfulfilled, onrejected) {
30
- return this.promise.then(onfulfilled, onrejected);
31
- }
32
- catch(onrejected) {
33
- return this.promise.catch(onrejected);
34
- }
35
- finally(onfinally) {
36
- return this.promise.finally(onfinally);
37
- }
38
- }
39
-
40
- class VNode {
41
- tag;
42
- props;
43
- children;
44
- constructor(tag, props, children) {
45
- this.tag = tag;
46
- this.props = props;
47
- this.children = children;
48
- }
49
- }
50
- var Fragment = Symbol("Fragment");
51
- function jsx(tag, props) {
52
- const { children, ...rest } = props || {};
53
- return new VNode(tag, { ...rest, children }, children);
54
- }
55
- var jsxs = jsx;
56
- var jsxDEV = jsx;
2
+ import {
3
+ AsyncBuffer,
4
+ Fragment,
5
+ SafeString,
6
+ VNode,
7
+ jsx,
8
+ jsxDEV,
9
+ jsxs
10
+ } from "../chunk-m9t91z6h.js";
57
11
  export {
58
12
  jsxs,
59
13
  jsxDEV,
@@ -1,59 +1,13 @@
1
1
  // @bun
2
- // src/jsx/index.ts
3
- class SafeString {
4
- value;
5
- constructor(value) {
6
- this.value = value;
7
- }
8
- toString() {
9
- return this.value;
10
- }
11
- }
12
-
13
- class AsyncBuffer extends ReadableStream {
14
- promise;
15
- constructor(promise) {
16
- super({
17
- async start(controller) {
18
- try {
19
- const result = await promise;
20
- controller.enqueue(new TextEncoder().encode(result.toString()));
21
- controller.close();
22
- } catch (e) {
23
- controller.error(e);
24
- }
25
- }
26
- });
27
- this.promise = promise;
28
- }
29
- then(onfulfilled, onrejected) {
30
- return this.promise.then(onfulfilled, onrejected);
31
- }
32
- catch(onrejected) {
33
- return this.promise.catch(onrejected);
34
- }
35
- finally(onfinally) {
36
- return this.promise.finally(onfinally);
37
- }
38
- }
39
-
40
- class VNode {
41
- tag;
42
- props;
43
- children;
44
- constructor(tag, props, children) {
45
- this.tag = tag;
46
- this.props = props;
47
- this.children = children;
48
- }
49
- }
50
- var Fragment = Symbol("Fragment");
51
- function jsx(tag, props) {
52
- const { children, ...rest } = props || {};
53
- return new VNode(tag, { ...rest, children }, children);
54
- }
55
- var jsxs = jsx;
56
- var jsxDEV = jsx;
2
+ import {
3
+ AsyncBuffer,
4
+ Fragment,
5
+ SafeString,
6
+ VNode,
7
+ jsx,
8
+ jsxDEV,
9
+ jsxs
10
+ } from "../chunk-m9t91z6h.js";
57
11
  export {
58
12
  jsxs,
59
13
  jsxDEV,
@@ -19,10 +19,6 @@ export type ServeStaticOptions = {
19
19
  * Extension (without dot) -> Mime Type
20
20
  */
21
21
  mimes?: Record<string, string>;
22
- /**
23
- * Callback when file is not found.
24
- */
25
- onNotFound?: (path: string, req: Request) => void;
26
22
  };
27
23
  /**
28
24
  * Middleware to serve static files using Bun.file
@@ -29,9 +29,6 @@ var serveStatic = (options = {}) => {
29
29
  }
30
30
  return response;
31
31
  }
32
- if (options.onNotFound) {
33
- options.onNotFound(filePath, req);
34
- }
35
32
  return next();
36
33
  };
37
34
  };
@@ -0,0 +1,21 @@
1
+ interface TranspilerOptions {
2
+ /** Directory where source files (.ts, .tsx) are located */
3
+ sourcePath: string;
4
+ /** URL prefix to intercept (e.g., "/_modules") */
5
+ staticBasePath: string;
6
+ /** Optional sub-path for vendor modules. Defaults to 'vendor' */
7
+ vendorPath?: string;
8
+ /** Optional list of modules to bundle on startup */
9
+ prewarm?: string[];
10
+ }
11
+ /**
12
+ * Transpiler middleware that handles on-the-fly TS/TSX transpilation
13
+ * and automatic npm module bundling (vendor modules).
14
+ *
15
+ * Usage:
16
+ * ```ts
17
+ * transpiler({ sourcePath: "./src", staticBasePath: "/_modules" })
18
+ * ```
19
+ */
20
+ export declare const transpiler: (options: TranspilerOptions) => import("../..").Middleware<string, undefined>;
21
+ export {};
@@ -0,0 +1,157 @@
1
+ // @bun
2
+ import {
3
+ createMiddleware
4
+ } from "../../chunk-m2mdqvmd.js";
5
+ import"../../chunk-xw5b0251.js";
6
+
7
+ // src/middleware/transpiler/index.ts
8
+ import { existsSync, mkdirSync } from "fs";
9
+ import path from "path";
10
+ var transpiler = (options) => {
11
+ const {
12
+ sourcePath,
13
+ staticBasePath,
14
+ vendorPath = "vendor",
15
+ prewarm = []
16
+ } = options;
17
+ const cacheDir = path.resolve(process.cwd(), "node_modules", ".transpiler");
18
+ const basePrefix = staticBasePath.endsWith("/") ? staticBasePath : `${staticBasePath}/`;
19
+ const vendorPrefix = `${basePrefix}${vendorPath.replace(/^\/|\/$/g, "")}/`;
20
+ if (!existsSync(cacheDir)) {
21
+ mkdirSync(cacheDir, { recursive: true });
22
+ }
23
+ async function bundleVendorModule(moduleName) {
24
+ const cacheKey = moduleName.replace(/\//g, "__");
25
+ const cachedFile = path.join(cacheDir, `${cacheKey}.js`);
26
+ if (existsSync(cachedFile))
27
+ return;
28
+ try {
29
+ const entryPoint = Bun.resolveSync(moduleName, process.cwd());
30
+ const result = await Bun.build({
31
+ entrypoints: [entryPoint],
32
+ target: "browser",
33
+ format: "esm",
34
+ minify: true,
35
+ plugins: [
36
+ {
37
+ name: "abret-external-vendor",
38
+ setup(build) {
39
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
40
+ if (args.path === moduleName)
41
+ return null;
42
+ return { path: args.path, external: true };
43
+ });
44
+ }
45
+ }
46
+ ]
47
+ });
48
+ if (!result.success || result.outputs.length === 0) {
49
+ console.error(`[Abret] Failed to bundle vendor module: ${moduleName}`, result.logs);
50
+ return;
51
+ }
52
+ const output = result.outputs[0];
53
+ if (!output)
54
+ return;
55
+ const rawContent = await output.text();
56
+ const content = rawContent.replace(/((?:import|export)\s*[\s\S]*?from\s*['"]|import\s*\(['"])([^'"]+)(['"]\)?)/g, (match, prefix, path2, suffix) => {
57
+ if (/^(https?:|(?:\/\/))/.test(path2))
58
+ return match;
59
+ if (!path2.startsWith(".") && !path2.startsWith("/")) {
60
+ return `${prefix}${basePrefix}${vendorPath.replace(/^\/|\/$/g, "")}/${path2}${suffix}`;
61
+ }
62
+ return match;
63
+ });
64
+ await Bun.write(cachedFile, content);
65
+ console.log(`[Abret] Pre-bundled: ${moduleName}`);
66
+ } catch (err) {
67
+ console.error(`[Abret] Error bundling ${moduleName}:`, err);
68
+ }
69
+ }
70
+ if (prewarm.length > 0) {
71
+ for (const moduleName of prewarm) {
72
+ bundleVendorModule(moduleName);
73
+ }
74
+ }
75
+ return createMiddleware(async (req, _server, next) => {
76
+ const url = new URL(req.url);
77
+ const pathname = url.pathname;
78
+ if (!pathname.startsWith(basePrefix) && pathname !== staticBasePath) {
79
+ return next();
80
+ }
81
+ if (pathname.startsWith(vendorPrefix)) {
82
+ const moduleName = pathname.slice(vendorPrefix.length);
83
+ const cacheKey = moduleName.replace(/\//g, "__");
84
+ const cachedFile = path.join(cacheDir, `${cacheKey}.js`);
85
+ if (existsSync(cachedFile)) {
86
+ return new Response(Bun.file(cachedFile), {
87
+ headers: {
88
+ "Content-Type": "application/javascript",
89
+ "Cache-Control": "public, max-age=31536000, immutable"
90
+ }
91
+ });
92
+ }
93
+ await bundleVendorModule(moduleName);
94
+ if (existsSync(cachedFile)) {
95
+ return new Response(Bun.file(cachedFile), {
96
+ headers: {
97
+ "Content-Type": "application/javascript",
98
+ "Cache-Control": "public, max-age=31536000, immutable"
99
+ }
100
+ });
101
+ }
102
+ return next();
103
+ }
104
+ const internalPath = pathname.slice(basePrefix.length);
105
+ const baseFileName = internalPath.endsWith(".js") ? internalPath.slice(0, -3) : internalPath;
106
+ const possibleExtensions = [".tsx", ".ts", ".jsx", ".js"];
107
+ let sourceFile = "";
108
+ for (const ext of possibleExtensions) {
109
+ const p = path.join(path.resolve(sourcePath), (baseFileName.startsWith("/") ? baseFileName.slice(1) : baseFileName) + ext);
110
+ if (existsSync(p)) {
111
+ sourceFile = p;
112
+ break;
113
+ }
114
+ }
115
+ if (sourceFile) {
116
+ try {
117
+ const buildResult = await Bun.build({
118
+ entrypoints: [sourceFile],
119
+ target: "browser",
120
+ format: "esm",
121
+ external: ["*"]
122
+ });
123
+ if (!buildResult.success || buildResult.outputs.length === 0) {
124
+ console.error(`[Abret] Build error for ${sourceFile}:`, buildResult.logs);
125
+ return next();
126
+ }
127
+ const output = buildResult.outputs[0];
128
+ if (!output) {
129
+ console.error(`[Abret] No output files generated for ${sourceFile}`);
130
+ return next();
131
+ }
132
+ const transpiledCode = await output.text();
133
+ const finalCode = transpiledCode.replace(/((?:import|export)\s*[\s\S]*?from\s*['"]|import\s*\(['"])([^'"]+)(['"]\)?)/g, (match, prefix, path2, suffix) => {
134
+ if (/^(https?:|(?:\/\/))/.test(path2))
135
+ return match;
136
+ if (!path2.startsWith(".") && !path2.startsWith("/")) {
137
+ return `${prefix}${basePrefix}${vendorPath.replace(/^\/|\/$/g, "")}/${path2}${suffix}`;
138
+ }
139
+ if (path2.startsWith(".") && !path2.split("/").pop()?.includes(".")) {
140
+ return `${prefix}${path2}.js${suffix}`;
141
+ }
142
+ return match;
143
+ });
144
+ return new Response(finalCode, {
145
+ headers: { "Content-Type": "application/javascript" }
146
+ });
147
+ } catch (err) {
148
+ console.error(`[Abret] Transpilation error for ${sourceFile}:`, err);
149
+ return next();
150
+ }
151
+ }
152
+ return next();
153
+ });
154
+ };
155
+ export {
156
+ transpiler
157
+ };
package/dist/store.js CHANGED
@@ -1,81 +1,14 @@
1
1
  // @bun
2
- // src/store.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var contextStore = new AsyncLocalStorage;
5
- function createContext(name, ...args) {
6
- const [defaultValue] = args;
7
- const id = Symbol(name);
8
- if (args.length > 0) {
9
- const Provider = (props) => {
10
- return props.children;
11
- };
12
- Provider._context = { id, defaultValue };
13
- return {
14
- id,
15
- defaultValue,
16
- Provider
17
- };
18
- }
19
- return id;
20
- }
21
- function getContextId(context) {
22
- if (typeof context === "symbol") {
23
- return context;
24
- }
25
- return context.id;
26
- }
27
- function getDefaultValue(context) {
28
- if (typeof context !== "symbol" && "defaultValue" in context) {
29
- return context.defaultValue;
30
- }
31
- return;
32
- }
33
- var setContext = (context, value) => {
34
- const store = contextStore.getStore();
35
- if (!store) {
36
- throw new Error("setContext must be called within a context scope. " + "Ensure you are inside a route handler or use runWithContext.");
37
- }
38
- store.set(getContextId(context), value);
39
- };
40
- function useContext(context, options) {
41
- const store = contextStore.getStore();
42
- const id = getContextId(context);
43
- const value = store?.get(id);
44
- if (value !== undefined) {
45
- return value;
46
- }
47
- const defaultVal = getDefaultValue(context);
48
- if (defaultVal !== undefined) {
49
- return defaultVal;
50
- }
51
- if (options?.required) {
52
- const name = typeof context === "symbol" ? context.description : context.id.description;
53
- throw new Error(`Context "${name}" is required but not set`);
54
- }
55
- return;
56
- }
57
- var hasContext = (context) => {
58
- const store = contextStore.getStore();
59
- return store?.has(getContextId(context)) ?? false;
60
- };
61
- var clearContext = (context) => {
62
- const store = contextStore.getStore();
63
- if (store) {
64
- store.delete(getContextId(context));
65
- }
66
- };
67
- function runWithContext(fn) {
68
- const currentStore = contextStore.getStore();
69
- const newStore = currentStore ? new Map(currentStore) : new Map;
70
- return contextStore.run(newStore, fn);
71
- }
72
- function runWithContextValue(context, value, fn) {
73
- const currentStore = contextStore.getStore() || new Map;
74
- const newStore = new Map(currentStore);
75
- newStore.set(getContextId(context), value);
76
- return contextStore.run(newStore, fn);
77
- }
78
- var getContextStore = () => contextStore;
2
+ import {
3
+ clearContext,
4
+ createContext,
5
+ getContextStore,
6
+ hasContext,
7
+ runWithContext,
8
+ runWithContextValue,
9
+ setContext,
10
+ useContext
11
+ } from "./chunk-xw5b0251.js";
79
12
  export {
80
13
  useContext,
81
14
  setContext,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "abret",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Fast, type-safe web framework for Bun with built-in JSX and middleware support.",
5
5
  "license": "MIT",
6
6
  "author": "Arisris",
@@ -52,6 +52,10 @@
52
52
  "./middleware/static": {
53
53
  "types": "./dist/middleware/static/index.d.ts",
54
54
  "import": "./dist/middleware/static/index.js"
55
+ },
56
+ "./middleware/transpiler": {
57
+ "types": "./dist/middleware/transpiler/index.d.ts",
58
+ "import": "./dist/middleware/transpiler/index.js"
55
59
  }
56
60
  },
57
61
  "scripts": {
@@ -63,7 +67,9 @@
63
67
  },
64
68
  "devDependencies": {
65
69
  "@biomejs/biome": "2.3.12",
70
+ "@preact/signals": "^2.6.2",
66
71
  "@types/bun": "latest",
72
+ "preact": "^10.28.3",
67
73
  "typescript": "^5"
68
74
  }
69
75
  }