@sigil-dev/grimoire 0.9.20 → 0.9.22

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -114
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -745
  28. package/src/rendering/preload.ts +101 -95
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -194
  35. package/src/server/asset-cache.ts +57 -55
  36. package/src/server/build.ts +262 -249
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -0
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1022
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -0
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -113
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -69
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -0,0 +1,42 @@
1
+ import type { GrimoireConfig } from "../types";
2
+
3
+ /**
4
+ * Names that must be set before a server starts, from `env.required` in the
5
+ * config and from each plugin's `requiredEnv`.
6
+ *
7
+ * `$env/*` reads a missing variable as "", which turns an unset secret into a
8
+ * confusing failure somewhere far from the cause. Checking at boot moves the
9
+ * failure to the one place that can name the variable.
10
+ *
11
+ * Empty counts as missing: `FOO=` in a compose file is how a variable ends up
12
+ * "set" and useless.
13
+ */
14
+ export function missingEnv(
15
+ config: Pick<GrimoireConfig, "env" | "plugins">,
16
+ env: Record<string, string | undefined> = process.env,
17
+ ): { name: string; by: string }[] {
18
+ const wanted = new Map<string, string>();
19
+ for (const name of config.env?.required ?? [])
20
+ wanted.set(name, "sigil.config.ts");
21
+ for (const plugin of config.plugins ?? []) {
22
+ for (const name of plugin.requiredEnv ?? []) {
23
+ if (!wanted.has(name)) wanted.set(name, `plugin "${plugin.name}"`);
24
+ }
25
+ }
26
+ return [...wanted]
27
+ .filter(([name]) => !env[name])
28
+ .map(([name, by]) => ({ name, by }));
29
+ }
30
+
31
+ /** Throws one error listing every missing variable, so a deploy is fixed in one pass. */
32
+ export function assertRequiredEnv(
33
+ config: Pick<GrimoireConfig, "env" | "plugins">,
34
+ env: Record<string, string | undefined> = process.env,
35
+ ): void {
36
+ const missing = missingEnv(config, env);
37
+ if (!missing.length) return;
38
+ throw new Error(
39
+ `Missing required environment variable${missing.length > 1 ? "s" : ""}:\n` +
40
+ missing.map((m) => ` ${m.name} (required by ${m.by})`).join("\n"),
41
+ );
42
+ }
@@ -1,61 +1,61 @@
1
- import { readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
-
4
- export async function generateEnvTypes(
5
- projectRoot: string,
6
- outDir: string,
7
- ): Promise<void> {
8
- const envPath = join(projectRoot, ".env");
9
- let envContent = "";
10
- try {
11
- envContent = await readFile(envPath, "utf-8");
12
- } catch {
13
- // no .env file — generate empty types
14
- }
15
-
16
- const publicVars: string[] = [];
17
- const privateVars: string[] = [];
18
-
19
- for (const line of envContent.split("\n")) {
20
- const trimmed = line.trim();
21
- if (!trimmed || trimmed.startsWith("#")) continue;
22
- const eqIndex = trimmed.indexOf("=");
23
- if (eqIndex === -1) continue;
24
- const key = trimmed.slice(0, eqIndex).trim();
25
- if (!key) continue;
26
- if (key.startsWith("PUBLIC_")) {
27
- publicVars.push(key);
28
- } else {
29
- privateVars.push(key);
30
- }
31
- }
32
-
33
- const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
34
- declare module "$env/static/public" {
35
- \texport const env: Record<string, string>;
36
- ${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
37
- }
38
- `;
39
-
40
- const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
41
- declare module "$env/static/private" {
42
- \texport const env: Record<string, string>;
43
- ${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
44
- }
45
- `;
46
-
47
- const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
48
- declare module "$env/dynamic/public" {
49
- \texport const env: Record<string, string>;
50
- }
51
- declare module "$env/dynamic/private" {
52
- \texport const env: Record<string, string>;
53
- }
54
- `;
55
-
56
- await Promise.all([
57
- writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
58
- writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
59
- writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
60
- ]);
61
- }
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ export async function generateEnvTypes(
5
+ projectRoot: string,
6
+ outDir: string,
7
+ ): Promise<void> {
8
+ const envPath = join(projectRoot, ".env");
9
+ let envContent = "";
10
+ try {
11
+ envContent = await readFile(envPath, "utf-8");
12
+ } catch {
13
+ // no .env file — generate empty types
14
+ }
15
+
16
+ const publicVars: string[] = [];
17
+ const privateVars: string[] = [];
18
+
19
+ for (const line of envContent.split("\n")) {
20
+ const trimmed = line.trim();
21
+ if (!trimmed || trimmed.startsWith("#")) continue;
22
+ const eqIndex = trimmed.indexOf("=");
23
+ if (eqIndex === -1) continue;
24
+ const key = trimmed.slice(0, eqIndex).trim();
25
+ if (!key) continue;
26
+ if (key.startsWith("PUBLIC_")) {
27
+ publicVars.push(key);
28
+ } else {
29
+ privateVars.push(key);
30
+ }
31
+ }
32
+
33
+ const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
34
+ declare module "$env/static/public" {
35
+ \texport const env: Record<string, string>;
36
+ ${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
37
+ }
38
+ `;
39
+
40
+ const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
41
+ declare module "$env/static/private" {
42
+ \texport const env: Record<string, string>;
43
+ ${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
44
+ }
45
+ `;
46
+
47
+ const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
48
+ declare module "$env/dynamic/public" {
49
+ \texport const env: Record<string, string>;
50
+ }
51
+ declare module "$env/dynamic/private" {
52
+ \texport const env: Record<string, string>;
53
+ }
54
+ `;
55
+
56
+ await Promise.all([
57
+ writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
58
+ writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
59
+ writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
60
+ ]);
61
+ }
package/src/headers.ts CHANGED
@@ -1,114 +1,105 @@
1
- import type { GrimoirePlugin } from "./types";
2
-
3
- export interface SecurityHeadersConfig {
4
- /** Content-Security-Policy. Set false to omit. */
5
- contentSecurityPolicy?: string | false;
6
- /** X-Content-Type-Options. Default: "nosniff" */
7
- contentTypeOptions?: string | false;
8
- /** X-Frame-Options. Default: "DENY" */
9
- frameOptions?: string | false;
10
- /** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
11
- xssProtection?: string | false;
12
- /** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
13
- referrerPolicy?: string | false;
14
- /** Strict-Transport-Security. Set false to omit. */
15
- strictTransportSecurity?: string | false;
16
- /** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
17
- permissionsPolicy?: string | false;
18
- /** Per-route overrides: path pattern → partial config */
19
- routes?: Record<string, Partial<SecurityHeadersConfig>>;
20
- }
21
-
22
- const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
23
- contentSecurityPolicy:
24
- "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
25
- contentTypeOptions: "nosniff",
26
- frameOptions: "DENY",
27
- xssProtection: "0",
28
- referrerPolicy: "strict-origin-when-cross-origin",
29
- strictTransportSecurity: "max-age=31536000; includeSubDomains",
30
- permissionsPolicy: "camera=(), microphone=(), geolocation=()",
31
- };
32
-
33
- function resolveHeaders(
34
- config: SecurityHeadersConfig,
35
- pathname: string,
36
- ): Record<string, string> {
37
- // Start with defaults, overlay user config
38
- const merged = { ...DEFAULTS, ...config };
39
- delete (merged as any).routes;
40
-
41
- // Apply route overrides
42
- if (config.routes) {
43
- for (const pattern in config.routes) {
44
- if (pathname.startsWith(pattern)) {
45
- Object.assign(merged, config.routes[pattern]);
46
- }
47
- }
48
- }
49
-
50
- const headers: Record<string, string> = {};
51
-
52
- if (merged.contentSecurityPolicy !== false)
53
- headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
54
- if (merged.contentTypeOptions !== false)
55
- headers["X-Content-Type-Options"] = merged.contentTypeOptions;
56
- if (merged.frameOptions !== false)
57
- headers["X-Frame-Options"] = merged.frameOptions;
58
- if (merged.xssProtection !== false)
59
- headers["X-XSS-Protection"] = merged.xssProtection;
60
- if (merged.referrerPolicy !== false)
61
- headers["Referrer-Policy"] = merged.referrerPolicy;
62
- if (merged.strictTransportSecurity !== false)
63
- headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
64
- if (merged.permissionsPolicy !== false)
65
- headers["Permissions-Policy"] = merged.permissionsPolicy;
66
-
67
- return headers;
68
- }
69
-
70
- /**
71
- * Security headers plugin.
72
- * Adds standard security headers to all responses.
73
- *
74
- * Usage:
75
- *
76
- * import { securityHeaders } from "@sigil-dev/grimoire/headers";
77
- *
78
- * createServer({
79
- * plugins: [
80
- * securityHeaders({
81
- * // override defaults
82
- * frameOptions: "SAMEORIGIN",
83
- * // per-route
84
- * routes: {
85
- * "/admin": { contentSecurityPolicy: "default-src 'self'" },
86
- * },
87
- * }),
88
- * ],
89
- * });
90
- */
91
- export function securityHeaders(
92
- config: SecurityHeadersConfig = {},
93
- ): GrimoirePlugin {
94
- return {
95
- name: "grimoire-security-headers",
96
- async onRequest(req, next) {
97
- const res = await next();
98
- const url = new URL(req.url);
99
- const headers = resolveHeaders(config, url.pathname);
100
-
101
- // Clone response with security headers
102
- const newHeaders = new Headers(res.headers);
103
- for (const [key, value] of Object.entries(headers)) {
104
- newHeaders.set(key, value);
105
- }
106
-
107
- return new Response(res.body, {
108
- status: res.status,
109
- statusText: res.statusText,
110
- headers: newHeaders,
111
- });
112
- },
113
- };
114
- }
1
+ import { withHeaders } from "./server/with-headers";
2
+ import type { GrimoirePlugin } from "./types";
3
+
4
+ export interface SecurityHeadersConfig {
5
+ /** Content-Security-Policy. Set false to omit. */
6
+ contentSecurityPolicy?: string | false;
7
+ /** X-Content-Type-Options. Default: "nosniff" */
8
+ contentTypeOptions?: string | false;
9
+ /** X-Frame-Options. Default: "DENY" */
10
+ frameOptions?: string | false;
11
+ /** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
12
+ xssProtection?: string | false;
13
+ /** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
14
+ referrerPolicy?: string | false;
15
+ /** Strict-Transport-Security. Set false to omit. */
16
+ strictTransportSecurity?: string | false;
17
+ /** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
18
+ permissionsPolicy?: string | false;
19
+ /** Per-route overrides: path pattern → partial config */
20
+ routes?: Record<string, Partial<SecurityHeadersConfig>>;
21
+ }
22
+
23
+ const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
24
+ contentSecurityPolicy:
25
+ "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
26
+ contentTypeOptions: "nosniff",
27
+ frameOptions: "DENY",
28
+ xssProtection: "0",
29
+ referrerPolicy: "strict-origin-when-cross-origin",
30
+ strictTransportSecurity: "max-age=31536000; includeSubDomains",
31
+ permissionsPolicy: "camera=(), microphone=(), geolocation=()",
32
+ };
33
+
34
+ function resolveHeaders(
35
+ config: SecurityHeadersConfig,
36
+ pathname: string,
37
+ ): Record<string, string> {
38
+ // Start with defaults, overlay user config
39
+ const merged = { ...DEFAULTS, ...config };
40
+ delete (merged as any).routes;
41
+
42
+ // Apply route overrides
43
+ if (config.routes) {
44
+ for (const pattern in config.routes) {
45
+ if (pathname.startsWith(pattern)) {
46
+ Object.assign(merged, config.routes[pattern]);
47
+ }
48
+ }
49
+ }
50
+
51
+ const headers: Record<string, string> = {};
52
+
53
+ if (merged.contentSecurityPolicy !== false)
54
+ headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
55
+ if (merged.contentTypeOptions !== false)
56
+ headers["X-Content-Type-Options"] = merged.contentTypeOptions;
57
+ if (merged.frameOptions !== false)
58
+ headers["X-Frame-Options"] = merged.frameOptions;
59
+ if (merged.xssProtection !== false)
60
+ headers["X-XSS-Protection"] = merged.xssProtection;
61
+ if (merged.referrerPolicy !== false)
62
+ headers["Referrer-Policy"] = merged.referrerPolicy;
63
+ if (merged.strictTransportSecurity !== false)
64
+ headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
65
+ if (merged.permissionsPolicy !== false)
66
+ headers["Permissions-Policy"] = merged.permissionsPolicy;
67
+
68
+ return headers;
69
+ }
70
+
71
+ /**
72
+ * Security headers plugin.
73
+ * Adds standard security headers to all responses.
74
+ *
75
+ * Usage:
76
+ *
77
+ * import { securityHeaders } from "@sigil-dev/grimoire/headers";
78
+ *
79
+ * createServer({
80
+ * plugins: [
81
+ * securityHeaders({
82
+ * // override defaults
83
+ * frameOptions: "SAMEORIGIN",
84
+ * // per-route
85
+ * routes: {
86
+ * "/admin": { contentSecurityPolicy: "default-src 'self'" },
87
+ * },
88
+ * }),
89
+ * ],
90
+ * });
91
+ */
92
+ export function securityHeaders(
93
+ config: SecurityHeadersConfig = {},
94
+ ): GrimoirePlugin {
95
+ return {
96
+ name: "grimoire-security-headers",
97
+ async onRequest(req, next) {
98
+ const res = await next();
99
+ const url = new URL(req.url);
100
+ const headers = resolveHeaders(config, url.pathname);
101
+
102
+ return withHeaders(res, Object.entries(headers));
103
+ },
104
+ };
105
+ }
@@ -1,117 +1,117 @@
1
- // packages/grimoire/src/logger/transports.ts
2
-
3
- import { appendFileSync } from "node:fs";
4
- import type { LogEntry, LogTransport } from "./types.ts";
5
-
6
- // ── colours (only applied when stdout is a TTY) ──────────────────────────────
7
-
8
- const isTTY = process.stdout.isTTY;
9
- const c = isTTY
10
- ? {
11
- reset: "\x1b[0m",
12
- dim: "\x1b[2m",
13
- bold: "\x1b[1m",
14
- debug: "\x1b[90m", // grey
15
- info: "\x1b[36m", // cyan
16
- warn: "\x1b[33m", // yellow
17
- error: "\x1b[31m", // red
18
- fatal: "\x1b[35m", // magenta
19
- scope: "\x1b[34m", // blue
20
- req: "\x1b[32m", // green
21
- }
22
- : (Object.fromEntries(
23
- [
24
- "reset",
25
- "dim",
26
- "bold",
27
- "debug",
28
- "info",
29
- "warn",
30
- "error",
31
- "fatal",
32
- "scope",
33
- "req",
34
- ].map((k) => [k, ""]),
35
- ) as Record<string, string>);
36
-
37
- const LEVEL_LABEL: Record<string, string> = {
38
- debug: "DBG",
39
- info: "INF",
40
- warn: "WRN",
41
- error: "ERR",
42
- fatal: "FTL",
43
- };
44
-
45
- function ts(timestamp: number): string {
46
- return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
47
- }
48
-
49
- function formatData(data: unknown): string {
50
- if (data === undefined) return "";
51
- if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
52
- if (typeof data !== "object" || data === null) return ` ${String(data)}`;
53
-
54
- // flat key=value for simple objects, JSON block only for nested/complex
55
- const entries = Object.entries(data as Record<string, unknown>);
56
- const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
57
- if (isFlat) {
58
- return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
59
- }
60
- // nested — indent but don't pretty-print the whole thing
61
- return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
62
- }
63
-
64
- // ── ConsoleTransport ─────────────────────────────────────────────────────────
65
-
66
- export class ConsoleTransport implements LogTransport {
67
- write(entry: LogEntry) {
68
- const levelColor = c[entry.level] ?? c.info;
69
- const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
70
-
71
- const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
72
- const requestId = entry.requestId
73
- ? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
74
- : "";
75
- const scope = `${c.scope}${entry.scope}${c.reset}`;
76
- const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
77
- const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
78
- const msg = entry.message;
79
- const data = formatData(entry.data);
80
-
81
- const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
82
-
83
- if (entry.level === "error" || entry.level === "fatal") {
84
- process.stderr.write(`${line}\n`);
85
- } else {
86
- process.stdout.write(`${line}\n`);
87
- }
88
- }
89
- }
90
-
91
- // ── FileTransport ────────────────────────────────────────────────────────────
92
- // Writes newline-delimited JSON for ingestion by log collectors.
93
-
94
- export class FileTransport implements LogTransport {
95
- constructor(private path: string) {}
96
-
97
- write(entry: LogEntry) {
98
- try {
99
- appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
100
- } catch {
101
- // if the file write fails we can't really do anything useful
102
- }
103
- }
104
- }
105
-
106
- // ── NullTransport ────────────────────────────────────────────────────────────
107
- // For tests — captures entries instead of printing them.
108
-
109
- export class NullTransport implements LogTransport {
110
- readonly entries: LogEntry[] = [];
111
- write(entry: LogEntry) {
112
- this.entries.push(entry);
113
- }
114
- clear() {
115
- this.entries.length = 0;
116
- }
117
- }
1
+ // packages/grimoire/src/logger/transports.ts
2
+
3
+ import { appendFileSync } from "node:fs";
4
+ import type { LogEntry, LogTransport } from "./types.ts";
5
+
6
+ // ── colours (only applied when stdout is a TTY) ──────────────────────────────
7
+
8
+ const isTTY = process.stdout.isTTY;
9
+ const c = isTTY
10
+ ? {
11
+ reset: "\x1b[0m",
12
+ dim: "\x1b[2m",
13
+ bold: "\x1b[1m",
14
+ debug: "\x1b[90m", // grey
15
+ info: "\x1b[36m", // cyan
16
+ warn: "\x1b[33m", // yellow
17
+ error: "\x1b[31m", // red
18
+ fatal: "\x1b[35m", // magenta
19
+ scope: "\x1b[34m", // blue
20
+ req: "\x1b[32m", // green
21
+ }
22
+ : (Object.fromEntries(
23
+ [
24
+ "reset",
25
+ "dim",
26
+ "bold",
27
+ "debug",
28
+ "info",
29
+ "warn",
30
+ "error",
31
+ "fatal",
32
+ "scope",
33
+ "req",
34
+ ].map((k) => [k, ""]),
35
+ ) as Record<string, string>);
36
+
37
+ const LEVEL_LABEL: Record<string, string> = {
38
+ debug: "DBG",
39
+ info: "INF",
40
+ warn: "WRN",
41
+ error: "ERR",
42
+ fatal: "FTL",
43
+ };
44
+
45
+ function ts(timestamp: number): string {
46
+ return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
47
+ }
48
+
49
+ function formatData(data: unknown): string {
50
+ if (data === undefined) return "";
51
+ if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
52
+ if (typeof data !== "object" || data === null) return ` ${String(data)}`;
53
+
54
+ // flat key=value for simple objects, JSON block only for nested/complex
55
+ const entries = Object.entries(data as Record<string, unknown>);
56
+ const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
57
+ if (isFlat) {
58
+ return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
59
+ }
60
+ // nested — indent but don't pretty-print the whole thing
61
+ return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
62
+ }
63
+
64
+ // ── ConsoleTransport ─────────────────────────────────────────────────────────
65
+
66
+ export class ConsoleTransport implements LogTransport {
67
+ write(entry: LogEntry) {
68
+ const levelColor = c[entry.level] ?? c.info;
69
+ const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
70
+
71
+ const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
72
+ const requestId = entry.requestId
73
+ ? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
74
+ : "";
75
+ const scope = `${c.scope}${entry.scope}${c.reset}`;
76
+ const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
77
+ const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
78
+ const msg = entry.message;
79
+ const data = formatData(entry.data);
80
+
81
+ const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
82
+
83
+ if (entry.level === "error" || entry.level === "fatal") {
84
+ process.stderr.write(`${line}\n`);
85
+ } else {
86
+ process.stdout.write(`${line}\n`);
87
+ }
88
+ }
89
+ }
90
+
91
+ // ── FileTransport ────────────────────────────────────────────────────────────
92
+ // Writes newline-delimited JSON for ingestion by log collectors.
93
+
94
+ export class FileTransport implements LogTransport {
95
+ constructor(private path: string) {}
96
+
97
+ write(entry: LogEntry) {
98
+ try {
99
+ appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
100
+ } catch {
101
+ // if the file write fails we can't really do anything useful
102
+ }
103
+ }
104
+ }
105
+
106
+ // ── NullTransport ────────────────────────────────────────────────────────────
107
+ // For tests — captures entries instead of printing them.
108
+
109
+ export class NullTransport implements LogTransport {
110
+ readonly entries: LogEntry[] = [];
111
+ write(entry: LogEntry) {
112
+ this.entries.push(entry);
113
+ }
114
+ clear() {
115
+ this.entries.length = 0;
116
+ }
117
+ }