@mandujs/core 0.27.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/bundler/build.ts +26 -2
- package/src/bundler/generate-static-params.ts +290 -0
- package/src/bundler/index.ts +1 -0
- package/src/bundler/plugins/__tests__/block-generated-imports.test.ts +263 -0
- package/src/bundler/plugins/block-generated-imports.ts +155 -0
- package/src/bundler/plugins/index.ts +63 -0
- package/src/bundler/prerender.ts +242 -69
- package/src/bundler/types.ts +8 -0
- package/src/client/hydrate.ts +340 -0
- package/src/client/index.ts +11 -0
- package/src/config/mandu.ts +56 -0
- package/src/config/validate.ts +42 -0
- package/src/dev-error-overlay/__tests__/overlay-injector.test.ts +241 -0
- package/src/dev-error-overlay/index.ts +30 -0
- package/src/dev-error-overlay/overlay-client.ts +300 -0
- package/src/dev-error-overlay/overlay-injector.ts +243 -0
- package/src/dev-error-overlay/overlay-styles.ts +52 -0
- package/src/dev-error-overlay/types.ts +66 -0
- package/src/guard/check.ts +36 -6
- package/src/middleware/bridge.ts +147 -0
- package/src/middleware/compose.ts +134 -0
- package/src/middleware/define.ts +132 -0
- package/src/middleware/index.ts +76 -50
- package/src/router/fs-patterns.test.ts +96 -0
- package/src/router/fs-routes.ts +1 -0
- package/src/router/fs-scanner.ts +10 -1
- package/src/router/fs-types.ts +8 -0
- package/src/runtime/server.ts +310 -10
- package/src/runtime/ssr.ts +70 -2
- package/src/spec/schema.ts +6 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 18.α — Dev Error Overlay injector.
|
|
3
|
+
*
|
|
4
|
+
* Provides two surfaces:
|
|
5
|
+
*
|
|
6
|
+
* 1. `buildOverlayHeadTag(config)` — returns the `<style>` + `<script>`
|
|
7
|
+
* block to splice into the SSR `<head>`. Returns `""` in production
|
|
8
|
+
* mode, when the user opts out via `ManduConfig.dev.errorOverlay:
|
|
9
|
+
* false`, or when the environment signals a non-dev build. This is
|
|
10
|
+
* the canonical entry point called from `runtime/ssr.ts`.
|
|
11
|
+
*
|
|
12
|
+
* 2. `buildOverlayErrorEmbed(payload)` — serialises a
|
|
13
|
+
* `DevErrorPayload` into two tags (a `<script type="application/json">`
|
|
14
|
+
* the IIFE reads on DOMContentLoaded, plus a fire-and-forget event
|
|
15
|
+
* dispatch for late-mounted pages). Used by the 500-response path
|
|
16
|
+
* in `runtime/server.ts` so SSR crashes still render the overlay
|
|
17
|
+
* even when the React tree never produced output.
|
|
18
|
+
*
|
|
19
|
+
* Security posture:
|
|
20
|
+
* - Prod NEVER renders the overlay — triple-gated by env, explicit
|
|
21
|
+
* opt-in, and the injector's early-return.
|
|
22
|
+
* - The payload is escaped with the existing `escapeJsonForInlineScript`
|
|
23
|
+
* so `</script>` sequences cannot break out.
|
|
24
|
+
* - Stack traces contain absolute paths. Acceptable in dev; the
|
|
25
|
+
* injector refuses to emit when NODE_ENV=production regardless of
|
|
26
|
+
* any other flag.
|
|
27
|
+
*/
|
|
28
|
+
import { escapeJsonForInlineScript } from "../runtime/escape";
|
|
29
|
+
import { OVERLAY_CLIENT_SCRIPT } from "./overlay-client";
|
|
30
|
+
import { OVERLAY_STYLES } from "./overlay-styles";
|
|
31
|
+
import type { DevErrorPayload, DevErrorStackFrame } from "./types";
|
|
32
|
+
import {
|
|
33
|
+
OVERLAY_CUSTOM_EVENT,
|
|
34
|
+
OVERLAY_PAYLOAD_ELEMENT_ID,
|
|
35
|
+
} from "./types";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Config consumed by the injector. Mirrors `ManduConfig.dev.errorOverlay`
|
|
39
|
+
* plus an `isDev` escape hatch for callers that already know the runtime
|
|
40
|
+
* mode (e.g. the SSR pipeline computes this from `settings.isDev`).
|
|
41
|
+
*/
|
|
42
|
+
export interface DevOverlayInjectorConfig {
|
|
43
|
+
/** Explicit dev-mode signal. When `false`, the injector ALWAYS returns "". */
|
|
44
|
+
isDev: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* User-level opt-out from `ManduConfig.dev.errorOverlay`. `undefined`
|
|
47
|
+
* means "default" (enabled in dev). `false` disables; `true` is a
|
|
48
|
+
* no-op (dev is always enabled).
|
|
49
|
+
*/
|
|
50
|
+
enabled?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The absolute guard: production NEVER renders. Triple-checks:
|
|
55
|
+
* - `config.isDev === true` (caller authoritative)
|
|
56
|
+
* - `NODE_ENV !== "production"` (env authoritative; `isDev` can't lie)
|
|
57
|
+
* - user did not set `dev.errorOverlay: false`
|
|
58
|
+
*
|
|
59
|
+
* All three must pass. If any check fails we return `false` and the
|
|
60
|
+
* injector emits an empty string.
|
|
61
|
+
*/
|
|
62
|
+
export function shouldInjectOverlay(config: DevOverlayInjectorConfig): boolean {
|
|
63
|
+
if (config.enabled === false) return false;
|
|
64
|
+
if (!config.isDev) return false;
|
|
65
|
+
try {
|
|
66
|
+
if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "production") {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
// edge runtimes that sandbox `process` — fall through; isDev already
|
|
71
|
+
// passed and the caller asserted dev mode.
|
|
72
|
+
}
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Build the `<style>` + `<script>` block to inject into the SSR `<head>`.
|
|
78
|
+
* Returns `""` in production or when the user opts out.
|
|
79
|
+
*
|
|
80
|
+
* The returned string is expected to be spliced AS-IS into the
|
|
81
|
+
* `renderToHTML` head template — `escapeJsonForInlineScript` is NOT
|
|
82
|
+
* applied at this layer because the content is already safe (a verbatim
|
|
83
|
+
* IIFE string and a verbatim CSS string, both authored in this repo).
|
|
84
|
+
*/
|
|
85
|
+
export function buildOverlayHeadTag(config: DevOverlayInjectorConfig): string {
|
|
86
|
+
if (!shouldInjectOverlay(config)) return "";
|
|
87
|
+
// `id` attributes let tests + HMR locate the tags. The IIFE guards
|
|
88
|
+
// against double-mount via `OVERLAY_MOUNTED_FLAG`, so even if two
|
|
89
|
+
// copies somehow slip in the user-visible behaviour is still correct.
|
|
90
|
+
return (
|
|
91
|
+
`<style id="__mandu-dev-overlay-style">${OVERLAY_STYLES}</style>` +
|
|
92
|
+
`<script id="__mandu-dev-overlay-client">${OVERLAY_CLIENT_SCRIPT}</script>`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Thin wrapper called from `runtime/ssr.ts`. The function name matches
|
|
98
|
+
* the spec ("maybeInjectDevOverlay"). Returning a string keeps ssr.ts'
|
|
99
|
+
* template-literal interpolation ergonomic.
|
|
100
|
+
*/
|
|
101
|
+
export function maybeInjectDevOverlay(config: DevOverlayInjectorConfig): string {
|
|
102
|
+
return buildOverlayHeadTag(config);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Parse a raw `error.stack` string into frames on the server, mirroring
|
|
107
|
+
* the client-side parser. Server-side preparation means the overlay
|
|
108
|
+
* renders the structured list immediately — no regex cost on the main
|
|
109
|
+
* thread at page load.
|
|
110
|
+
*
|
|
111
|
+
* Deliberately simple: handles Chrome / V8 (` at fn (file:line:col)`)
|
|
112
|
+
* and Firefox (`fn@file:line:col`). Anything else becomes an
|
|
113
|
+
* `<anonymous>` frame carrying the raw line text, so information is
|
|
114
|
+
* never lost.
|
|
115
|
+
*/
|
|
116
|
+
export function parseStackFrames(stack: string | undefined | null): DevErrorStackFrame[] {
|
|
117
|
+
if (!stack) return [];
|
|
118
|
+
const lines = stack.split("\n");
|
|
119
|
+
const out: DevErrorStackFrame[] = [];
|
|
120
|
+
for (const raw of lines) {
|
|
121
|
+
const t = raw.trim();
|
|
122
|
+
if (!t) continue;
|
|
123
|
+
// Skip the first line if it's just "Error: message" (the header).
|
|
124
|
+
if (/^[A-Z][a-zA-Z]*(?:Error)?:/.test(t) && out.length === 0) continue;
|
|
125
|
+
let m = t.match(/^at\s+(.+?)\s+\((.+):(\d+):(\d+)\)$/);
|
|
126
|
+
if (m) {
|
|
127
|
+
out.push({
|
|
128
|
+
fn: m[1],
|
|
129
|
+
file: m[2],
|
|
130
|
+
line: Number.parseInt(m[3], 10),
|
|
131
|
+
column: Number.parseInt(m[4], 10),
|
|
132
|
+
raw,
|
|
133
|
+
});
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
m = t.match(/^at\s+(.+):(\d+):(\d+)$/);
|
|
137
|
+
if (m) {
|
|
138
|
+
out.push({
|
|
139
|
+
fn: "<anonymous>",
|
|
140
|
+
file: m[1],
|
|
141
|
+
line: Number.parseInt(m[2], 10),
|
|
142
|
+
column: Number.parseInt(m[3], 10),
|
|
143
|
+
raw,
|
|
144
|
+
});
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
m = t.match(/^(.*?)@(.+):(\d+):(\d+)$/);
|
|
148
|
+
if (m) {
|
|
149
|
+
out.push({
|
|
150
|
+
fn: m[1] || "<anonymous>",
|
|
151
|
+
file: m[2],
|
|
152
|
+
line: Number.parseInt(m[3], 10),
|
|
153
|
+
column: Number.parseInt(m[4], 10),
|
|
154
|
+
raw,
|
|
155
|
+
});
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
out.push({ fn: "<anonymous>", file: t, line: null, column: null, raw });
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Build a `DevErrorPayload` from a caught `Error`-like value. Safe
|
|
165
|
+
* against non-Error throws (strings, plain objects, undefined).
|
|
166
|
+
*/
|
|
167
|
+
export function buildPayloadFromError(
|
|
168
|
+
err: unknown,
|
|
169
|
+
extra: { kind?: DevErrorPayload["kind"]; routeId?: string; url?: string } = {},
|
|
170
|
+
): DevErrorPayload {
|
|
171
|
+
let name = "Error";
|
|
172
|
+
let message = "";
|
|
173
|
+
let stack = "";
|
|
174
|
+
if (err && typeof err === "object") {
|
|
175
|
+
const rec = err as { name?: unknown; message?: unknown; stack?: unknown };
|
|
176
|
+
name = typeof rec.name === "string" ? rec.name : "Error";
|
|
177
|
+
message = typeof rec.message === "string" ? rec.message : "";
|
|
178
|
+
stack = typeof rec.stack === "string" ? rec.stack : "";
|
|
179
|
+
} else if (typeof err === "string") {
|
|
180
|
+
message = err;
|
|
181
|
+
} else if (err !== null && err !== undefined) {
|
|
182
|
+
try { message = String(err); } catch { message = "<unserializable>"; }
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
name,
|
|
186
|
+
message,
|
|
187
|
+
frames: parseStackFrames(stack),
|
|
188
|
+
stack,
|
|
189
|
+
kind: extra.kind ?? "ssr",
|
|
190
|
+
timestamp: Date.now(),
|
|
191
|
+
routeId: extra.routeId,
|
|
192
|
+
url: extra.url,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Build the body-end embed tags for an SSR 500 response. The first tag
|
|
198
|
+
* carries the payload as JSON (the IIFE picks it up on
|
|
199
|
+
* DOMContentLoaded); the second tag is a defensive re-dispatch for
|
|
200
|
+
* pages that already fired DOMContentLoaded by the time the overlay
|
|
201
|
+
* mounts (possible when HMR re-runs the client bundle).
|
|
202
|
+
*
|
|
203
|
+
* Both tags are safe to splice verbatim — `escapeJsonForInlineScript`
|
|
204
|
+
* neutralises any `</script>` in the payload.
|
|
205
|
+
*/
|
|
206
|
+
export function buildOverlayErrorEmbed(payload: DevErrorPayload): string {
|
|
207
|
+
const json = escapeJsonForInlineScript(JSON.stringify(payload));
|
|
208
|
+
const dispatch = `(function(){try{var d=${json};window.dispatchEvent(new CustomEvent(${JSON.stringify(
|
|
209
|
+
OVERLAY_CUSTOM_EVENT,
|
|
210
|
+
)},{detail:d}));}catch(_){}})();`;
|
|
211
|
+
return (
|
|
212
|
+
`<script id="${OVERLAY_PAYLOAD_ELEMENT_ID}" type="application/json">${json}</script>` +
|
|
213
|
+
`<script>${dispatch}</script>`
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Produce a minimal HTML document for the SSR 500 surface in dev. The
|
|
219
|
+
* overlay client IIFE is inlined so the overlay renders even when the
|
|
220
|
+
* React tree never emitted a root — which is exactly when `createSSRErrorResponse`
|
|
221
|
+
* fires. Returns a complete `<!doctype html>` string; the server wraps
|
|
222
|
+
* it in a 500 `Response`.
|
|
223
|
+
*/
|
|
224
|
+
export function buildOverlayErrorHtml(payload: DevErrorPayload): string {
|
|
225
|
+
return (
|
|
226
|
+
`<!doctype html><html lang="en"><head><meta charset="UTF-8">` +
|
|
227
|
+
`<title>Mandu — ${escapeTitle(payload.name)}</title>` +
|
|
228
|
+
buildOverlayHeadTag({ isDev: true }) +
|
|
229
|
+
`</head><body><div id="root"></div>` +
|
|
230
|
+
buildOverlayErrorEmbed(payload) +
|
|
231
|
+
`</body></html>`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function escapeTitle(s: string): string {
|
|
236
|
+
return s.replace(/[<>&"']/g, (c) =>
|
|
237
|
+
c === "<" ? "<"
|
|
238
|
+
: c === ">" ? ">"
|
|
239
|
+
: c === "&" ? "&"
|
|
240
|
+
: c === "\"" ? """
|
|
241
|
+
: "'",
|
|
242
|
+
);
|
|
243
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 18.α — Dev Error Overlay styles.
|
|
3
|
+
*
|
|
4
|
+
* Scoped CSS string emitted inside a single `<style>` tag by the
|
|
5
|
+
* injector. Deliberately:
|
|
6
|
+
*
|
|
7
|
+
* - Prefix every selector with `.mandu-dev-overlay` so we never leak
|
|
8
|
+
* into the host page's stylesheet (no `*` or `body` selectors).
|
|
9
|
+
* - Inline all values — no Tailwind, no CSS vars from userland.
|
|
10
|
+
* - Use `system-ui, -apple-system, ...` + a monospace stack so the
|
|
11
|
+
* overlay works even on pages that have not yet loaded webfonts
|
|
12
|
+
* (broken SSR responses often haven't).
|
|
13
|
+
* - Hit contrast ratio ≥ 7:1 (WCAG AAA) for the text-on-backdrop
|
|
14
|
+
* combination: `#f4f4f5` on `rgba(10,10,10,0.94)` ≈ 14.2:1.
|
|
15
|
+
*
|
|
16
|
+
* The whole string weighs ~2.2 KB uncompressed. gzip ≈ 0.9 KB.
|
|
17
|
+
*/
|
|
18
|
+
export const OVERLAY_STYLES = `
|
|
19
|
+
.mandu-dev-overlay{position:fixed;inset:0;z-index:2147483647;background:rgba(10,10,10,0.94);color:#f4f4f5;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:13px;line-height:1.5;overflow:auto;padding:32px;box-sizing:border-box;-webkit-font-smoothing:antialiased}
|
|
20
|
+
.mandu-dev-overlay *,.mandu-dev-overlay *::before,.mandu-dev-overlay *::after{box-sizing:border-box}
|
|
21
|
+
.mandu-dev-overlay__panel{max-width:960px;margin:0 auto;background:#18181b;border:1px solid #3f3f46;border-radius:8px;box-shadow:0 20px 60px rgba(0,0,0,0.6);overflow:hidden}
|
|
22
|
+
.mandu-dev-overlay__header{display:flex;align-items:center;justify-content:space-between;padding:16px 24px;background:#27272a;border-bottom:1px solid #3f3f46}
|
|
23
|
+
.mandu-dev-overlay__title{display:flex;flex-direction:column;gap:4px}
|
|
24
|
+
.mandu-dev-overlay__kind{font-size:11px;text-transform:uppercase;letter-spacing:0.08em;color:#fca5a5;font-weight:600}
|
|
25
|
+
.mandu-dev-overlay__name{font-size:18px;color:#fafafa;font-weight:600;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
26
|
+
.mandu-dev-overlay__actions{display:flex;gap:8px}
|
|
27
|
+
.mandu-dev-overlay__btn{appearance:none;background:#3f3f46;border:1px solid #52525b;color:#fafafa;padding:6px 12px;border-radius:6px;font-family:inherit;font-size:12px;cursor:pointer;transition:background 120ms ease;font-weight:500}
|
|
28
|
+
.mandu-dev-overlay__btn:hover{background:#52525b}
|
|
29
|
+
.mandu-dev-overlay__btn:focus-visible{outline:2px solid #60a5fa;outline-offset:2px}
|
|
30
|
+
.mandu-dev-overlay__btn--primary{background:#2563eb;border-color:#1d4ed8}
|
|
31
|
+
.mandu-dev-overlay__btn--primary:hover{background:#1d4ed8}
|
|
32
|
+
.mandu-dev-overlay__body{padding:24px}
|
|
33
|
+
.mandu-dev-overlay__message{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;font-size:15px;color:#fafafa;margin:0 0 20px;white-space:pre-wrap;word-break:break-word;padding:12px 16px;background:#0a0a0a;border-left:3px solid #ef4444;border-radius:4px}
|
|
34
|
+
.mandu-dev-overlay__meta{display:flex;flex-wrap:wrap;gap:16px;margin-bottom:20px;padding:12px 16px;background:#0a0a0a;border-radius:6px;font-size:12px}
|
|
35
|
+
.mandu-dev-overlay__meta-item{display:flex;flex-direction:column;gap:2px}
|
|
36
|
+
.mandu-dev-overlay__meta-label{color:#a1a1aa;font-size:10px;text-transform:uppercase;letter-spacing:0.06em}
|
|
37
|
+
.mandu-dev-overlay__meta-value{color:#e4e4e7}
|
|
38
|
+
.mandu-dev-overlay__section-title{font-size:11px;text-transform:uppercase;letter-spacing:0.08em;color:#a1a1aa;margin:0 0 8px;font-weight:600}
|
|
39
|
+
.mandu-dev-overlay__frames{list-style:none;margin:0;padding:0;background:#0a0a0a;border-radius:6px;overflow:hidden}
|
|
40
|
+
.mandu-dev-overlay__frame{padding:10px 16px;border-bottom:1px solid #27272a;display:flex;flex-direction:column;gap:2px}
|
|
41
|
+
.mandu-dev-overlay__frame:last-child{border-bottom:none}
|
|
42
|
+
.mandu-dev-overlay__frame-fn{color:#fbbf24;font-weight:500}
|
|
43
|
+
.mandu-dev-overlay__frame-loc{color:#a1a1aa;font-size:12px}
|
|
44
|
+
.mandu-dev-overlay__frame-link{color:#93c5fd;text-decoration:none;cursor:pointer}
|
|
45
|
+
.mandu-dev-overlay__frame-link:hover{text-decoration:underline;color:#bfdbfe}
|
|
46
|
+
.mandu-dev-overlay__frame-link:focus-visible{outline:2px solid #60a5fa;outline-offset:1px;border-radius:2px}
|
|
47
|
+
.mandu-dev-overlay__stack{margin-top:16px;padding:12px 16px;background:#0a0a0a;border-radius:6px;max-height:240px;overflow:auto;white-space:pre-wrap;word-break:break-all;color:#d4d4d8;font-size:12px}
|
|
48
|
+
.mandu-dev-overlay__footer{padding:12px 24px;background:#0a0a0a;border-top:1px solid #27272a;font-size:11px;color:#71717a;text-align:center}
|
|
49
|
+
.mandu-dev-overlay__footer code{background:#27272a;padding:1px 6px;border-radius:3px;color:#a1a1aa}
|
|
50
|
+
.mandu-dev-overlay[hidden]{display:none}
|
|
51
|
+
@media (prefers-reduced-motion:reduce){.mandu-dev-overlay__btn{transition:none}}
|
|
52
|
+
`.trim();
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 18.α — Dev Error Overlay: shared type definitions.
|
|
3
|
+
*
|
|
4
|
+
* These types are shipped to both the server-side injector AND the
|
|
5
|
+
* client-side IIFE. Keep them plain-object friendly (no class instances,
|
|
6
|
+
* no bigints) because the payload is round-tripped through
|
|
7
|
+
* `JSON.stringify` when embedded into the 500-response HTML and read back
|
|
8
|
+
* via `JSON.parse(document.getElementById('__MANDU_ERROR__').textContent)`
|
|
9
|
+
* by `overlay-client.ts`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A single formatted stack frame. Parsed from `Error.stack` by the
|
|
14
|
+
* client IIFE; the server also pre-parses when emitting a 500 payload
|
|
15
|
+
* so the overlay can render immediately without running the regex on
|
|
16
|
+
* the main thread twice.
|
|
17
|
+
*/
|
|
18
|
+
export interface DevErrorStackFrame {
|
|
19
|
+
/** Function name (e.g. `MyComponent`), or `<anonymous>` when the frame is anonymous. */
|
|
20
|
+
fn: string;
|
|
21
|
+
/** Absolute or project-relative file path. Used to build the clickable `vscode://file/` link. */
|
|
22
|
+
file: string;
|
|
23
|
+
/** 1-based line number, or `null` when the stack frame did not carry one. */
|
|
24
|
+
line: number | null;
|
|
25
|
+
/** 1-based column number, or `null`. */
|
|
26
|
+
column: number | null;
|
|
27
|
+
/** The raw frame text as it appeared in `Error.stack` — preserved for copy-paste fidelity. */
|
|
28
|
+
raw: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The structured error payload that both the server (for SSR 500s) and
|
|
33
|
+
* the client (for `window.onerror` / `unhandledrejection`) marshall into
|
|
34
|
+
* the overlay. `kind` distinguishes the entry point so the UI can render
|
|
35
|
+
* a slightly different header ("SSR render failed" vs "Uncaught
|
|
36
|
+
* TypeError") without losing the rest of the data.
|
|
37
|
+
*/
|
|
38
|
+
export interface DevErrorPayload {
|
|
39
|
+
/** Error class name, e.g. `TypeError`. Falls back to `"Error"` when absent. */
|
|
40
|
+
name: string;
|
|
41
|
+
/** The message. May be empty. */
|
|
42
|
+
message: string;
|
|
43
|
+
/** Parsed frames — first frame is the top of the call stack. */
|
|
44
|
+
frames: DevErrorStackFrame[];
|
|
45
|
+
/** Raw `error.stack` string for "Copy for AI" and fallback rendering. */
|
|
46
|
+
stack: string;
|
|
47
|
+
/** Where the error surfaced. Used for UI copy. */
|
|
48
|
+
kind: "ssr" | "window" | "unhandled-rejection" | "manual";
|
|
49
|
+
/** Unix ms timestamp (client or server clock — both are best-effort in dev). */
|
|
50
|
+
timestamp: number;
|
|
51
|
+
/** Route id, when known (SSR errors carry it; client errors usually don't). */
|
|
52
|
+
routeId?: string;
|
|
53
|
+
/** URL pathname at error time — helpful when copying for AI triage. */
|
|
54
|
+
url?: string;
|
|
55
|
+
/** User-agent, for client-side errors only. The server never fills this. */
|
|
56
|
+
userAgent?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** HTML attribute name the injector uses for the `<script type="application/json">` payload tag. */
|
|
60
|
+
export const OVERLAY_PAYLOAD_ELEMENT_ID = "__MANDU_ERROR__";
|
|
61
|
+
|
|
62
|
+
/** `window` event name fired by user code / server embed to surface an error to the overlay. */
|
|
63
|
+
export const OVERLAY_CUSTOM_EVENT = "__MANDU_ERROR__";
|
|
64
|
+
|
|
65
|
+
/** Sentinel flag on `window` used by the client IIFE to avoid double-mount on HMR. */
|
|
66
|
+
export const OVERLAY_MOUNTED_FLAG = "__MANDU_OVERLAY_MOUNTED__";
|
package/src/guard/check.ts
CHANGED
|
@@ -12,6 +12,40 @@ export interface GuardCheckResult {
|
|
|
12
12
|
violations: GuardViolation[];
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Canonical docs URL for the `getGenerated()` runtime-registry pattern.
|
|
17
|
+
* Shared by the Guard `INVALID_GENERATED_IMPORT` rule and the bundler
|
|
18
|
+
* plugin `block-generated-imports` so both paths surface the same
|
|
19
|
+
* remediation target.
|
|
20
|
+
*/
|
|
21
|
+
export const GENERATED_IMPORT_DOCS_URL =
|
|
22
|
+
"https://mandujs.com/docs/architect/generated-access";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Build the user-facing message for a detected direct `__generated__/`
|
|
26
|
+
* import. `specifier` is the literal import string that tripped the
|
|
27
|
+
* guard (not the resolved path).
|
|
28
|
+
*
|
|
29
|
+
* This helper is the single source of truth for the message text — both
|
|
30
|
+
* the static Guard pass (`checkInvalidGeneratedImport`) and the bundler
|
|
31
|
+
* plugin (`blockGeneratedImports`) call through it so the two paths
|
|
32
|
+
* cannot drift.
|
|
33
|
+
*/
|
|
34
|
+
export function buildForbiddenGeneratedImportMessage(specifier: string): string {
|
|
35
|
+
return (
|
|
36
|
+
`Direct __generated__/ imports are forbidden: ${specifier}. ` +
|
|
37
|
+
`Use the runtime registry: see ${GENERATED_IMPORT_DOCS_URL}`
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Shared remediation hint. Points at `getGenerated()` from
|
|
43
|
+
* `@mandujs/core/runtime` and the decision-tree docs.
|
|
44
|
+
*/
|
|
45
|
+
export const FORBIDDEN_GENERATED_IMPORT_SUGGESTION =
|
|
46
|
+
"Import getGenerated() from @mandujs/core/runtime and read the generated artifact through the manifest. " +
|
|
47
|
+
`See ${GENERATED_IMPORT_DOCS_URL} for the decision tree.`;
|
|
48
|
+
|
|
15
49
|
function normalizeSeverity(level: GuardRuleSeverity): "error" | "warning" | "off" {
|
|
16
50
|
if (level === "warn") return "warning";
|
|
17
51
|
return level;
|
|
@@ -119,12 +153,8 @@ export async function checkInvalidGeneratedImport(
|
|
|
119
153
|
violations.push({
|
|
120
154
|
ruleId: GUARD_RULES.INVALID_GENERATED_IMPORT.id,
|
|
121
155
|
file: relativePath,
|
|
122
|
-
message:
|
|
123
|
-
|
|
124
|
-
`Use the runtime registry: see https://mandujs.com/docs/architect/generated-access`,
|
|
125
|
-
suggestion:
|
|
126
|
-
"Import getGenerated() from @mandujs/core/runtime and read the generated artifact through the manifest. " +
|
|
127
|
-
"See https://mandujs.com/docs/architect/generated-access for the decision tree.",
|
|
156
|
+
message: buildForbiddenGeneratedImportMessage(match[1]),
|
|
157
|
+
suggestion: FORBIDDEN_GENERATED_IMPORT_SUGGESTION,
|
|
128
158
|
});
|
|
129
159
|
}
|
|
130
160
|
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge wrappers — Phase 18.ε
|
|
3
|
+
*
|
|
4
|
+
* Adapters that expose Mandu's existing ctx-based middleware
|
|
5
|
+
* (`csrf` / `session` / `secure` / `rateLimit`) through the canonical
|
|
6
|
+
* request-level {@link Middleware} interface. Both call styles remain
|
|
7
|
+
* supported forever — these bridges exist purely so the new
|
|
8
|
+
* `compose(...)` API can slot in a familiar primitive without wiring
|
|
9
|
+
* boilerplate.
|
|
10
|
+
*
|
|
11
|
+
* The bridge pattern:
|
|
12
|
+
*
|
|
13
|
+
* 1. Build a throwaway `ManduContext` from the incoming Request so the
|
|
14
|
+
* ctx-based handler has the API surface it expects (`ctx.headers`,
|
|
15
|
+
* `ctx.cookies`, `ctx.forbidden()`, etc.).
|
|
16
|
+
* 2. Invoke the ctx-based handler.
|
|
17
|
+
* 3. If it returns a Response, treat that as a short-circuit.
|
|
18
|
+
* 4. Otherwise call `next()` to continue the chain, then apply any
|
|
19
|
+
* pending cookies the ctx-based handler wrote (e.g. CSRF cookie
|
|
20
|
+
* issuance, session commits) onto the downstream Response.
|
|
21
|
+
*
|
|
22
|
+
* Note: request-level composition happens BEFORE route matching, so the
|
|
23
|
+
* `ctx.params` is always `{}` at this stage. Middleware that depends on
|
|
24
|
+
* route params (unusual) should stick with `filling().use(...)`.
|
|
25
|
+
*/
|
|
26
|
+
import { defineMiddleware, type Middleware } from "./define";
|
|
27
|
+
import { ManduContext, type CookieManager } from "../filling/context";
|
|
28
|
+
import { csrf, type CsrfMiddlewareOptions } from "./csrf";
|
|
29
|
+
import {
|
|
30
|
+
session,
|
|
31
|
+
saveSession,
|
|
32
|
+
destroySession,
|
|
33
|
+
type SessionMiddlewareOptions,
|
|
34
|
+
} from "./session";
|
|
35
|
+
import {
|
|
36
|
+
secure as secureCtx,
|
|
37
|
+
type SecureMiddlewareOptions,
|
|
38
|
+
} from "./secure";
|
|
39
|
+
import {
|
|
40
|
+
rateLimit as rateLimitCtx,
|
|
41
|
+
type RateLimitMiddlewareOptions,
|
|
42
|
+
} from "./rate-limit";
|
|
43
|
+
|
|
44
|
+
// Re-export helpers so `saveSession` / `destroySession` are still reachable
|
|
45
|
+
// from call-sites that import from the bridge surface. Backward compat.
|
|
46
|
+
export { saveSession, destroySession };
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Copy pending Set-Cookie headers recorded on a `CookieManager` onto a
|
|
50
|
+
* downstream Response. Mirrors the end-of-request commit path used by
|
|
51
|
+
* `ManduContext.json()`/`ok()` so the ctx-based middleware's cookie
|
|
52
|
+
* writes (e.g. CSRF token issuance) survive the bridge.
|
|
53
|
+
*/
|
|
54
|
+
function applyCookies(cookies: CookieManager, response: Response): Response {
|
|
55
|
+
return cookies.hasPendingCookies() ? cookies.applyToResponse(response) : response;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Build a bridge middleware from a ctx-based `(ctx) => Response | void`
|
|
60
|
+
* handler. Short-circuits when the ctx handler returns a Response;
|
|
61
|
+
* otherwise continues the chain and folds the ctx's pending cookies
|
|
62
|
+
* back onto the final Response.
|
|
63
|
+
*/
|
|
64
|
+
function bridgeCtxMiddleware(
|
|
65
|
+
name: string,
|
|
66
|
+
build: () => (ctx: ManduContext) => Promise<Response | void> | Response | void
|
|
67
|
+
): Middleware {
|
|
68
|
+
const ctxHandler = build();
|
|
69
|
+
return defineMiddleware({
|
|
70
|
+
name,
|
|
71
|
+
async handler(req, next) {
|
|
72
|
+
const ctx = new ManduContext(req);
|
|
73
|
+
const early = await ctxHandler(ctx);
|
|
74
|
+
if (early instanceof Response) {
|
|
75
|
+
return applyCookies(ctx.cookies, early);
|
|
76
|
+
}
|
|
77
|
+
const response = await next();
|
|
78
|
+
return applyCookies(ctx.cookies, response);
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Request-level CSRF middleware — issues a double-submit cookie on safe
|
|
85
|
+
* methods and rejects with 403 when an unsafe request lacks a matching
|
|
86
|
+
* token. See {@link csrf} for the full semantics.
|
|
87
|
+
*/
|
|
88
|
+
export function csrfMiddleware(options: CsrfMiddlewareOptions): Middleware {
|
|
89
|
+
return bridgeCtxMiddleware("csrf", () => csrf(options));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Request-level session middleware — attaches a `Session` under the
|
|
94
|
+
* configured key. Commit remains caller-driven via {@link saveSession}
|
|
95
|
+
* / {@link destroySession}. See {@link session} for full semantics.
|
|
96
|
+
*
|
|
97
|
+
* Note: because composition runs pre-dispatch, the attached session is
|
|
98
|
+
* ONLY observable inside route handlers that read it via the same key
|
|
99
|
+
* (e.g. `ctx.get("session")`). The bridge's `ManduContext` is discarded
|
|
100
|
+
* after cookie-commit, so this bridge is strictly a convenience for
|
|
101
|
+
* session *hydration* + cookie roll-over; writes performed inside the
|
|
102
|
+
* route handler must still call `saveSession(routeCtx)` explicitly.
|
|
103
|
+
*/
|
|
104
|
+
export function sessionMiddleware(options: SessionMiddlewareOptions): Middleware {
|
|
105
|
+
return bridgeCtxMiddleware("session", () => session(options));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Request-level secure-headers middleware. Unlike the ctx-based
|
|
110
|
+
* `secure()` which uses `afterHandle` on a filling plugin, this bridge
|
|
111
|
+
* applies security headers via the `compose()` chain — it wraps the
|
|
112
|
+
* downstream Response and mutates its headers. See {@link secureCtx}
|
|
113
|
+
* for configuration.
|
|
114
|
+
*
|
|
115
|
+
* Implementation: calls the underlying `secure()` plugin's `afterHandle`
|
|
116
|
+
* hook directly against the downstream Response, skipping its
|
|
117
|
+
* `beforeHandle` (which only sets the CSP nonce for ctx-aware SSR — a
|
|
118
|
+
* request-level chain cannot thread a nonce into the route component,
|
|
119
|
+
* so nonce plumbing is intentionally out of scope for this bridge and
|
|
120
|
+
* users who need it should keep `.use(secure(...))` inline).
|
|
121
|
+
*/
|
|
122
|
+
export function secureMiddleware(options: SecureMiddlewareOptions = {}): Middleware {
|
|
123
|
+
const plugin = secureCtx(options);
|
|
124
|
+
return defineMiddleware({
|
|
125
|
+
name: "secure",
|
|
126
|
+
async handler(req, next) {
|
|
127
|
+
const response = await next();
|
|
128
|
+
const ctx = new ManduContext(req);
|
|
129
|
+
const afterHandle = plugin.afterHandle;
|
|
130
|
+
if (typeof afterHandle !== "function") return response;
|
|
131
|
+
const mutated = await afterHandle(ctx, response);
|
|
132
|
+
return mutated ?? response;
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Request-level rate-limit middleware. Shares the underlying
|
|
139
|
+
* `rateLimit()` store semantics (sliding window, pluggable store). When
|
|
140
|
+
* the limiter rejects, returns the configured 429 Response directly
|
|
141
|
+
* (short-circuits the chain).
|
|
142
|
+
*/
|
|
143
|
+
export function rateLimitMiddleware(
|
|
144
|
+
options: RateLimitMiddlewareOptions
|
|
145
|
+
): Middleware {
|
|
146
|
+
return bridgeCtxMiddleware("rate-limit", () => rateLimitCtx(options));
|
|
147
|
+
}
|