@sigil-dev/grimoire 0.9.4 → 0.9.5

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.
Files changed (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +42 -20
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +10 -6
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +295 -298
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,102 +1,102 @@
1
- import { basename, dirname, join, relative, resolve } from "node:path";
2
- import { transformSync } from "@babel/core";
3
- import sigilPlugin from "@sigil-dev/compiler/babel";
4
- import type { GrimoirePlugin } from "../types";
5
- import type { RouteFile } from "./scanner";
6
-
7
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
8
-
9
- // Inline the same hash helper used in bun-plugin.ts to avoid importing
10
- // unexported internals from @sigil-dev/compiler.
11
- function computeHash(filePath: string): string {
12
- let h = 0x811c9dc5;
13
- for (let i = 0; i < filePath.length; i++) {
14
- h ^= filePath.charCodeAt(i);
15
- h = (h * 0x01000193) >>> 0;
16
- }
17
- return h.toString(36);
18
- }
19
-
20
- function rewriteRelativeImports(filePath: string) {
21
- const basedir = dirname(filePath);
22
- const rewrite = (source?: { value: string }) => {
23
- if (!source?.value.startsWith(".")) return;
24
- source.value = resolve(basedir, source.value);
25
- };
26
-
27
- return {
28
- name: "sigil-rewrite-relative-route-imports",
29
- visitor: {
30
- ImportDeclaration(path: any) {
31
- rewrite(path.node.source);
32
- },
33
- ExportNamedDeclaration(path: any) {
34
- rewrite(path.node.source);
35
- },
36
- ExportAllDeclaration(path: any) {
37
- rewrite(path.node.source);
38
- },
39
- CallExpression(path: any) {
40
- if (path.node.callee.type !== "Import") return;
41
- rewrite(path.node.arguments[0]);
42
- },
43
- },
44
- };
45
- }
46
-
47
- /**
48
- * Pre-transforms route .tsx/.jsx files to plain JS using the Babel sigil
49
- * pipeline, writing the output to `outDir`. Returns a Map from the original
50
- * filePath to the compiled .js path.
51
- *
52
- * Workaround for Bun 1.3.13: Bun.build's native parser runs before onLoad
53
- * hooks fire, crashing on TypeScript syntax. Pre-transforming to JS means
54
- * Bun.build only ever sees plain JavaScript.
55
- */
56
- export async function transformRoutes(
57
- routes: RouteFile[],
58
- outDir: string,
59
- mode: "hydrate" | "dom",
60
- plugins: GrimoirePlugin[] = [],
61
- ): Promise<Map<string, string>> {
62
- const map = new Map<string, string>();
63
- // loader: "ts" — Babel already consumed JSX, Bun only strips remaining types
64
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
65
-
66
- await Promise.all(
67
- routes.map(async (route, index) => {
68
- let code = await Bun.file(route.filePath).text();
69
- const hash = computeHash(route.filePath);
70
- code = code.replace(STYLE_RE, "");
71
-
72
- const res = transformSync(code, {
73
- configFile: false,
74
- babelrc: false,
75
- parserOpts: {
76
- plugins: ["typescript", "jsx"], // no isTSX
77
- },
78
- plugins: [
79
- [sigilPlugin, { hash, mode }],
80
- //@ts-expect-error it fills what it needs
81
- rewriteRelativeImports(route.filePath),
82
- ],
83
- filename: route.filePath,
84
- });
85
- let out = transpiler.transformSync(res?.code ?? "");
86
- for (const plugin of plugins) {
87
- if (plugin.transform)
88
- out = (await plugin.transform(out, route.filePath)) ?? out;
89
- }
90
-
91
- const rel = relative(process.cwd(), route.filePath)
92
- .replace(/\.tsx?$/, "")
93
- .replace(/[^a-zA-Z0-9._-]/g, "_");
94
- const nameBase = rel || basename(route.filePath).replace(/\.[jt]sx$/, "");
95
- const outPath = join(outDir, `${index}-${nameBase}.${mode}.js`);
96
-
97
- await Bun.write(outPath, out);
98
- map.set(route.filePath, outPath);
99
- }),
100
- );
101
- return map;
102
- }
1
+ import { basename, dirname, join, relative, resolve } from "node:path";
2
+ import { transformSync } from "@babel/core";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import type { GrimoirePlugin } from "../types";
5
+ import type { RouteFile } from "./scanner";
6
+
7
+ const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
8
+
9
+ // Inline the same hash helper used in bun-plugin.ts to avoid importing
10
+ // unexported internals from @sigil-dev/compiler.
11
+ function computeHash(filePath: string): string {
12
+ let h = 0x811c9dc5;
13
+ for (let i = 0; i < filePath.length; i++) {
14
+ h ^= filePath.charCodeAt(i);
15
+ h = (h * 0x01000193) >>> 0;
16
+ }
17
+ return h.toString(36);
18
+ }
19
+
20
+ function rewriteRelativeImports(filePath: string) {
21
+ const basedir = dirname(filePath);
22
+ const rewrite = (source?: { value: string }) => {
23
+ if (!source?.value.startsWith(".")) return;
24
+ source.value = resolve(basedir, source.value);
25
+ };
26
+
27
+ return {
28
+ name: "sigil-rewrite-relative-route-imports",
29
+ visitor: {
30
+ ImportDeclaration(path: any) {
31
+ rewrite(path.node.source);
32
+ },
33
+ ExportNamedDeclaration(path: any) {
34
+ rewrite(path.node.source);
35
+ },
36
+ ExportAllDeclaration(path: any) {
37
+ rewrite(path.node.source);
38
+ },
39
+ CallExpression(path: any) {
40
+ if (path.node.callee.type !== "Import") return;
41
+ rewrite(path.node.arguments[0]);
42
+ },
43
+ },
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Pre-transforms route .tsx/.jsx files to plain JS using the Babel sigil
49
+ * pipeline, writing the output to `outDir`. Returns a Map from the original
50
+ * filePath to the compiled .js path.
51
+ *
52
+ * Workaround for Bun 1.3.13: Bun.build's native parser runs before onLoad
53
+ * hooks fire, crashing on TypeScript syntax. Pre-transforming to JS means
54
+ * Bun.build only ever sees plain JavaScript.
55
+ */
56
+ export async function transformRoutes(
57
+ routes: RouteFile[],
58
+ outDir: string,
59
+ mode: "hydrate" | "dom",
60
+ plugins: GrimoirePlugin[] = [],
61
+ ): Promise<Map<string, string>> {
62
+ const map = new Map<string, string>();
63
+ // loader: "ts" — Babel already consumed JSX, Bun only strips remaining types
64
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
65
+
66
+ await Promise.all(
67
+ routes.map(async (route, index) => {
68
+ let code = await Bun.file(route.filePath).text();
69
+ const hash = computeHash(route.filePath);
70
+ code = code.replace(STYLE_RE, "");
71
+
72
+ const res = transformSync(code, {
73
+ configFile: false,
74
+ babelrc: false,
75
+ parserOpts: {
76
+ plugins: ["typescript", "jsx"], // no isTSX
77
+ },
78
+ plugins: [
79
+ [sigilPlugin, { hash, mode }],
80
+ //@ts-expect-error it fills what it needs
81
+ rewriteRelativeImports(route.filePath),
82
+ ],
83
+ filename: route.filePath,
84
+ });
85
+ let out = transpiler.transformSync(res?.code ?? "");
86
+ for (const plugin of plugins) {
87
+ if (plugin.transform)
88
+ out = (await plugin.transform(out, route.filePath)) ?? out;
89
+ }
90
+
91
+ const rel = relative(process.cwd(), route.filePath)
92
+ .replace(/\.tsx?$/, "")
93
+ .replace(/[^a-zA-Z0-9._-]/g, "_");
94
+ const nameBase = rel || basename(route.filePath).replace(/\.[jt]sx$/, "");
95
+ const outPath = join(outDir, `${index}-${nameBase}.${mode}.js`);
96
+
97
+ await Bun.write(outPath, out);
98
+ map.set(route.filePath, outPath);
99
+ }),
100
+ );
101
+ return map;
102
+ }
@@ -1,52 +1,52 @@
1
- /**
2
- * Throw an error from a load function or form action.
3
- * The server catches it and returns an error response.
4
- *
5
- * Usage in +page.server.ts:
6
- *
7
- * import { error } from "@sigil-dev/grimoire";
8
- *
9
- * export async function load({ params }) {
10
- * const item = await db.find(params.id);
11
- * if (!item) throw error(404, "Not found");
12
- * return { item };
13
- * }
14
- *
15
- * export async function POST({ request }) {
16
- * const session = await getSession(request);
17
- * if (!session) throw error(401, "Unauthorized");
18
- * // ...
19
- * }
20
- *
21
- * The server:
22
- * - Returns JSON { error: true, status, message } for API requests
23
- * - Renders +error.tsx page if one exists for the route
24
- * - Falls back to a plain text error response
25
- */
26
- export interface ErrorResult {
27
- __error: true;
28
- status: number;
29
- message: string;
30
- }
31
-
32
- export function error(status: number, message: string): never;
33
- export function error(status: number, data: Record<string, unknown>): never;
34
- export function error(
35
- status: number,
36
- messageOrData: string | Record<string, unknown>,
37
- ): never {
38
- const message =
39
- typeof messageOrData === "string"
40
- ? messageOrData
41
- : JSON.stringify(messageOrData);
42
-
43
- throw { __error: true, status, message } as ErrorResult;
44
- }
45
-
46
- export function isErrorResult(value: unknown): value is ErrorResult {
47
- return (
48
- typeof value === "object" &&
49
- value !== null &&
50
- (value as any).__error === true
51
- );
52
- }
1
+ /**
2
+ * Throw an error from a load function or form action.
3
+ * The server catches it and returns an error response.
4
+ *
5
+ * Usage in +page.server.ts:
6
+ *
7
+ * import { error } from "@sigil-dev/grimoire";
8
+ *
9
+ * export async function load({ params }) {
10
+ * const item = await db.find(params.id);
11
+ * if (!item) throw error(404, "Not found");
12
+ * return { item };
13
+ * }
14
+ *
15
+ * export async function POST({ request }) {
16
+ * const session = await getSession(request);
17
+ * if (!session) throw error(401, "Unauthorized");
18
+ * // ...
19
+ * }
20
+ *
21
+ * The server:
22
+ * - Returns JSON { error: true, status, message } for API requests
23
+ * - Renders +error.tsx page if one exists for the route
24
+ * - Falls back to a plain text error response
25
+ */
26
+ export interface ErrorResult {
27
+ __error: true;
28
+ status: number;
29
+ message: string;
30
+ }
31
+
32
+ export function error(status: number, message: string): never;
33
+ export function error(status: number, data: Record<string, unknown>): never;
34
+ export function error(
35
+ status: number,
36
+ messageOrData: string | Record<string, unknown>,
37
+ ): never {
38
+ const message =
39
+ typeof messageOrData === "string"
40
+ ? messageOrData
41
+ : JSON.stringify(messageOrData);
42
+
43
+ throw { __error: true, status, message } as ErrorResult;
44
+ }
45
+
46
+ export function isErrorResult(value: unknown): value is ErrorResult {
47
+ return (
48
+ typeof value === "object" &&
49
+ value !== null &&
50
+ (value as any).__error === true
51
+ );
52
+ }
@@ -1,41 +1,41 @@
1
- /**
2
- * Return validation errors from a server form action.
3
- * Instead of redirecting, the server sends a JSON response with the error data.
4
- *
5
- * Usage in +page.server.ts:
6
- *
7
- * import { fail } from "@sigil-dev/grimoire";
8
- *
9
- * export async function POST({ request }) {
10
- * const form = await request.formData();
11
- * const name = form.get("name")?.toString() ?? "";
12
- *
13
- * if (!name) {
14
- * return fail(400, { name, errors: { name: "Name is required" } });
15
- * }
16
- *
17
- * // success — redirect
18
- * return { redirect: "/dashboard" };
19
- * }
20
- */
21
- export function fail<T extends Record<string, unknown>>(
22
- status: number,
23
- data: T,
24
- ): FailResult<T> {
25
- return { __fail: true as const, status, data };
26
- }
27
-
28
- export interface FailResult<T = Record<string, unknown>> {
29
- __fail: true;
30
- status: number;
31
- data: T;
32
- }
33
-
34
- export function isFailResult(value: unknown): value is FailResult {
35
- return (
36
- typeof value === "object" &&
37
- value !== null &&
38
- "__fail" in value &&
39
- (value as any).__fail === true
40
- );
41
- }
1
+ /**
2
+ * Return validation errors from a server form action.
3
+ * Instead of redirecting, the server sends a JSON response with the error data.
4
+ *
5
+ * Usage in +page.server.ts:
6
+ *
7
+ * import { fail } from "@sigil-dev/grimoire";
8
+ *
9
+ * export async function POST({ request }) {
10
+ * const form = await request.formData();
11
+ * const name = form.get("name")?.toString() ?? "";
12
+ *
13
+ * if (!name) {
14
+ * return fail(400, { name, errors: { name: "Name is required" } });
15
+ * }
16
+ *
17
+ * // success — redirect
18
+ * return { redirect: "/dashboard" };
19
+ * }
20
+ */
21
+ export function fail<T extends Record<string, unknown>>(
22
+ status: number,
23
+ data: T,
24
+ ): FailResult<T> {
25
+ return { __fail: true as const, status, data };
26
+ }
27
+
28
+ export interface FailResult<T = Record<string, unknown>> {
29
+ __fail: true;
30
+ status: number;
31
+ data: T;
32
+ }
33
+
34
+ export function isFailResult(value: unknown): value is FailResult {
35
+ return (
36
+ typeof value === "object" &&
37
+ value !== null &&
38
+ "__fail" in value &&
39
+ (value as any).__fail === true
40
+ );
41
+ }
@@ -1,35 +1,35 @@
1
- /**
2
- * Throw a redirect from a load function or form action.
3
- * The server catches it and returns a 3xx Response.
4
- *
5
- * Usage in +page.server.ts:
6
- *
7
- * import { redirect } from "@sigil-dev/grimoire";
8
- *
9
- * export async function load({ locals }) {
10
- * if (!locals.user) throw redirect(302, "/login");
11
- * return { user: locals.user };
12
- * }
13
- *
14
- * export async function POST({ request }) {
15
- * // ... process form
16
- * throw redirect(303, "/dashboard");
17
- * }
18
- */
19
- export interface RedirectResult {
20
- __redirect: true;
21
- status: number;
22
- location: string;
23
- }
24
-
25
- export function redirect(status: number, location: string): never {
26
- throw { __redirect: true, status, location } as RedirectResult;
27
- }
28
-
29
- export function isRedirectResult(value: unknown): value is RedirectResult {
30
- return (
31
- typeof value === "object" &&
32
- value !== null &&
33
- (value as any).__redirect === true
34
- );
35
- }
1
+ /**
2
+ * Throw a redirect from a load function or form action.
3
+ * The server catches it and returns a 3xx Response.
4
+ *
5
+ * Usage in +page.server.ts:
6
+ *
7
+ * import { redirect } from "@sigil-dev/grimoire";
8
+ *
9
+ * export async function load({ locals }) {
10
+ * if (!locals.user) throw redirect(302, "/login");
11
+ * return { user: locals.user };
12
+ * }
13
+ *
14
+ * export async function POST({ request }) {
15
+ * // ... process form
16
+ * throw redirect(303, "/dashboard");
17
+ * }
18
+ */
19
+ export interface RedirectResult {
20
+ __redirect: true;
21
+ status: number;
22
+ location: string;
23
+ }
24
+
25
+ export function redirect(status: number, location: string): never {
26
+ throw { __redirect: true, status, location } as RedirectResult;
27
+ }
28
+
29
+ export function isRedirectResult(value: unknown): value is RedirectResult {
30
+ return (
31
+ typeof value === "object" &&
32
+ value !== null &&
33
+ (value as any).__redirect === true
34
+ );
35
+ }