@mauroandre/velojs 0.0.21 → 0.0.23

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/dist/server.js CHANGED
@@ -1,55 +1,55 @@
1
1
  import { jsx as _ } from "preact/jsx-runtime";
2
- import { Hono as T } from "hono";
3
- import { logger as b } from "hono/logger";
4
- import { trimTrailingSlash as A } from "hono/trailing-slash";
5
- import { render as R } from "preact-render-to-string";
6
- import { Router as D } from "wouter-preact";
7
- import { AsyncLocalStorage as I } from "node:async_hooks";
8
- const y = new I();
2
+ import { Hono as b } from "hono";
3
+ import { logger as q } from "hono/logger";
4
+ import { trimTrailingSlash as T } from "hono/trailing-slash";
5
+ import { render as A } from "preact-render-to-string";
6
+ import { Router as R } from "wouter-preact";
7
+ import { AsyncLocalStorage as C } from "node:async_hooks";
8
+ import { getAppContext as v } from "./app-context.js";
9
+ const y = new C();
9
10
  globalThis.__veloServerData = y;
10
- const v = [];
11
11
  let g = null;
12
- function L(t) {
12
+ function G(t) {
13
13
  if (g) {
14
14
  t(g);
15
15
  return;
16
16
  }
17
- v.push(t);
17
+ v().serverCallbacks.push(t);
18
18
  }
19
19
  function w(t) {
20
20
  g = t;
21
- for (const e of v) e(t);
22
- v.length = 0;
21
+ const e = v();
22
+ for (const n of e.serverCallbacks) n(t);
23
+ e.serverCallbacks.length = 0;
23
24
  }
24
- const S = [];
25
- function U(t) {
26
- S.push(t);
25
+ function L(t) {
26
+ v().pendingRoutes.push(t);
27
27
  }
28
- const N = (t, e, s) => {
28
+ const D = (t, e, n) => {
29
29
  if (t.req.query("_data") === "1") {
30
- const c = globalThis.__veloBuildHash || void 0, o = s ? { ...s, __buildHash: c } : { __buildHash: c };
30
+ const c = globalThis.__veloBuildHash || void 0, o = n ? { ...n, __buildHash: c } : { __buildHash: c };
31
31
  return t.json(o);
32
32
  }
33
- const r = t.req.path, n = y.run(
34
- s ?? {},
35
- () => R(/* @__PURE__ */ _(D, { ssrPath: r, children: e }))
33
+ const s = t.req.path, r = y.run(
34
+ n ?? {},
35
+ () => A(/* @__PURE__ */ _(R, { ssrPath: s, children: e }))
36
36
  );
37
- if (t.header("Cache-Control", "no-cache"), !s)
38
- return t.html(n);
37
+ if (t.header("Cache-Control", "no-cache"), !n)
38
+ return t.html(r);
39
39
  const a = `<script>window.__PAGE_DATA__=${JSON.stringify(
40
- s
40
+ n
41
41
  )}<\/script>`;
42
- return t.html(n.replace("</head>", `${a}</head>`));
43
- }, O = async (t, e) => {
44
- const s = e.req.param(), r = e.req.query(), n = { params: s, query: r, c: e }, a = await Promise.all(
42
+ return t.html(r.replace("</head>", `${a}</head>`));
43
+ }, I = async (t, e) => {
44
+ const n = e.req.param(), s = e.req.query(), r = { params: n, query: s, c: e }, a = await Promise.all(
45
45
  t.map(async (o) => {
46
46
  if (!o.loader) return null;
47
- const l = await o.loader(n), i = o.metadata?.moduleId;
47
+ const l = await o.loader(r), i = o.metadata?.moduleId;
48
48
  return i ? { moduleId: i, loaderData: l } : null;
49
49
  })
50
50
  ), c = {
51
- __params: s,
52
- __query: r,
51
+ __params: n,
52
+ __query: s,
53
53
  __pathname: e.req.path
54
54
  };
55
55
  for (const o of a)
@@ -58,90 +58,90 @@ const N = (t, e, s) => {
58
58
  components: t.map((o) => o.Component),
59
59
  data: c
60
60
  };
61
- }, j = (t) => {
61
+ }, N = (t) => {
62
62
  if (t.length === 0) return null;
63
63
  const e = t.filter(Boolean);
64
64
  if (e.length === 0) return null;
65
65
  if (e.length === 1) {
66
- const n = e[0];
67
- return /* @__PURE__ */ _(n, {});
66
+ const r = e[0];
67
+ return /* @__PURE__ */ _(r, {});
68
68
  }
69
- const s = e[e.length - 1];
70
- return e.slice(0, -1).reduceRight((n, a) => /* @__PURE__ */ _(a, { children: n }), /* @__PURE__ */ _(s, {}));
71
- }, P = (t, e, s = [], r = []) => {
72
- for (const n of e) {
73
- const a = [...s, n.module], c = [
74
- ...r,
75
- ...n.middlewares || []
69
+ const n = e[e.length - 1];
70
+ return e.slice(0, -1).reduceRight((r, a) => /* @__PURE__ */ _(a, { children: r }), /* @__PURE__ */ _(n, {}));
71
+ }, S = (t, e, n = [], s = []) => {
72
+ for (const r of e) {
73
+ const a = [...n, r.module], c = [
74
+ ...s,
75
+ ...r.middlewares || []
76
76
  ];
77
- if (n.children)
78
- P(
77
+ if (r.children)
78
+ S(
79
79
  t,
80
- n.children,
80
+ r.children,
81
81
  a,
82
82
  c
83
83
  );
84
84
  else {
85
- const o = n.module.metadata?.fullPath;
85
+ const o = r.module.metadata?.fullPath;
86
86
  if (!o) {
87
87
  console.warn(
88
- `Module ${n.module.metadata?.moduleId} has no fullPath`
88
+ `Module ${r.module.metadata?.moduleId} has no fullPath`
89
89
  );
90
90
  continue;
91
91
  }
92
92
  const l = async (i) => {
93
- const { components: m, data: d } = await O(a, i), u = j(m);
94
- return N(i, u, d);
93
+ const { components: m, data: u } = await I(a, i), d = N(m);
94
+ return D(i, d, u);
95
95
  };
96
96
  c.length > 0 ? t.on(["GET"], [o], ...c, l) : t.on(["GET"], [o], l);
97
97
  }
98
98
  }
99
- }, E = (t, e, s = []) => {
100
- for (const r of e) {
101
- const n = r.module.metadata?.moduleId, a = [
102
- ...s,
103
- ...r.middlewares || []
99
+ }, P = (t, e, n = []) => {
100
+ for (const s of e) {
101
+ const r = s.module.metadata?.moduleId, a = [
102
+ ...n,
103
+ ...s.middlewares || []
104
104
  ];
105
- if (n) {
106
- const c = Object.keys(r.module).filter(
105
+ if (r) {
106
+ const c = Object.keys(s.module).filter(
107
107
  (o) => o.startsWith("action_")
108
108
  );
109
109
  for (const o of c) {
110
- const l = o.replace("action_", ""), i = r.module[o];
110
+ const l = o.replace("action_", ""), i = s.module[o];
111
111
  if (typeof i == "function") {
112
- const m = `/_action/${n}/${l}`, d = async (u) => {
112
+ const m = `/_action/${r}/${l}`, u = async (d) => {
113
113
  let f = {};
114
114
  try {
115
- f = await u.req.json();
115
+ f = await d.req.json();
116
116
  } catch {
117
117
  }
118
118
  const h = {
119
119
  body: f,
120
- params: u.req.param(),
121
- query: u.req.query(),
122
- c: u
120
+ params: d.req.param(),
121
+ query: d.req.query(),
122
+ c: d
123
123
  };
124
124
  try {
125
125
  const p = await i(h);
126
- return u.json(p ?? { ok: !0 });
126
+ return d.json(p ?? { ok: !0 });
127
127
  } catch (p) {
128
- const q = p instanceof Error ? p.message : "Action failed";
129
- return u.json({ error: q }, 500);
128
+ const E = p instanceof Error ? p.message : "Action failed";
129
+ return d.json({ error: E }, 500);
130
130
  }
131
131
  };
132
132
  a.length > 0 ? t.on(
133
133
  ["POST"],
134
134
  [m],
135
135
  ...a,
136
- d
137
- ) : t.on(["POST"], [m], d);
136
+ u
137
+ ) : t.on(["POST"], [m], u);
138
138
  }
139
139
  }
140
140
  }
141
- r.children && E(t, r.children, a);
141
+ s.children && P(t, s.children, a);
142
142
  }
143
- }, C = async (t, e, s = []) => {
144
- const { registerStreamHandler: r } = await import("./events.js"), n = (a, c) => {
143
+ }, O = async (t, e, n = []) => {
144
+ const { registerStreamHandler: s } = await import("./events.js"), r = (a, c) => {
145
145
  for (const o of a) {
146
146
  const l = o.module.metadata?.moduleId, i = [
147
147
  ...c,
@@ -149,13 +149,13 @@ const N = (t, e, s) => {
149
149
  ];
150
150
  if (l) {
151
151
  const m = Object.keys(o.module).filter(
152
- (d) => d.startsWith("stream_")
152
+ (u) => u.startsWith("stream_")
153
153
  );
154
- for (const d of m) {
155
- const u = d.replace("stream_", ""), f = o.module[d];
154
+ for (const u of m) {
155
+ const d = u.replace("stream_", ""), f = o.module[u];
156
156
  if (f?.__isVeloEventStream) {
157
- const h = `/_event/${l}/${u}`;
158
- f.__path = h, r(
157
+ const h = `/_event/${l}/${d}`;
158
+ f.__path = h, s(
159
159
  t,
160
160
  h,
161
161
  f,
@@ -164,37 +164,38 @@ const N = (t, e, s) => {
164
164
  }
165
165
  }
166
166
  }
167
- o.children && n(o.children, i);
167
+ o.children && r(o.children, i);
168
168
  }
169
169
  };
170
- n(e, s);
171
- }, $ = async (t) => {
172
- const e = new T();
173
- e.use(A()), process.env.NODE_ENV !== "production" && e.use("*", b());
174
- for (const r of S)
175
- await r(e);
176
- P(e, t), E(e, t), await C(e, t);
177
- const { flushPendingStreamRoutes: s } = await import("./events.js");
178
- if (s(e), process.env.NODE_ENV !== "production" && !g) {
179
- const r = globalThis.__veloDevServer;
180
- r && w(r);
170
+ r(e, n);
171
+ }, j = async (t) => {
172
+ const e = new b();
173
+ e.use(T()), process.env.NODE_ENV !== "production" && e.use("*", q());
174
+ const s = v().pendingRoutes.splice(0);
175
+ for (const a of s)
176
+ await a(e);
177
+ S(e, t), P(e, t), await O(e, t);
178
+ const { flushPendingStreamRoutes: r } = await import("./events.js");
179
+ if (r(e), process.env.NODE_ENV !== "production" && !g) {
180
+ const a = globalThis.__veloDevServer;
181
+ a && w(a);
181
182
  }
182
183
  return e;
183
- }, W = async (t) => {
184
- const { routes: e, port: s = Number(process.env.SERVER_PORT) || 3e3 } = t, r = await $(e);
184
+ }, U = async (t) => {
185
+ const { routes: e, port: n = Number(process.env.SERVER_PORT) || 3e3 } = t, s = await j(e);
185
186
  if (process.env.NODE_ENV === "production" && !process.env.VELO_STATIC) {
186
- const { serve: n } = await import("@hono/node-server"), { serveStatic: a } = await import("@hono/node-server/serve-static"), { join: c } = await import("node:path"), o = c(process.cwd(), "dist/client");
187
- (process.env.STATIC_BASE_URL || "").startsWith("http") || r.use("/*", a({ root: o })), console.log(`Server running on http://localhost:${s}`);
188
- const i = n({ fetch: r.fetch, port: s });
187
+ const { serve: r } = await import("@hono/node-server"), { serveStatic: a } = await import("@hono/node-server/serve-static"), { join: c } = await import("node:path"), o = c(process.cwd(), "dist/client");
188
+ (process.env.STATIC_BASE_URL || "").startsWith("http") || s.use("/*", a({ root: o })), console.log(`Server running on http://localhost:${n}`);
189
+ const i = r({ fetch: s.fetch, port: n });
189
190
  w(i);
190
191
  }
191
- return r;
192
+ return s;
192
193
  };
193
194
  export {
194
- U as addRoutes,
195
- $ as createApp,
196
- $ as default,
197
- L as onServer,
195
+ L as addRoutes,
196
+ j as createApp,
197
+ j as default,
198
+ G as onServer,
198
199
  y as serverDataStorage,
199
- W as startServer
200
+ U as startServer
200
201
  };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolve URLs from VeloJS function references (action_*, loader, stream_*).
3
+ * Relies on metadata injected by the VeloJS Vite plugin at build time.
4
+ */
5
+ import type { AppRoutes } from "../types.js";
6
+ interface ActionEntry {
7
+ name: string;
8
+ fn: Function;
9
+ moduleId: string;
10
+ url: string;
11
+ }
12
+ interface LoaderEntry {
13
+ fn: Function;
14
+ moduleId: string;
15
+ /** Multiple URL paths can share a loader if registered under different parents. */
16
+ paths: string[];
17
+ }
18
+ export interface ConventionRegistry {
19
+ actions: Map<Function, ActionEntry>;
20
+ loaders: Map<Function, LoaderEntry>;
21
+ }
22
+ export declare function buildConventionRegistry(routes: AppRoutes): ConventionRegistry;
23
+ export declare function resolveActionUrl(registry: ConventionRegistry, fnOrUrl: Function | string): string;
24
+ export declare function resolveLoaderPath(registry: ConventionRegistry, fnOrUrl: Function | string, params?: Record<string, string>): string;
25
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * createTestApp — main entry point for the VeloJS testing toolkit.
3
+ *
4
+ * Builds an in-memory Hono app from your `routes` import, isolates side effects
5
+ * via AsyncLocalStorage so multiple test apps coexist, and exposes a
6
+ * FastAPI-TestClient-style API on top.
7
+ */
8
+ import type { TestApp, CreateTestAppOptions } from "./types.js";
9
+ /**
10
+ * Creates an isolated test app from your routes.
11
+ *
12
+ * ```typescript
13
+ * import { createTestApp } from "@mauroandre/velojs/testing";
14
+ * import { routes } from "../app/routes.js";
15
+ *
16
+ * const app = await createTestApp({
17
+ * routes,
18
+ * bootstrap: async () => { await connectDb(); },
19
+ * getSessionCookie: async ({ user }) => ({ session: await sign(user) }),
20
+ * });
21
+ * ```
22
+ */
23
+ export declare function createTestApp(opts: CreateTestAppOptions): Promise<TestApp>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @mauroandre/velojs/testing
3
+ *
4
+ * Backend testing toolkit for VeloJS apps. FastAPI-TestClient-style API:
5
+ * spin up the app in memory, fire HTTP requests against the registered handlers,
6
+ * subscribe to event streams, assert on the result. No socket, no browser.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createTestApp } from "@mauroandre/velojs/testing";
11
+ * import { routes } from "../app/routes.js";
12
+ *
13
+ * const app = await createTestApp({ routes });
14
+ * const res = await app.get("/api/health");
15
+ * expect(res.status).toBe(200);
16
+ * await app.close();
17
+ * ```
18
+ */
19
+ export { createTestApp } from "./createTestApp.js";
20
+ export type { TestApp, TestResponse, TestSubscription, CreateTestAppOptions, RequestOptions, BodyRequestOptions, LoaderRequestOptions, SubscribeOptions, NextOptions, MockContextOptions, Cookies, Headers, Query, Params, } from "./types.js";