@sigil-dev/grimoire 0.9.29 → 0.9.31

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 (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +479 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +1181 -1171
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +642 -508
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +659 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,295 +1,304 @@
1
- import { mkdir } from "node:fs/promises";
2
- import { isAbsolute, join } from "node:path";
3
- import { sigil } from "@sigil-dev/compiler/bun";
4
- import { generateManifest } from "../routing/manifest-gen";
5
- import type { RouteTree } from "../routing/scanner";
6
- import { scanRoutes } from "../routing/scanner";
7
- import { transformRoutes } from "../routing/transform-routes";
8
- import { generateTypes } from "../typegen";
9
- import type { BuildResult, GrimoireConfig, GrimoirePlugin } from "../types";
10
- import {
11
- clientDir,
12
- pruneClientDir,
13
- RUNTIME_URL,
14
- resetClientDir,
15
- } from "./client-dir";
16
- import { recordClientEntry } from "./client-entry";
17
- import { runHook } from "./plugins";
18
- import { projectAliases, resolverPlugin } from "./resolver";
19
-
20
- const makeRoutesPlugin = (manifestPath: string) => ({
21
- name: "grimoire-routes",
22
- setup(build: any) {
23
- build.onResolve({ filter: /^#grimoire-routes$/ }, () => ({
24
- path: manifestPath,
25
- }));
26
- },
27
- });
28
-
29
- /**
30
- * Dev only: the client bundles import the runtime from RUNTIME_URL, the file
31
- * HMR-swapped modules import, instead of each carrying a copy.
32
- *
33
- * Two copies are two sets of module state. The one that broke: the router
34
- * collects a re-render's effects with `collectEffects`, which sets a flag on
35
- * globalThis that every copy reads, but queues into its own module. A swapped
36
- * layout's effects (`{children}`, any prop in text) went into the other copy's
37
- * queue, which nothing flushes, so the page vanished from the layout. Signals,
38
- * context and effect scopes don't cross copies either.
39
- *
40
- * Production has no swapped modules, so it keeps bundling the runtime.
41
- */
42
- const sharedDevRuntime = {
43
- name: "grimoire-shared-dev-runtime",
44
- setup(build: any) {
45
- build.onResolve({ filter: /^@sigil-dev\/runtime$/ }, () => ({
46
- path: RUNTIME_URL,
47
- external: true,
48
- }));
49
- },
50
- };
51
-
52
- /**
53
- * Rebuild the client bundles in dev.
54
- *
55
- * `hydrate.js` and the dom bundle are produced once at startup, so any full
56
- * reload after an edit would otherwise hand the browser pre-edit code. Route
57
- * files are re-transformed (Bun.build only ever sees plain JS) and the
58
- * manifests regenerated, which also picks up routes added since startup.
59
- * Returns the freshly scanned tree so the server can adopt it.
60
- */
61
- export async function rebuildClient(
62
- config: GrimoireConfig,
63
- plugins: GrimoirePlugin[] = [],
64
- ): Promise<{ result: BuildResult; tree: RouteTree }> {
65
- const { routes = "src/routes" } = config;
66
- const isDev = config.dev ?? false;
67
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
68
-
69
- const tree = await scanRoutes(routesDir, process.cwd());
70
- const compiledDir = join(process.cwd(), ".grimoire/compiled");
71
- const clientRoutes = [
72
- ...tree.routes.filter((r) => r.type === "page" || r.type === "simple"),
73
- ...tree.layouts.filter((r) => r.type === "layout"),
74
- ];
75
-
76
- const hydrateManifest = join(process.cwd(), ".grimoire/_routes.hydrate.js");
77
- const domManifest = join(process.cwd(), ".grimoire/_routes.dom.js");
78
- const [hydrateFiles, domFiles] = await Promise.all([
79
- transformRoutes(clientRoutes, compiledDir, "hydrate", plugins),
80
- transformRoutes(clientRoutes, compiledDir, "dom", plugins),
81
- ]);
82
- await Promise.all([
83
- Bun.write(
84
- hydrateManifest,
85
- generateManifest(clientRoutes, hydrateFiles, tree.paramMatcherFiles),
86
- ),
87
- Bun.write(
88
- domManifest,
89
- generateManifest(clientRoutes, domFiles, tree.paramMatcherFiles),
90
- ),
91
- ]);
92
-
93
- const bundleDir = clientDir();
94
-
95
- const [hydrateResult, domResult] = await Promise.all([
96
- Bun.build({
97
- entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
98
- outdir: bundleDir,
99
- naming: { entry: "[name]-[hash].[ext]" },
100
- // report failures in result.logs instead of throwing past them
101
- throw: false,
102
- // lazy route entries in the manifest use dynamic import()
103
- splitting: true,
104
- plugins: [
105
- ...(isDev ? [sharedDevRuntime] : []),
106
- sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
107
- makeRoutesPlugin(hydrateManifest),
108
- resolverPlugin(config, "browser"),
109
- ],
110
- }),
111
- Bun.build({
112
- entrypoints: [join(import.meta.dir, "../client/index.ts")],
113
- outdir: bundleDir,
114
- naming: { entry: "[name]-[hash].[ext]" },
115
- // report failures in result.logs instead of throwing past them
116
- throw: false,
117
- splitting: true,
118
- plugins: [
119
- ...(isDev ? [sharedDevRuntime] : []),
120
- sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
121
- makeRoutesPlugin(domManifest),
122
- resolverPlugin(config, "browser"),
123
- ],
124
- }),
125
- ]);
126
-
127
- const outputs = [...hydrateResult.outputs, ...domResult.outputs].map(
128
- (o) => o.path,
129
- );
130
- const success = hydrateResult.success && domResult.success;
131
- // a failed build keeps the last good bundle in place
132
- if (success) {
133
- recordClientEntry([...hydrateResult.outputs, ...domResult.outputs]);
134
- await pruneClientDir(outputs);
135
- }
136
-
137
- return {
138
- tree,
139
- result: {
140
- success,
141
- outputs,
142
- errors: [...hydrateResult.logs, ...domResult.logs].map(String),
143
- },
144
- };
145
- }
146
-
147
- export async function buildProject(
148
- config: GrimoireConfig,
149
- plugins: GrimoirePlugin[] = [],
150
- ): Promise<{ result: BuildResult; tree: RouteTree }> {
151
- await runHook(plugins, "onBuildStart");
152
-
153
- const { routes = "src/routes" } = config;
154
- const isDev = config.dev ?? false;
155
-
156
- const routesDir = isAbsolute(routes)
157
- ? routes.replace(/\0/g, "")
158
- : join(process.cwd(), routes).replace(/\0/g, "");
159
- const tree = await scanRoutes(routesDir, process.cwd());
160
-
161
- const outDir = join(process.cwd(), ".grimoire");
162
- await mkdir(outDir, { recursive: true });
163
-
164
- await generateTypes(tree, {
165
- projectRoot: process.cwd(),
166
- routesDir,
167
- outDir: join(outDir, "types"),
168
- aliases: projectAliases(config),
169
- });
170
-
171
- const { generateEnvTypes } = await import("../env/typegen");
172
- const envTypeDir = join(outDir, "types");
173
- await mkdir(envTypeDir, { recursive: true });
174
- await generateEnvTypes(process.cwd(), envTypeDir);
175
-
176
- const compiledDir = join(outDir, "compiled");
177
- await mkdir(compiledDir, { recursive: true });
178
-
179
- const clientRoutes = [
180
- ...tree.routes.filter((r) => r.type === "page" || r.type === "simple"),
181
- ...tree.layouts.filter((r) => r.type === "layout"),
182
- ];
183
-
184
- const [hydrateFiles, domFiles] = await Promise.all([
185
- transformRoutes(clientRoutes, compiledDir, "hydrate", plugins),
186
- transformRoutes(clientRoutes, compiledDir, "dom", plugins),
187
- ]);
188
-
189
- const hydrateManifest = join(process.cwd(), ".grimoire/_routes.hydrate.js");
190
- const domManifest = join(process.cwd(), ".grimoire/_routes.dom.js");
191
- await Promise.all([
192
- Bun.write(
193
- hydrateManifest,
194
- generateManifest(clientRoutes, hydrateFiles, tree.paramMatcherFiles),
195
- ),
196
- Bun.write(
197
- domManifest,
198
- generateManifest(clientRoutes, domFiles, tree.paramMatcherFiles),
199
- ),
200
- ]);
201
-
202
- const bundleStrategy = config.bundleStrategy ?? "split";
203
- const bundleDir = clientDir();
204
- await resetClientDir();
205
-
206
- if (bundleStrategy === "single") {
207
- const singleResult = await Bun.build({
208
- entrypoints: [
209
- join(import.meta.dir, "../rendering/hydrate.ts"),
210
- join(import.meta.dir, "../client/index.ts"),
211
- ],
212
- outdir: bundleDir,
213
- naming: { entry: "[name]-[hash].[ext]" },
214
- // report failures in result.logs instead of throwing past them
215
- throw: false,
216
- // lazy route entries in the manifest use dynamic import()
217
- splitting: true,
218
- plugins: [
219
- ...(isDev ? [sharedDevRuntime] : []),
220
- sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
221
- sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
222
- makeRoutesPlugin(hydrateManifest),
223
- makeRoutesPlugin(domManifest),
224
- resolverPlugin(config, "browser"),
225
- ],
226
- });
227
-
228
- if (!singleResult.success) {
229
- for (const log of singleResult.logs) console.error(log);
230
- } else {
231
- recordClientEntry(singleResult.outputs);
232
- }
233
-
234
- const result: BuildResult = {
235
- success: singleResult.success,
236
- outputs: singleResult.outputs.map((o) => o.path),
237
- errors: singleResult.logs.map(String),
238
- };
239
-
240
- await runHook(plugins, "onBuildEnd", result);
241
- return { result, tree };
242
- }
243
-
244
- const [hydrateResult, domResult] = await Promise.all([
245
- Bun.build({
246
- entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
247
- outdir: bundleDir,
248
- naming: { entry: "[name]-[hash].[ext]" },
249
- // report failures in result.logs instead of throwing past them
250
- throw: false,
251
- // lazy route entries in the manifest use dynamic import()
252
- splitting: true,
253
- plugins: [
254
- ...(isDev ? [sharedDevRuntime] : []),
255
- sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
256
- makeRoutesPlugin(hydrateManifest),
257
- resolverPlugin(config, "browser"),
258
- ],
259
- }),
260
- Bun.build({
261
- entrypoints: [join(import.meta.dir, "../client/index.ts")],
262
- outdir: bundleDir,
263
- naming: { entry: "[name]-[hash].[ext]" },
264
- // report failures in result.logs instead of throwing past them
265
- throw: false,
266
- splitting: true,
267
- plugins: [
268
- ...(isDev ? [sharedDevRuntime] : []),
269
- sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
270
- makeRoutesPlugin(domManifest),
271
- resolverPlugin(config, "browser"),
272
- ],
273
- }),
274
- ]);
275
-
276
- if (!hydrateResult.success) {
277
- for (const log of hydrateResult.logs) console.error(log);
278
- } else {
279
- recordClientEntry(hydrateResult.outputs);
280
- }
281
- if (!domResult.success) {
282
- for (const log of domResult.logs) console.error(log);
283
- }
284
-
285
- const result: BuildResult = {
286
- success: hydrateResult.success && domResult.success,
287
- outputs: [...hydrateResult.outputs, ...domResult.outputs].map(
288
- (o) => o.path,
289
- ),
290
- errors: [...hydrateResult.logs, ...domResult.logs].map(String),
291
- };
292
-
293
- await runHook(plugins, "onBuildEnd", result);
294
- return { result, tree };
295
- }
1
+ import { mkdir } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { setKnownRoutes, setStaticEnv } from "@sigil-dev/compiler";
4
+ import { sigil } from "@sigil-dev/compiler/bun";
5
+ import { filterPrivate, filterPublic } from "../env";
6
+ import { generateManifest } from "../routing/manifest-gen";
7
+ import { linkableRoutes, routeId } from "../routing/route-ids";
8
+ import type { RouteTree } from "../routing/scanner";
9
+ import { scanRoutes } from "../routing/scanner";
10
+ import { transformRoutes } from "../routing/transform-routes";
11
+ import { generateTypes } from "../typegen";
12
+ import type { BuildResult, GrimoireConfig, GrimoirePlugin } from "../types";
13
+ import {
14
+ clientDir,
15
+ pruneClientDir,
16
+ RUNTIME_URL,
17
+ resetClientDir,
18
+ } from "./client-dir";
19
+ import { recordClientEntry } from "./client-entry";
20
+ import { runHook } from "./plugins";
21
+ import { projectAliases, resolverPlugin } from "./resolver";
22
+
23
+ const makeRoutesPlugin = (manifestPath: string) => ({
24
+ name: "grimoire-routes",
25
+ setup(build: any) {
26
+ build.onResolve({ filter: /^#grimoire-routes$/ }, () => ({
27
+ path: manifestPath,
28
+ }));
29
+ },
30
+ });
31
+
32
+ /**
33
+ * Dev only: the client bundles import the runtime from RUNTIME_URL, the file
34
+ * HMR-swapped modules import, instead of each carrying a copy.
35
+ *
36
+ * Two copies are two sets of module state. The one that broke: the router
37
+ * collects a re-render's effects with `collectEffects`, which sets a flag on
38
+ * globalThis that every copy reads, but queues into its own module. A swapped
39
+ * layout's effects (`{children}`, any prop in text) went into the other copy's
40
+ * queue, which nothing flushes, so the page vanished from the layout. Signals,
41
+ * context and effect scopes don't cross copies either.
42
+ *
43
+ * Production has no swapped modules, so it keeps bundling the runtime.
44
+ */
45
+ const sharedDevRuntime = {
46
+ name: "grimoire-shared-dev-runtime",
47
+ setup(build: any) {
48
+ build.onResolve({ filter: /^@sigil-dev\/runtime$/ }, () => ({
49
+ path: RUNTIME_URL,
50
+ external: true,
51
+ }));
52
+ },
53
+ };
54
+
55
+ /**
56
+ * Rebuild the client bundles in dev.
57
+ *
58
+ * `hydrate.js` and the dom bundle are produced once at startup, so any full
59
+ * reload after an edit would otherwise hand the browser pre-edit code. Route
60
+ * files are re-transformed (Bun.build only ever sees plain JS) and the
61
+ * manifests regenerated, which also picks up routes added since startup.
62
+ * Returns the freshly scanned tree so the server can adopt it.
63
+ */
64
+ export async function rebuildClient(
65
+ config: GrimoireConfig,
66
+ plugins: GrimoirePlugin[] = [],
67
+ ): Promise<{ result: BuildResult; tree: RouteTree }> {
68
+ const { routes = "src/routes" } = config;
69
+ const isDev = config.dev ?? false;
70
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
71
+
72
+ const tree = await scanRoutes(routesDir, process.cwd());
73
+ setKnownRoutes(linkableRoutes(tree).map(routeId));
74
+ setStaticEnv(filterPublic(process.env), filterPrivate(process.env));
75
+ const compiledDir = join(process.cwd(), ".grimoire/compiled");
76
+ const clientRoutes = [
77
+ ...tree.routes.filter((r) => r.type === "page" || r.type === "simple"),
78
+ ...tree.layouts.filter((r) => r.type === "layout"),
79
+ ];
80
+
81
+ const hydrateManifest = join(process.cwd(), ".grimoire/_routes.hydrate.js");
82
+ const domManifest = join(process.cwd(), ".grimoire/_routes.dom.js");
83
+ const [hydrateFiles, domFiles] = await Promise.all([
84
+ transformRoutes(clientRoutes, compiledDir, "hydrate", plugins),
85
+ transformRoutes(clientRoutes, compiledDir, "dom", plugins),
86
+ ]);
87
+ await Promise.all([
88
+ Bun.write(
89
+ hydrateManifest,
90
+ generateManifest(clientRoutes, hydrateFiles, tree.paramMatcherFiles),
91
+ ),
92
+ Bun.write(
93
+ domManifest,
94
+ generateManifest(clientRoutes, domFiles, tree.paramMatcherFiles),
95
+ ),
96
+ ]);
97
+
98
+ const bundleDir = clientDir();
99
+
100
+ const [hydrateResult, domResult] = await Promise.all([
101
+ Bun.build({
102
+ entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
103
+ outdir: bundleDir,
104
+ naming: { entry: "[name]-[hash].[ext]" },
105
+ // report failures in result.logs instead of throwing past them
106
+ throw: false,
107
+ // lazy route entries in the manifest use dynamic import()
108
+ splitting: true,
109
+ plugins: [
110
+ ...(isDev ? [sharedDevRuntime] : []),
111
+ sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
112
+ makeRoutesPlugin(hydrateManifest),
113
+ resolverPlugin(config, "browser"),
114
+ ],
115
+ }),
116
+ Bun.build({
117
+ entrypoints: [join(import.meta.dir, "../client/index.ts")],
118
+ outdir: bundleDir,
119
+ naming: { entry: "[name]-[hash].[ext]" },
120
+ // report failures in result.logs instead of throwing past them
121
+ throw: false,
122
+ splitting: true,
123
+ plugins: [
124
+ ...(isDev ? [sharedDevRuntime] : []),
125
+ sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
126
+ makeRoutesPlugin(domManifest),
127
+ resolverPlugin(config, "browser"),
128
+ ],
129
+ }),
130
+ ]);
131
+
132
+ const outputs = [...hydrateResult.outputs, ...domResult.outputs].map(
133
+ (o) => o.path,
134
+ );
135
+ const success = hydrateResult.success && domResult.success;
136
+ // a failed build keeps the last good bundle in place
137
+ if (success) {
138
+ recordClientEntry([...hydrateResult.outputs, ...domResult.outputs]);
139
+ await pruneClientDir(outputs);
140
+ }
141
+
142
+ return {
143
+ tree,
144
+ result: {
145
+ success,
146
+ outputs,
147
+ errors: [...hydrateResult.logs, ...domResult.logs].map(String),
148
+ },
149
+ };
150
+ }
151
+
152
+ export async function buildProject(
153
+ config: GrimoireConfig,
154
+ plugins: GrimoirePlugin[] = [],
155
+ ): Promise<{ result: BuildResult; tree: RouteTree }> {
156
+ await runHook(plugins, "onBuildStart");
157
+
158
+ const { routes = "src/routes" } = config;
159
+ const isDev = config.dev ?? false;
160
+
161
+ const routesDir = isAbsolute(routes)
162
+ ? routes.replace(/\0/g, "")
163
+ : join(process.cwd(), routes).replace(/\0/g, "");
164
+ const tree = await scanRoutes(routesDir, process.cwd());
165
+ // the compiler checks literal <a href="/…"> against these
166
+ setKnownRoutes(linkableRoutes(tree).map(routeId));
167
+ // and writes $env/static values into the code, read now, as documented
168
+ setStaticEnv(filterPublic(process.env), filterPrivate(process.env));
169
+
170
+ const outDir = join(process.cwd(), ".grimoire");
171
+ await mkdir(outDir, { recursive: true });
172
+
173
+ await generateTypes(tree, {
174
+ projectRoot: process.cwd(),
175
+ routesDir,
176
+ outDir: join(outDir, "types"),
177
+ aliases: projectAliases(config),
178
+ });
179
+
180
+ const { generateEnvTypes } = await import("../env/typegen");
181
+ const envTypeDir = join(outDir, "types");
182
+ await mkdir(envTypeDir, { recursive: true });
183
+ await generateEnvTypes(process.cwd(), envTypeDir);
184
+
185
+ const compiledDir = join(outDir, "compiled");
186
+ await mkdir(compiledDir, { recursive: true });
187
+
188
+ const clientRoutes = [
189
+ ...tree.routes.filter((r) => r.type === "page" || r.type === "simple"),
190
+ ...tree.layouts.filter((r) => r.type === "layout"),
191
+ ];
192
+
193
+ const [hydrateFiles, domFiles] = await Promise.all([
194
+ transformRoutes(clientRoutes, compiledDir, "hydrate", plugins),
195
+ transformRoutes(clientRoutes, compiledDir, "dom", plugins),
196
+ ]);
197
+
198
+ const hydrateManifest = join(process.cwd(), ".grimoire/_routes.hydrate.js");
199
+ const domManifest = join(process.cwd(), ".grimoire/_routes.dom.js");
200
+ await Promise.all([
201
+ Bun.write(
202
+ hydrateManifest,
203
+ generateManifest(clientRoutes, hydrateFiles, tree.paramMatcherFiles),
204
+ ),
205
+ Bun.write(
206
+ domManifest,
207
+ generateManifest(clientRoutes, domFiles, tree.paramMatcherFiles),
208
+ ),
209
+ ]);
210
+
211
+ const bundleStrategy = config.bundleStrategy ?? "split";
212
+ const bundleDir = clientDir();
213
+ await resetClientDir();
214
+
215
+ if (bundleStrategy === "single") {
216
+ const singleResult = await Bun.build({
217
+ entrypoints: [
218
+ join(import.meta.dir, "../rendering/hydrate.ts"),
219
+ join(import.meta.dir, "../client/index.ts"),
220
+ ],
221
+ outdir: bundleDir,
222
+ naming: { entry: "[name]-[hash].[ext]" },
223
+ // report failures in result.logs instead of throwing past them
224
+ throw: false,
225
+ // lazy route entries in the manifest use dynamic import()
226
+ splitting: true,
227
+ plugins: [
228
+ ...(isDev ? [sharedDevRuntime] : []),
229
+ sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
230
+ sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
231
+ makeRoutesPlugin(hydrateManifest),
232
+ makeRoutesPlugin(domManifest),
233
+ resolverPlugin(config, "browser"),
234
+ ],
235
+ });
236
+
237
+ if (!singleResult.success) {
238
+ for (const log of singleResult.logs) console.error(log);
239
+ } else {
240
+ recordClientEntry(singleResult.outputs);
241
+ }
242
+
243
+ const result: BuildResult = {
244
+ success: singleResult.success,
245
+ outputs: singleResult.outputs.map((o) => o.path),
246
+ errors: singleResult.logs.map(String),
247
+ };
248
+
249
+ await runHook(plugins, "onBuildEnd", result);
250
+ return { result, tree };
251
+ }
252
+
253
+ const [hydrateResult, domResult] = await Promise.all([
254
+ Bun.build({
255
+ entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
256
+ outdir: bundleDir,
257
+ naming: { entry: "[name]-[hash].[ext]" },
258
+ // report failures in result.logs instead of throwing past them
259
+ throw: false,
260
+ // lazy route entries in the manifest use dynamic import()
261
+ splitting: true,
262
+ plugins: [
263
+ ...(isDev ? [sharedDevRuntime] : []),
264
+ sigil({ mode: "hydrate", dev: isDev, aliases: projectAliases(config) }),
265
+ makeRoutesPlugin(hydrateManifest),
266
+ resolverPlugin(config, "browser"),
267
+ ],
268
+ }),
269
+ Bun.build({
270
+ entrypoints: [join(import.meta.dir, "../client/index.ts")],
271
+ outdir: bundleDir,
272
+ naming: { entry: "[name]-[hash].[ext]" },
273
+ // report failures in result.logs instead of throwing past them
274
+ throw: false,
275
+ splitting: true,
276
+ plugins: [
277
+ ...(isDev ? [sharedDevRuntime] : []),
278
+ sigil({ mode: "dom", dev: isDev, aliases: projectAliases(config) }),
279
+ makeRoutesPlugin(domManifest),
280
+ resolverPlugin(config, "browser"),
281
+ ],
282
+ }),
283
+ ]);
284
+
285
+ if (!hydrateResult.success) {
286
+ for (const log of hydrateResult.logs) console.error(log);
287
+ } else {
288
+ recordClientEntry(hydrateResult.outputs);
289
+ }
290
+ if (!domResult.success) {
291
+ for (const log of domResult.logs) console.error(log);
292
+ }
293
+
294
+ const result: BuildResult = {
295
+ success: hydrateResult.success && domResult.success,
296
+ outputs: [...hydrateResult.outputs, ...domResult.outputs].map(
297
+ (o) => o.path,
298
+ ),
299
+ errors: [...hydrateResult.logs, ...domResult.logs].map(String),
300
+ };
301
+
302
+ await runHook(plugins, "onBuildEnd", result);
303
+ return { result, tree };
304
+ }