@sigil-dev/grimoire 0.9.28 → 0.9.30

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 +476 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +8 -0
  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 +140 -19
  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 +640 -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,17 +1,17 @@
1
- /**
2
- * `+page.server.ts` exports that are never dispatched as named actions.
3
- *
4
- * Every other function export is callable by name (`?/create`), so a helper
5
- * a route module exports for the framework has to be listed here or a form
6
- * could invoke it.
7
- */
8
- export const RESERVED_EXPORTS = new Set([
9
- "load",
10
- "canMatch",
11
- "csrf",
12
- "loading",
13
- "default",
14
- // read by the build, never by a request
15
- "prerender",
16
- "entries",
17
- ]);
1
+ /**
2
+ * `+page.server.ts` exports that are never dispatched as named actions.
3
+ *
4
+ * Every other function export is callable by name (`?/create`), so a helper
5
+ * a route module exports for the framework has to be listed here or a form
6
+ * could invoke it.
7
+ */
8
+ export const RESERVED_EXPORTS = new Set([
9
+ "load",
10
+ "canMatch",
11
+ "csrf",
12
+ "loading",
13
+ "default",
14
+ // read by the build, never by a request
15
+ "prerender",
16
+ "entries",
17
+ ]);
@@ -1,123 +1,149 @@
1
- import { isAbsolute, join } from "node:path";
2
- import type { BunPlugin } from "bun";
3
- import { resolveFile } from "../dev/resolve";
4
- import { ENV_MODULE, envModuleSource } from "../env/modules";
5
- import type { GrimoireConfig } from "../types";
6
-
7
- /**
8
- * Import prefixes → absolute directories: `$lib` for `src/lib` unless the
9
- * config says otherwise, plus `GrimoireConfig.alias`.
10
- */
11
- export function projectAliases(
12
- config: GrimoireConfig,
13
- root = process.cwd(),
14
- ): Record<string, string> {
15
- const out: Record<string, string> = { $lib: join(root, "src/lib") };
16
- for (const [prefix, target] of Object.entries(config.alias ?? {})) {
17
- out[prefix] = isAbsolute(target) ? target : join(root, target);
18
- }
19
- return out;
20
- }
21
-
22
- const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
-
24
- /**
25
- * Resolves `$env/*` and aliased imports, for the browser builds (Bun.build)
26
- * and for the server (Bun.plugin). Bun has no alias option of its own.
27
- */
28
- export function resolverPlugin(
29
- config: GrimoireConfig,
30
- target: "server" | "browser",
31
- ): BunPlugin {
32
- const aliases = projectAliases(config);
33
- return {
34
- name: `grimoire-resolve-${target}`,
35
- setup(build) {
36
- if (target === "server") {
37
- // Bun's runtime plugins don't see static imports in onResolve;
38
- // virtual modules have to be registered by name. Aliases on the
39
- // server are rewritten by the SSR plugin (rewriteAliases).
40
- for (const specifier of ENV_SPECIFIERS) {
41
- build.module(specifier, () => ({
42
- contents: envModuleSource(specifier, "server"),
43
- loader: "js",
44
- }));
45
- }
46
- return;
47
- }
48
- build.onResolve({ filter: ENV_MODULE }, (args) => ({
49
- path: args.path,
50
- namespace: "grimoire-env",
51
- }));
52
- build.onLoad({ filter: /.*/, namespace: "grimoire-env" }, (args) => ({
53
- contents: envModuleSource(args.path, target),
54
- loader: "js",
55
- }));
56
- for (const [prefix, dir] of Object.entries(aliases)) {
57
- build.onResolve(
58
- { filter: new RegExp(`^${escapeRegExp(prefix)}(/|$)`) },
59
- (args) => {
60
- const file = resolveFile(join(dir, args.path.slice(prefix.length)));
61
- return file ? { path: file } : undefined;
62
- },
63
- );
64
- }
65
- },
66
- };
67
- }
68
-
69
- const ENV_SPECIFIERS = [
70
- "$env/static/public",
71
- "$env/static/private",
72
- "$env/dynamic/public",
73
- "$env/dynamic/private",
74
- ];
75
-
76
- const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
77
-
78
- /** Point aliased import specifiers in compiled code at their files. */
79
- export function rewriteAliases(
80
- code: string,
81
- aliases: Record<string, string>,
82
- ): string {
83
- const prefixes = Object.keys(aliases);
84
- if (prefixes.length === 0) return code;
85
- return code.replace(
86
- SPEC_RE,
87
- (match, keyword: string, quote: string, specifier: string) => {
88
- const prefix = prefixes.find(
89
- (p) => specifier === p || specifier.startsWith(`${p}/`),
90
- );
91
- if (!prefix) return match;
92
- const file = resolveFile(
93
- join(aliases[prefix]!, specifier.slice(prefix.length)),
94
- );
95
- // Forward slashes: this lands inside a JS string literal, where a
96
- // Windows path's backslashes would be read as escapes (\P → P).
97
- return file
98
- ? `${keyword}${quote}${file.replaceAll("\\", "/")}${quote}`
99
- : match;
100
- },
101
- );
102
- }
103
-
104
- let runtimeEntry: string | null = null;
105
-
106
- /**
107
- * Point server-compiled code's `@sigil-dev/runtime` imports at grimoire's own
108
- * copy of the runtime. The server's context root and the components' owners
109
- * live in that instance, so page code must share it; and a page file outside
110
- * the project's node_modules tree must still find it. Bun's runtime plugins
111
- * don't see static imports in onResolve, so this rewrites the specifier.
112
- */
113
- export function pinRuntime(code: string): string {
114
- if (!code.includes("@sigil-dev/runtime")) return code;
115
- runtimeEntry ??= Bun.resolveSync("@sigil-dev/runtime", import.meta.dir).replace(
116
- /\\/g,
117
- "/",
118
- );
119
- return code.replace(
120
- /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(["'])@sigil-dev\/runtime\2/g,
121
- (_m, lead: string) => `${lead}${JSON.stringify(runtimeEntry)}`,
122
- );
123
- }
1
+ import { isAbsolute, join } from "node:path";
2
+ import type { BunPlugin } from "bun";
3
+ import { resolveFile } from "../dev/resolve";
4
+ import { ENV_MODULE, envModuleSource } from "../env/modules";
5
+ import {
6
+ serverOnlyError,
7
+ serverOnlyPattern,
8
+ serverOnlyReason,
9
+ } from "../server-only";
10
+ import type { GrimoireConfig } from "../types";
11
+
12
+ /**
13
+ * Import prefixes → absolute directories: `$lib` for `src/lib` unless the
14
+ * config says otherwise, plus `GrimoireConfig.alias`.
15
+ */
16
+ export function projectAliases(
17
+ config: GrimoireConfig,
18
+ root = process.cwd(),
19
+ ): Record<string, string> {
20
+ const out: Record<string, string> = { $lib: join(root, "src/lib") };
21
+ for (const [prefix, target] of Object.entries(config.alias ?? {})) {
22
+ out[prefix] = isAbsolute(target) ? target : join(root, target);
23
+ }
24
+ return out;
25
+ }
26
+
27
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+
29
+ /**
30
+ * Resolves `$env/*` and aliased imports, for the browser builds (Bun.build)
31
+ * and for the server (Bun.plugin). Bun has no alias option of its own.
32
+ */
33
+ export function resolverPlugin(
34
+ config: GrimoireConfig,
35
+ target: "server" | "browser",
36
+ ): BunPlugin {
37
+ const aliases = projectAliases(config);
38
+ return {
39
+ name: `grimoire-resolve-${target}`,
40
+ setup(build) {
41
+ if (target === "server") {
42
+ // Bun's runtime plugins don't see static imports in onResolve;
43
+ // virtual modules have to be registered by name. Aliases on the
44
+ // server are rewritten by the SSR plugin (rewriteAliases).
45
+ for (const specifier of ENV_SPECIFIERS) {
46
+ build.module(specifier, () => ({
47
+ contents: envModuleSource(specifier, "server"),
48
+ loader: "js",
49
+ }));
50
+ }
51
+ return;
52
+ }
53
+ // Server code never reaches the browser bundle: a browser import
54
+ // of src/lib/server/, a plugin's server directory or a server file
55
+ // fails the build instead of shipping it.
56
+ const root = process.cwd();
57
+ build.onLoad(
58
+ { filter: serverOnlyPattern(root, config.plugins) },
59
+ (args) => {
60
+ const reason = serverOnlyReason(args.path, root, config.plugins);
61
+ if (reason) throw serverOnlyError(args.path, root, reason);
62
+ return undefined;
63
+ },
64
+ );
65
+ // The runtime is grimoire's own copy, as on the server: compiled
66
+ // route files import it from the project, which need not have it
67
+ // installed, and a second copy would be a second set of signals.
68
+ build.onResolve({ filter: /^@sigil-dev\/runtime$/ }, () => ({
69
+ path: runtimeEntry(),
70
+ }));
71
+ build.onResolve({ filter: ENV_MODULE }, (args) => ({
72
+ path: args.path,
73
+ namespace: "grimoire-env",
74
+ }));
75
+ build.onLoad({ filter: /.*/, namespace: "grimoire-env" }, (args) => ({
76
+ contents: envModuleSource(args.path, target),
77
+ loader: "js",
78
+ }));
79
+ for (const [prefix, dir] of Object.entries(aliases)) {
80
+ build.onResolve(
81
+ { filter: new RegExp(`^${escapeRegExp(prefix)}(/|$)`) },
82
+ (args) => {
83
+ const file = resolveFile(join(dir, args.path.slice(prefix.length)));
84
+ return file ? { path: file } : undefined;
85
+ },
86
+ );
87
+ }
88
+ },
89
+ };
90
+ }
91
+
92
+ const ENV_SPECIFIERS = [
93
+ "$env/static/public",
94
+ "$env/static/private",
95
+ "$env/dynamic/public",
96
+ "$env/dynamic/private",
97
+ ];
98
+
99
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
100
+
101
+ /** Point aliased import specifiers in compiled code at their files. */
102
+ export function rewriteAliases(
103
+ code: string,
104
+ aliases: Record<string, string>,
105
+ ): string {
106
+ const prefixes = Object.keys(aliases);
107
+ if (prefixes.length === 0) return code;
108
+ return code.replace(
109
+ SPEC_RE,
110
+ (match, keyword: string, quote: string, specifier: string) => {
111
+ const prefix = prefixes.find(
112
+ (p) => specifier === p || specifier.startsWith(`${p}/`),
113
+ );
114
+ if (!prefix) return match;
115
+ const file = resolveFile(
116
+ join(aliases[prefix]!, specifier.slice(prefix.length)),
117
+ );
118
+ // Forward slashes: this lands inside a JS string literal, where a
119
+ // Windows path's backslashes would be read as escapes (\P → P).
120
+ return file
121
+ ? `${keyword}${quote}${file.replaceAll("\\", "/")}${quote}`
122
+ : match;
123
+ },
124
+ );
125
+ }
126
+
127
+ let pinnedRuntime: string | null = null;
128
+
129
+ /** grimoire's copy of the runtime, the one every app runs. */
130
+ export function runtimeEntry(): string {
131
+ pinnedRuntime ??= Bun.resolveSync("@sigil-dev/runtime", import.meta.dir);
132
+ return pinnedRuntime;
133
+ }
134
+
135
+ /**
136
+ * Point server-compiled code's `@sigil-dev/runtime` imports at grimoire's own
137
+ * copy of the runtime. The server's context root and the components' owners
138
+ * live in that instance, so page code must share it; and a page file outside
139
+ * the project's node_modules tree must still find it. Bun's runtime plugins
140
+ * don't see static imports in onResolve, so this rewrites the specifier.
141
+ */
142
+ export function pinRuntime(code: string): string {
143
+ if (!code.includes("@sigil-dev/runtime")) return code;
144
+ const entry = runtimeEntry().replace(/\\/g, "/");
145
+ return code.replace(
146
+ /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(["'])@sigil-dev\/runtime\2/g,
147
+ (_m, lead: string) => `${lead}${JSON.stringify(entry)}`,
148
+ );
149
+ }
@@ -1,28 +1,28 @@
1
- import type { GrimoirePlugin, RenderContext } from "../types";
2
-
3
- /**
4
- * Run every plugin's `rewriteHtml` over a page response without buffering it.
5
- *
6
- * Each plugin registers its element handlers on one shared `HTMLRewriter`,
7
- * which then transforms the response body as a stream: the shell is rewritten
8
- * and flushed while later chunks (streamed data, deferred patches) are still
9
- * being produced. That is the whole difference from `onRouteRender`, which
10
- * needs the finished document as a string and so cannot stream.
11
- *
12
- * Only HTML bodies are touched. A redirect, a JSON action result or an empty
13
- * body is returned as it came.
14
- */
15
- export async function applyRewriters(
16
- response: Response,
17
- plugins: GrimoirePlugin[],
18
- context: RenderContext,
19
- ): Promise<Response> {
20
- const active = plugins.filter((p) => p.rewriteHtml);
21
- if (!active.length || response.body === null) return response;
22
- if (!(response.headers.get("content-type") ?? "").includes("text/html")) {
23
- return response;
24
- }
25
- const rewriter = new HTMLRewriter();
26
- for (const plugin of active) await plugin.rewriteHtml?.(rewriter, context);
27
- return rewriter.transform(response);
28
- }
1
+ import type { GrimoirePlugin, RenderContext } from "../types";
2
+
3
+ /**
4
+ * Run every plugin's `rewriteHtml` over a page response without buffering it.
5
+ *
6
+ * Each plugin registers its element handlers on one shared `HTMLRewriter`,
7
+ * which then transforms the response body as a stream: the shell is rewritten
8
+ * and flushed while later chunks (streamed data, deferred patches) are still
9
+ * being produced. That is the whole difference from `onRouteRender`, which
10
+ * needs the finished document as a string and so cannot stream.
11
+ *
12
+ * Only HTML bodies are touched. A redirect, a JSON action result or an empty
13
+ * body is returned as it came.
14
+ */
15
+ export async function applyRewriters(
16
+ response: Response,
17
+ plugins: GrimoirePlugin[],
18
+ context: RenderContext,
19
+ ): Promise<Response> {
20
+ const active = plugins.filter((p) => p.rewriteHtml);
21
+ if (!active.length || response.body === null) return response;
22
+ if (!(response.headers.get("content-type") ?? "").includes("text/html")) {
23
+ return response;
24
+ }
25
+ const rewriter = new HTMLRewriter();
26
+ for (const plugin of active) await plugin.rewriteHtml?.(rewriter, context);
27
+ return rewriter.transform(response);
28
+ }
@@ -61,13 +61,19 @@ export function startWarming(opts: {
61
61
  if (stopped) return;
62
62
  const t0 = performance.now();
63
63
  try {
64
- const res = await handle(new Request(new URL(path, origin), { headers }));
64
+ const res = await handle(
65
+ new Request(new URL(path, origin), { headers }),
66
+ );
65
67
  // drain the body: a streamed page and its deferred data only
66
68
  // finish (and only fill their caches) when someone reads it all
67
69
  await res.arrayBuffer();
68
- log(`warmed ${path} (${res.status}) in ${Math.round(performance.now() - t0)}ms`);
70
+ log(
71
+ `warmed ${path} (${res.status}) in ${Math.round(performance.now() - t0)}ms`,
72
+ );
69
73
  } catch (e) {
70
- log(`warming ${path} failed: ${e instanceof Error ? e.message : String(e)}`);
74
+ log(
75
+ `warming ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
76
+ );
71
77
  }
72
78
  }
73
79
  }
@@ -1,27 +1,27 @@
1
- /**
2
- * Adds headers to a response. Sets them in place when it can: rebuilding
3
- * from `response.body` would turn a body Bun types itself (a string, a
4
- * file) into a stream that is sent with no Content-Type, which browsers
5
- * treat as a download. A response whose headers are locked (one from
6
- * fetch) is rebuilt, keeping its type.
7
- */
8
- export function withHeaders(
9
- response: Response,
10
- set: Iterable<[string, string]>,
11
- append: Iterable<[string, string]> = [],
12
- ): Response {
13
- try {
14
- for (const [k, v] of set) response.headers.set(k, v);
15
- for (const [k, v] of append) response.headers.append(k, v);
16
- return response;
17
- } catch {
18
- const headers = new Headers(response.headers);
19
- for (const [k, v] of set) headers.set(k, v);
20
- for (const [k, v] of append) headers.append(k, v);
21
- return new Response(response.body, {
22
- status: response.status,
23
- statusText: response.statusText,
24
- headers,
25
- });
26
- }
27
- }
1
+ /**
2
+ * Adds headers to a response. Sets them in place when it can: rebuilding
3
+ * from `response.body` would turn a body Bun types itself (a string, a
4
+ * file) into a stream that is sent with no Content-Type, which browsers
5
+ * treat as a download. A response whose headers are locked (one from
6
+ * fetch) is rebuilt, keeping its type.
7
+ */
8
+ export function withHeaders(
9
+ response: Response,
10
+ set: Iterable<[string, string]>,
11
+ append: Iterable<[string, string]> = [],
12
+ ): Response {
13
+ try {
14
+ for (const [k, v] of set) response.headers.set(k, v);
15
+ for (const [k, v] of append) response.headers.append(k, v);
16
+ return response;
17
+ } catch {
18
+ const headers = new Headers(response.headers);
19
+ for (const [k, v] of set) headers.set(k, v);
20
+ for (const [k, v] of append) headers.append(k, v);
21
+ return new Response(response.body, {
22
+ status: response.status,
23
+ statusText: response.statusText,
24
+ headers,
25
+ });
26
+ }
27
+ }
@@ -1,5 +1,4 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { importConfig } from "../config-file";
3
2
  import type { GrimoireConfig, GrimoirePlugin, WorkerMode } from "../types";
4
3
  import { createServer } from "./index";
5
4
 
@@ -40,10 +39,7 @@ if (process.env.GRIMOIRE_INTERNAL_SECRET) {
40
39
  const cwd = process.cwd();
41
40
 
42
41
  // a config that fails to load must fail the worker, not run on defaults
43
- const configFile = join(cwd, "sigil.config.ts");
44
- const config: GrimoireConfig = existsSync(configFile)
45
- ? ((await import(configFile)).default ?? {})
46
- : {};
42
+ const config: GrimoireConfig = await importConfig(cwd);
47
43
 
48
44
  // Forced, not defaulted. The worker re-reads sigil.config.ts from disk
49
45
  // rather than trusting what the CLI passed, so a `dev: true` left in the
@@ -0,0 +1,78 @@
1
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
2
+ import { isServerOnly } from "./dev/resolve";
3
+ import type { GrimoirePlugin } from "./types";
4
+
5
+ /**
6
+ * Code that must never reach the browser: `src/lib/server/`, every
7
+ * directory a plugin declares with `serverOnly`, and server files by name
8
+ * (`+page.server.ts`, `+server.ts`, `hooks.server.ts`, `*.server.ts`).
9
+ *
10
+ * A browser import of one is an error, in dev and in the build, rather than
11
+ * a bundle carrying a database client and whatever secrets it reads.
12
+ */
13
+
14
+ let pluginDirs: readonly string[] = [];
15
+
16
+ /** The directories plugins declared, for the dev compiler, which has no config of its own. */
17
+ export function setServerOnlyPlugins(
18
+ plugins: readonly GrimoirePlugin<any>[],
19
+ ): void {
20
+ pluginDirs = plugins.flatMap((p) => p.serverOnly ?? []);
21
+ }
22
+
23
+ export function serverOnlyDirs(
24
+ root: string,
25
+ plugins?: readonly GrimoirePlugin<any>[],
26
+ ): string[] {
27
+ const declared = plugins
28
+ ? plugins.flatMap((p) => p.serverOnly ?? [])
29
+ : pluginDirs;
30
+ return [
31
+ join(root, "src/lib/server"),
32
+ ...declared.map((d) => (isAbsolute(d) ? d : resolve(root, d))),
33
+ ];
34
+ }
35
+
36
+ const rel = (root: string, p: string) => relative(root, p).replace(/\\/g, "/");
37
+
38
+ /** Why `file` is server-only, or undefined when the browser may have it. */
39
+ export function serverOnlyReason(
40
+ file: string,
41
+ root: string,
42
+ plugins?: readonly GrimoirePlugin<any>[],
43
+ ): string | undefined {
44
+ if (isServerOnly(file)) return "it is a server file";
45
+ for (const dir of serverOnlyDirs(root, plugins)) {
46
+ if (file.startsWith(dir + sep) || file.startsWith(`${dir}/`)) {
47
+ return `everything in ${rel(root, dir)}/ is server-only`;
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ export function serverOnlyError(
54
+ file: string,
55
+ root: string,
56
+ reason: string,
57
+ importer?: string,
58
+ ): Error {
59
+ return new Error(
60
+ `${rel(root, file)} can't be imported into browser code${importer ? ` (by ${rel(root, importer)})` : ""}: ${reason}. ` +
61
+ "Import it from server code — a +page.server.ts, +layout.server.ts, +server.ts, hooks.server.ts or another server-only file — and pass what the page needs through load().",
62
+ );
63
+ }
64
+
65
+ const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
+
67
+ /** One pattern for a bundler's onLoad: the server-only directories and file names. */
68
+ export function serverOnlyPattern(
69
+ root: string,
70
+ plugins?: readonly GrimoirePlugin<any>[],
71
+ ): RegExp {
72
+ const dirs = serverOnlyDirs(root, plugins).map((d) =>
73
+ d.replace(/\\/g, "/").split("/").map(escape).join("[\\\\/]"),
74
+ );
75
+ return new RegExp(
76
+ `^(?:${dirs.join("|")})[\\\\/]|(^|[\\\\/])(\\+page\\.server|\\+layout\\.server|\\+server|hooks\\.server)\\.[cm]?[jt]s$|\\.server\\.[cm]?[jt]sx?$`,
77
+ );
78
+ }