prunelle 0.6.0 → 0.7.1
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/LICENSE +21 -0
- package/llms.txt +48 -43
- package/package.json +4 -1
- package/src/a11y/declaration.ts +106 -72
- package/src/a11y/index.ts +59 -39
- package/src/a11y/rgaa-map.ts +95 -49
- package/src/build/bundle.ts +8 -4
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-plugin.ts +3 -1
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +25 -16
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +61 -18
- package/src/build/island-promote.ts +250 -0
- package/src/build/islands.ts +12 -201
- package/src/build/manifest.ts +4 -125
- package/src/build/plugin-host.ts +21 -8
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +97 -44
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +25 -3
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +2 -0
- package/src/cli/check-forms.ts +97 -48
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +2 -2
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +37 -7
- package/src/cli/commands.ts +35 -7
- package/src/cli/docs.ts +4 -3
- package/src/cli/inspect.ts +2 -1
- package/src/cli/mcp-tools.ts +7 -5
- package/src/cli/mcp.ts +1 -1
- package/src/cli/new.ts +14 -3
- package/src/cli/render.ts +14 -19
- package/src/cli/upgrade.ts +22 -5
- package/src/compiler/analyze.ts +27 -5
- package/src/compiler/cacheability.ts +2 -2
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +110 -4
- package/src/compiler/compliance-urls.ts +146 -0
- package/src/compiler/compliance.ts +168 -116
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/shared.ts +2 -2
- package/src/compiler/ssr.ts +2 -2
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +90 -64
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +17 -7
- package/src/dev/open-editor.ts +36 -12
- package/src/dev/protocol.ts +2 -0
- package/src/dev/supervisor.ts +8 -0
- package/src/dev/watchers.ts +27 -2
- package/src/dom/action.ts +4 -1
- package/src/dom/extras.ts +1 -2
- package/src/dom/index.ts +28 -6
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +60 -27
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +44 -1
- package/src/plugins/load.ts +4 -3
- package/src/plugins/public.ts +2 -2
- package/src/plugins/services.ts +3 -0
- package/src/plugins/types.ts +17 -2
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +38 -37
- package/src/server/action.ts +11 -127
- package/src/server/app-secret.ts +63 -0
- package/src/server/compress.ts +5 -1
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +3 -1
- package/src/server/form-schema.ts +1 -1
- package/src/server/health.ts +46 -15
- package/src/server/http.ts +56 -8
- package/src/server/index.ts +59 -30
- package/src/server/loader.ts +10 -2
- package/src/server/plugin-host.ts +3 -1
- package/src/server/public.ts +4 -3
- package/src/server/rate-limit.ts +52 -9
- package/src/server/route-cache.ts +26 -4
- package/src/server/route-table.ts +7 -3
- package/src/server/routing.ts +3 -87
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +73 -22
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +31 -5
- package/src/server/stream.ts +28 -6
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +20 -4
- package/src/ssr/index.ts +18 -0
- package/src/ssr/navigation.ts +2 -2
- package/src/style.ts +64 -1
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/src/routes/legal.tsx +10 -1
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +1 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Refuses a reactive primitive imported from another framework, with the prunelle name to write instead.
|
|
2
|
+
|
|
3
|
+
import { mistake } from './mistakes'
|
|
4
|
+
|
|
5
|
+
const REACT: Record<string, string> = {
|
|
6
|
+
useState: 'signal() from \'prunelle\' (count.value reads and writes it)',
|
|
7
|
+
useReducer: 'signal() from \'prunelle\' and a plain function that sets .value',
|
|
8
|
+
useEffect: 'effect() or onMount() from \'prunelle\'',
|
|
9
|
+
useLayoutEffect: 'effect() or onMount() from \'prunelle\'',
|
|
10
|
+
useMemo: 'computed() from \'prunelle\'',
|
|
11
|
+
useCallback: 'a plain function: a component runs once, so nothing is recreated',
|
|
12
|
+
useRef: 'a ref={el => ...} callback on the element, or a plain variable',
|
|
13
|
+
memo: 'nothing: a component runs once, so there is no re-render to skip',
|
|
14
|
+
useId: 'useId from \'prunelle\'',
|
|
15
|
+
useContext: 'useContext from \'prunelle\'',
|
|
16
|
+
createContext: 'createContext from \'prunelle\'',
|
|
17
|
+
Suspense: 'Suspense from \'prunelle\'',
|
|
18
|
+
Fragment: '<>...</>, which needs no import',
|
|
19
|
+
createRoot: 'nothing: prunelle hydrates islands itself',
|
|
20
|
+
hydrateRoot: 'nothing: prunelle hydrates islands itself',
|
|
21
|
+
render: 'nothing: prunelle renders pages and hydrates islands itself',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const SOLID: Record<string, string> = {
|
|
25
|
+
createSignal: 'signal() from \'prunelle\'',
|
|
26
|
+
createMemo: 'computed() from \'prunelle\'',
|
|
27
|
+
createEffect: 'effect() from \'prunelle\'',
|
|
28
|
+
createRenderEffect: 'effect() from \'prunelle\'',
|
|
29
|
+
createComputed: 'computed() from \'prunelle\'',
|
|
30
|
+
createRoot: 'root() from \'prunelle\'',
|
|
31
|
+
createSelector: 'selector() from \'prunelle\'',
|
|
32
|
+
createStore: 'store() from \'prunelle\'',
|
|
33
|
+
createContext: 'createContext from \'prunelle\'',
|
|
34
|
+
useContext: 'useContext from \'prunelle\'',
|
|
35
|
+
createUniqueId: 'useId from \'prunelle\'',
|
|
36
|
+
batch: 'batch from \'prunelle\'',
|
|
37
|
+
untrack: 'untrack from \'prunelle\'',
|
|
38
|
+
onMount: 'onMount from \'prunelle\'',
|
|
39
|
+
onCleanup: 'onCleanup from \'prunelle\'',
|
|
40
|
+
Show: 'a ternary or && in the JSX',
|
|
41
|
+
For: 'items.map(item => ...) in the JSX',
|
|
42
|
+
Index: 'items.map(item => ...) in the JSX',
|
|
43
|
+
Suspense: 'Suspense from \'prunelle\'',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const VUE: Record<string, string> = {
|
|
47
|
+
ref: 'signal() from \'prunelle\'',
|
|
48
|
+
shallowRef: 'signal() from \'prunelle\'',
|
|
49
|
+
reactive: 'store() from \'prunelle\'',
|
|
50
|
+
computed: 'computed from \'prunelle\'',
|
|
51
|
+
watch: 'effect() from \'prunelle\'',
|
|
52
|
+
watchEffect: 'effect() from \'prunelle\'',
|
|
53
|
+
onMounted: 'onMount() from \'prunelle\'',
|
|
54
|
+
onUnmounted: 'onCleanup() from \'prunelle\'',
|
|
55
|
+
provide: 'provideContext from \'prunelle\'',
|
|
56
|
+
inject: 'useContext from \'prunelle\'',
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const SVELTE: Record<string, string> = {
|
|
60
|
+
onMount: 'onMount from \'prunelle\'',
|
|
61
|
+
onDestroy: 'onCleanup from \'prunelle\'',
|
|
62
|
+
writable: 'signal() from \'prunelle\'',
|
|
63
|
+
readable: 'signal() from \'prunelle\'',
|
|
64
|
+
derived: 'computed() from \'prunelle\'',
|
|
65
|
+
setContext: 'provideContext from \'prunelle\'',
|
|
66
|
+
getContext: 'useContext from \'prunelle\'',
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const FOREIGN = new Map<string, Record<string, string>>([
|
|
70
|
+
['react', REACT],
|
|
71
|
+
['preact', REACT],
|
|
72
|
+
['preact/hooks', REACT],
|
|
73
|
+
['preact/compat', REACT],
|
|
74
|
+
['react-dom', REACT],
|
|
75
|
+
['react-dom/client', REACT],
|
|
76
|
+
['solid-js', SOLID],
|
|
77
|
+
['solid-js/store', SOLID],
|
|
78
|
+
['vue', VUE],
|
|
79
|
+
['svelte', SVELTE],
|
|
80
|
+
['svelte/store', SVELTE],
|
|
81
|
+
])
|
|
82
|
+
|
|
83
|
+
/** Throws on a name a React, Solid, Vue or Svelte app imports for what prunelle spells differently, naming the prunelle form. */
|
|
84
|
+
export function assertNoForeignImport(source: string, imported: string, filename: string): void {
|
|
85
|
+
const table = FOREIGN.get(source)
|
|
86
|
+
if (table !== undefined && Object.hasOwn(table, imported))
|
|
87
|
+
throw mistake(`import { ${imported} } from '${source}'`, filename, `prunelle has no ${source}; write ${table[imported]}`)
|
|
88
|
+
}
|
package/src/compiler/mistakes.ts
CHANGED
|
@@ -66,6 +66,13 @@ export function mistake(what: string, filename: string, fix: string): PrunelleMi
|
|
|
66
66
|
return new PrunelleMistake(`prunelle compiler: ${what} in ${filename}: ${fix}.`)
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/** `$hydrate` where nothing can hydrate: on an element (`component` false) or on a component that is not an island. The one wording the compiler, the build and `prunelle check` share. */
|
|
70
|
+
export function hydrateMistake(tag: string, filename: string, component: boolean): PrunelleMistake {
|
|
71
|
+
return mistake(`$hydrate on <${tag}>`, filename, component
|
|
72
|
+
? `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`
|
|
73
|
+
: 'only components can be islands; drop $hydrate, or move it onto a component tag')
|
|
74
|
+
}
|
|
75
|
+
|
|
69
76
|
let collected: PrunelleMistake[] | undefined
|
|
70
77
|
|
|
71
78
|
/** Runs one check, a mistake it throws placed at `start`. The build stops at the first mistake; while `collectMistakes` runs, the mistake is recorded and the caller goes on. */
|
|
@@ -112,6 +119,13 @@ export function serverOnlyTagError(filename: string, { tag, island, reason, offs
|
|
|
112
119
|
return err
|
|
113
120
|
}
|
|
114
121
|
|
|
122
|
+
/** The error for an Astro `---` block opening a file, at the first dash. */
|
|
123
|
+
export function frontmatterMistake(filename: string, start: number): PrunelleMistake {
|
|
124
|
+
const err = mistake('a --- frontmatter block', filename, 'prunelle files are plain TypeScript with no --- fence; write that code above the component, or inside it, and delete both --- lines')
|
|
125
|
+
err.start = start
|
|
126
|
+
return err
|
|
127
|
+
}
|
|
128
|
+
|
|
115
129
|
const KAY_SOURCE_RE = /^@kayjs\/(kay(?=\/|$))?/
|
|
116
130
|
|
|
117
131
|
/** Refuses an import of kay, the name prunelle had before: the app would load both. */
|
|
@@ -289,7 +303,7 @@ function checkElementAttribute(attr: JSXAttribute, tag: string, isCustomElement:
|
|
|
289
303
|
return
|
|
290
304
|
const name = attr.name.name
|
|
291
305
|
if (name === '$hydrate')
|
|
292
|
-
throw
|
|
306
|
+
throw hydrateMistake(tag, filename, false)
|
|
293
307
|
if (name.toLowerCase() === 'srcdoc')
|
|
294
308
|
throw mistake(`${name} on <${tag}>`, filename, 'prunelle blocks srcdoc for XSS safety; serve the document from a route and load it with src')
|
|
295
309
|
if (name === 'dangerouslySetInnerHTML')
|
|
@@ -373,6 +387,10 @@ export function checkMistakes(
|
|
|
373
387
|
const canonical = resolveTag(tag)
|
|
374
388
|
const isElement = tag !== '' && !isComponentTag(tag)
|
|
375
389
|
const isCustomElement = tag.includes('-')
|
|
390
|
+
if (tag === 'slot') {
|
|
391
|
+
const named = staticAttr(element.openingElement.attributes, 'name') !== undefined
|
|
392
|
+
guarded(element.start, () => { throw mistake('<slot>', filename, named ? 'prunelle has no slots, pass the named part as its own prop, <Card footer={<p />} />, and write {footer} where it goes' : 'prunelle has no slots, take children as a prop, function Card({ children }) { return <div>{children}</div> }, and write {children} where the content goes') })
|
|
393
|
+
}
|
|
376
394
|
if (canonical === 'Suspense') {
|
|
377
395
|
const children = filterMeaningfulChildren(element.children).length
|
|
378
396
|
if (children > 1)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Warns on `const { a } = props` in a component that runs in the browser: only a destructured parameter is rewritten to stay reactive, and a read of stable objects in the body can be meant.
|
|
2
|
+
|
|
3
|
+
import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
|
|
4
|
+
import type { CompilerWarning } from './mistakes'
|
|
5
|
+
import { containsJsx, unwrapTsExpr } from './shared'
|
|
6
|
+
|
|
7
|
+
function isFunction(node: Node | null | undefined): node is FunctionNode {
|
|
8
|
+
return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// The functions a top-level statement declares: `function C`, `export default function`, `const C = () => ...`.
|
|
12
|
+
function declaredFunctions(stmt: Node): FunctionNode[] {
|
|
13
|
+
const decl = stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration' ? stmt.declaration : stmt
|
|
14
|
+
if (decl === null || decl === undefined)
|
|
15
|
+
return []
|
|
16
|
+
if (isFunction(decl))
|
|
17
|
+
return [decl]
|
|
18
|
+
if (decl.type !== 'VariableDeclaration')
|
|
19
|
+
return []
|
|
20
|
+
const found: FunctionNode[] = []
|
|
21
|
+
for (const d of decl.declarations) {
|
|
22
|
+
const init = d.init === null ? undefined : unwrapTsExpr(d.init)
|
|
23
|
+
if (isFunction(init))
|
|
24
|
+
found.push(init)
|
|
25
|
+
}
|
|
26
|
+
return found
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
|
|
30
|
+
export function checkBodyPropsDestructure(
|
|
31
|
+
program: Program,
|
|
32
|
+
code: string,
|
|
33
|
+
browserSpans: readonly [number, number][],
|
|
34
|
+
jsxNodes: WeakSet<Node>,
|
|
35
|
+
filename: string,
|
|
36
|
+
warnings: CompilerWarning[],
|
|
37
|
+
): void {
|
|
38
|
+
if (browserSpans.length === 0)
|
|
39
|
+
return
|
|
40
|
+
for (const stmt of program.body) {
|
|
41
|
+
for (const fn of declaredFunctions(stmt)) {
|
|
42
|
+
if (!browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e))
|
|
43
|
+
continue
|
|
44
|
+
const rawParam = fn.params[0]
|
|
45
|
+
const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
|
|
46
|
+
if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement' || !containsJsx(fn.body, jsxNodes))
|
|
47
|
+
continue
|
|
48
|
+
for (const inner of fn.body.body) {
|
|
49
|
+
if (inner.type !== 'VariableDeclaration')
|
|
50
|
+
continue
|
|
51
|
+
for (const d of inner.declarations) {
|
|
52
|
+
const init = d.init === null ? undefined : unwrapTsExpr(d.init)
|
|
53
|
+
if (d.id.type !== 'ObjectPattern' || init?.type !== 'Identifier' || init.name !== param.name)
|
|
54
|
+
continue
|
|
55
|
+
warnings.push({ start: d.start, message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads the props once, so a change to them never reaches this component: destructure in the parameter list, (${code.slice(d.id.start, d.id.end)}), which stays reactive, or read props.<name> where it is used.` })
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/compiler/shared.ts
CHANGED
|
@@ -363,9 +363,9 @@ export interface PrunelleTagBinding {
|
|
|
363
363
|
specifiers: readonly { local: string, imported: string }[]
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
-
type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'Catch'
|
|
366
|
+
type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'ConsentBanner' | 'ConsentPreferences' | 'Catch'
|
|
367
367
|
|
|
368
|
-
const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'Catch'])
|
|
368
|
+
const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Catch'])
|
|
369
369
|
|
|
370
370
|
/** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag. */
|
|
371
371
|
export function resolvePrunelleTag(tag: string, imports: readonly PrunelleTagBinding[]): PrunelleTag | undefined {
|
package/src/compiler/ssr.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
|
|
|
13
13
|
import { analyzeModule, getExprContext, parseTsx } from './analyze'
|
|
14
14
|
import { walk } from './ast'
|
|
15
15
|
import { createDevSourceAttr } from './dev-source'
|
|
16
|
-
import {
|
|
16
|
+
import { hydrateMistake } from './mistakes'
|
|
17
17
|
import { alignLines, lineMarker, SourceEditor } from './patch'
|
|
18
18
|
import {
|
|
19
19
|
containsJsx,
|
|
@@ -443,7 +443,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
443
443
|
|
|
444
444
|
const islandInfo = islands?.get(tag)
|
|
445
445
|
if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
|
|
446
|
-
throw
|
|
446
|
+
throw hydrateMistake(tag, filename, true)
|
|
447
447
|
|
|
448
448
|
const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
|
|
449
449
|
const childMarkers = islandInfo === undefined && markersAt(node.start)
|
package/src/context.ts
CHANGED
|
@@ -21,6 +21,26 @@ export interface ConsentGateProps {
|
|
|
21
21
|
children?: PrunelleChild
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, English by default. */
|
|
25
|
+
export interface ConsentTexts {
|
|
26
|
+
accept?: string | undefined
|
|
27
|
+
refuse?: string | undefined
|
|
28
|
+
save?: string | undefined
|
|
29
|
+
/** Legend of the checkbox list (default: `'Cookies by purpose'`). */
|
|
30
|
+
legend?: string | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ConsentBannerProps extends ConsentTexts {
|
|
34
|
+
/** Heading of the banner (default: `'Cookies'`). */
|
|
35
|
+
title?: string | undefined
|
|
36
|
+
/** What the cookies are for; by default a sentence listing each category's label. */
|
|
37
|
+
children?: PrunelleChild
|
|
38
|
+
/** The cookie or privacy policy page, linked under the text. */
|
|
39
|
+
policyHref?: string | undefined
|
|
40
|
+
/** Text of the disclosure holding the checkboxes (default: `'Choose'`). */
|
|
41
|
+
choose?: string | undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
24
44
|
export interface CatchProps {
|
|
25
45
|
/** Rendered in place of `children` when they throw; a function gets the error and a `retry` that renders the children again (a no-op on the server). */
|
|
26
46
|
fallback?: PrunelleChild | ((error: unknown, retry: () => void) => PrunelleChild)
|
|
@@ -30,6 +50,8 @@ export interface CatchProps {
|
|
|
30
50
|
export interface ServerContextBridge {
|
|
31
51
|
region(props: RegionProps): PrunelleChild
|
|
32
52
|
consentGate(props: ConsentGateProps): PrunelleChild
|
|
53
|
+
consentBanner(props: ConsentBannerProps): PrunelleChild
|
|
54
|
+
consentPreferences(props: ConsentTexts): PrunelleChild
|
|
33
55
|
getContext(key: symbol): { found: true, value: unknown } | undefined
|
|
34
56
|
runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
|
|
35
57
|
nextId(): string | undefined
|
|
@@ -83,6 +105,18 @@ export function ConsentGate(props: ConsentGateProps): PrunelleChild {
|
|
|
83
105
|
return bridge !== undefined ? bridge.consentGate(props) : (props.fallback ?? null)
|
|
84
106
|
}
|
|
85
107
|
|
|
108
|
+
/** Asks for consent until the visitor accepts, refuses or picks categories: a zero-JS form posting to the consent endpoint, with Accept and Refuse given the same weight. Server-only. */
|
|
109
|
+
export function ConsentBanner(props: ConsentBannerProps): PrunelleChild {
|
|
110
|
+
const bridge = getServerBridge()
|
|
111
|
+
return bridge !== undefined ? bridge.consentBanner(props) : null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The visitor's current choice per category, to change or withdraw it as easily as it was given: put it on the cookie policy page or behind a footer link. Server-only. */
|
|
115
|
+
export function ConsentPreferences(props: ConsentTexts): PrunelleChild {
|
|
116
|
+
const bridge = getServerBridge()
|
|
117
|
+
return bridge !== undefined ? bridge.consentPreferences(props) : null
|
|
118
|
+
}
|
|
119
|
+
|
|
86
120
|
export interface Context<T> {
|
|
87
121
|
readonly id: symbol
|
|
88
122
|
readonly defaultValue: T
|
package/src/dev/error-log.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
// Persists the last dev build error, child crash, and recent runtime errors
|
|
1
|
+
// Persists the last dev build error, child crash, and recent runtime errors in an append-only journal, `.prunelle-dev/last-errors.jsonl`,
|
|
2
2
|
// so `prunelle mcp` (`dev_errors` tool) can inspect live dev failures without touching `dist/` or tracked files.
|
|
3
3
|
|
|
4
4
|
import type { ServerErrorInfo } from '../plugins/index'
|
|
5
|
-
import {
|
|
5
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
6
6
|
import { dirname, join, resolve } from 'node:path'
|
|
7
7
|
|
|
8
8
|
export interface DevErrorEntry {
|
|
@@ -22,9 +22,16 @@ export interface DevErrorLog {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
const MAX_RUNTIME_ERRORS = 20
|
|
25
|
+
/** Past this size the journal is folded back to its current state. */
|
|
26
|
+
const COMPACT_BYTES = 256 * 1024
|
|
27
|
+
|
|
28
|
+
/** One line of the journal: a build or crash message (none clears it), or a runtime error. */
|
|
29
|
+
type JournalRecord =
|
|
30
|
+
| { op: 'build' | 'crash', at: string, message?: string | undefined }
|
|
31
|
+
| { op: 'runtime', at: string, entry: DevErrorEntry }
|
|
25
32
|
|
|
26
33
|
function errorLogPath(root: string): string {
|
|
27
|
-
return join(resolve(root), '.prunelle-dev', 'last-errors.
|
|
34
|
+
return join(resolve(root), '.prunelle-dev', 'last-errors.jsonl')
|
|
28
35
|
}
|
|
29
36
|
|
|
30
37
|
function isDevErrorEntry(value: unknown): value is DevErrorEntry {
|
|
@@ -36,96 +43,115 @@ function isDevErrorEntry(value: unknown): value is DevErrorEntry {
|
|
|
36
43
|
&& typeof rec.message === 'string'
|
|
37
44
|
}
|
|
38
45
|
|
|
39
|
-
|
|
40
|
-
export function readDevErrorLog(root: string): DevErrorLog | undefined {
|
|
41
|
-
const file = errorLogPath(root)
|
|
42
|
-
if (!existsSync(file))
|
|
43
|
-
return undefined
|
|
46
|
+
function parseRecord(line: string): JournalRecord | undefined {
|
|
44
47
|
try {
|
|
45
|
-
const
|
|
46
|
-
if (typeof
|
|
48
|
+
const rec = JSON.parse(line) as Record<string, unknown>
|
|
49
|
+
if (typeof rec.at !== 'string')
|
|
47
50
|
return undefined
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
51
|
+
if ((rec.op === 'build' || rec.op === 'crash') && (rec.message === undefined || typeof rec.message === 'string'))
|
|
52
|
+
return { op: rec.op, at: rec.at, message: rec.message }
|
|
53
|
+
if (rec.op === 'runtime' && isDevErrorEntry(rec.entry))
|
|
54
|
+
return { op: 'runtime', at: rec.at, entry: rec.entry }
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// A line cut by a crash is skipped; the rest of the journal still reads.
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
return undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Folds the journal lines, in order, into the state they leave. */
|
|
64
|
+
function foldJournal(text: string): DevErrorLog | undefined {
|
|
65
|
+
let log: DevErrorLog | undefined
|
|
66
|
+
for (const line of text.split('\n')) {
|
|
67
|
+
const rec = line === '' ? undefined : parseRecord(line)
|
|
68
|
+
if (rec === undefined)
|
|
69
|
+
continue
|
|
70
|
+
log ??= { updatedAt: rec.at, runtimeErrors: [] }
|
|
71
|
+
log.updatedAt = rec.at
|
|
72
|
+
if (rec.op === 'runtime') {
|
|
73
|
+
log.runtimeErrors.push(rec.entry)
|
|
74
|
+
if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
|
|
75
|
+
log.runtimeErrors.shift()
|
|
76
|
+
continue
|
|
58
77
|
}
|
|
78
|
+
const key = rec.op === 'build' ? 'buildError' : 'crashError'
|
|
79
|
+
if (rec.message !== undefined && rec.message.length > 0)
|
|
80
|
+
log[key] = rec.message
|
|
81
|
+
else
|
|
82
|
+
delete log[key]
|
|
83
|
+
}
|
|
84
|
+
return log
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Reads `.prunelle-dev/last-errors.jsonl` safely, returning `undefined` when missing or unreadable. */
|
|
88
|
+
export function readDevErrorLog(root: string): DevErrorLog | undefined {
|
|
89
|
+
try {
|
|
90
|
+
return foldJournal(readFileSync(errorLogPath(root), 'utf8'))
|
|
59
91
|
}
|
|
60
92
|
catch {
|
|
61
93
|
return undefined
|
|
62
94
|
}
|
|
63
95
|
}
|
|
64
96
|
|
|
65
|
-
|
|
97
|
+
/** The records that rebuild `log`, for a compacted journal. */
|
|
98
|
+
function recordsOf(log: DevErrorLog): JournalRecord[] {
|
|
99
|
+
return [
|
|
100
|
+
...(log.buildError !== undefined ? [{ op: 'build', at: log.updatedAt, message: log.buildError } as const] : []),
|
|
101
|
+
...(log.crashError !== undefined ? [{ op: 'crash', at: log.updatedAt, message: log.crashError } as const] : []),
|
|
102
|
+
...log.runtimeErrors.map(entry => ({ op: 'runtime', at: entry.timestamp, entry }) as const),
|
|
103
|
+
]
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Appends one record. A short `O_APPEND` write lands whole, so two processes (the supervisor and its child) never overwrite each other.
|
|
108
|
+
* Only a journal past `COMPACT_BYTES` is rewritten, through a temp file.
|
|
109
|
+
*/
|
|
110
|
+
function appendRecord(root: string, rec: JournalRecord): void {
|
|
66
111
|
const file = errorLogPath(root)
|
|
67
|
-
const payload = JSON.stringify(log, null, 2)
|
|
68
112
|
try {
|
|
69
113
|
mkdirSync(dirname(file), { recursive: true })
|
|
114
|
+
appendFileSync(file, `${JSON.stringify(rec)}\n`, 'utf8')
|
|
115
|
+
if (statSync(file).size <= COMPACT_BYTES)
|
|
116
|
+
return
|
|
117
|
+
const log = foldJournal(readFileSync(file, 'utf8'))
|
|
118
|
+
if (log === undefined)
|
|
119
|
+
return
|
|
70
120
|
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
|
|
71
|
-
writeFileSync(tmp,
|
|
121
|
+
writeFileSync(tmp, recordsOf(log).map(r => `${JSON.stringify(r)}\n`).join(''), 'utf8')
|
|
72
122
|
renameSync(tmp, file)
|
|
73
123
|
}
|
|
74
124
|
catch {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
writeFileSync(file, payload, 'utf8')
|
|
78
|
-
}
|
|
79
|
-
catch {
|
|
80
|
-
return
|
|
81
|
-
}
|
|
125
|
+
// The log is a convenience for `prunelle mcp`; a read-only folder must not take the dev server down.
|
|
126
|
+
return
|
|
82
127
|
}
|
|
83
128
|
}
|
|
84
129
|
|
|
85
|
-
function loadOrCreateLog(root: string, now: string): DevErrorLog {
|
|
86
|
-
const existing = readDevErrorLog(root)
|
|
87
|
-
if (existing !== undefined)
|
|
88
|
-
return { ...existing, updatedAt: now, runtimeErrors: [...existing.runtimeErrors] }
|
|
89
|
-
return { updatedAt: now, runtimeErrors: [] }
|
|
90
|
-
}
|
|
91
|
-
|
|
92
130
|
/** Records or clears the active dev build error (passing `undefined` clears it after a successful build). */
|
|
93
131
|
export function recordDevBuildError(root: string, message: string | undefined): void {
|
|
94
|
-
|
|
95
|
-
const log = loadOrCreateLog(root, now)
|
|
96
|
-
if (message !== undefined && message.length > 0)
|
|
97
|
-
log.buildError = message
|
|
98
|
-
else
|
|
99
|
-
delete log.buildError
|
|
100
|
-
writeDevErrorLog(root, log)
|
|
132
|
+
appendRecord(root, { op: 'build', at: new Date().toISOString(), message })
|
|
101
133
|
}
|
|
102
134
|
|
|
103
135
|
/** Records or clears the active dev child crash message (passing `undefined` clears it once the child is ready). */
|
|
104
136
|
export function recordDevCrashError(root: string, message: string | undefined): void {
|
|
105
|
-
|
|
106
|
-
const log = loadOrCreateLog(root, now)
|
|
107
|
-
if (message !== undefined && message.length > 0)
|
|
108
|
-
log.crashError = message
|
|
109
|
-
else
|
|
110
|
-
delete log.crashError
|
|
111
|
-
writeDevErrorLog(root, log)
|
|
137
|
+
appendRecord(root, { op: 'crash', at: new Date().toISOString(), message })
|
|
112
138
|
}
|
|
113
139
|
|
|
114
|
-
/** Appends a runtime error to `.prunelle-dev/last-errors.
|
|
140
|
+
/** Appends a runtime error to `.prunelle-dev/last-errors.jsonl`; reading keeps the last 20. */
|
|
115
141
|
export function recordDevRuntimeError(root: string, entry: Omit<DevErrorEntry, 'kind' | 'timestamp'>): void {
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
142
|
+
const at = new Date().toISOString()
|
|
143
|
+
appendRecord(root, {
|
|
144
|
+
op: 'runtime',
|
|
145
|
+
at,
|
|
146
|
+
entry: {
|
|
147
|
+
kind: 'runtime',
|
|
148
|
+
timestamp: at,
|
|
149
|
+
message: entry.message,
|
|
150
|
+
...(entry.source !== undefined ? { source: entry.source } : {}),
|
|
151
|
+
...(entry.method !== undefined ? { method: entry.method } : {}),
|
|
152
|
+
...(entry.path !== undefined ? { path: entry.path } : {}),
|
|
153
|
+
},
|
|
125
154
|
})
|
|
126
|
-
if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
|
|
127
|
-
log.runtimeErrors = log.runtimeErrors.slice(-MAX_RUNTIME_ERRORS)
|
|
128
|
-
writeDevErrorLog(root, log)
|
|
129
155
|
}
|
|
130
156
|
|
|
131
157
|
function safePathname(rawUrl: string): string {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// A DNS-rebinding page reaches a dev server under the page's own domain name, so the dev server answers only the names it can be opened under.
|
|
2
|
+
|
|
3
|
+
const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
4
|
+
const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/
|
|
5
|
+
const BAD_HOST_CHARS_RE = /[@/?#\\\s\u0000-\u001F\u007F]/
|
|
6
|
+
|
|
7
|
+
function hostnameOf(host: string): string | undefined {
|
|
8
|
+
if (host.length === 0 || BAD_HOST_CHARS_RE.test(host) || !URL.canParse(`http://${host}`))
|
|
9
|
+
return undefined
|
|
10
|
+
const parsed = new URL(`http://${host}`)
|
|
11
|
+
if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '')
|
|
12
|
+
return undefined
|
|
13
|
+
return parsed.hostname
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Refuses with `421` a request whose `Host` is not loopback, `*.localhost`, an IP address, the bound `hostname` or the host of one of `origins`. */
|
|
17
|
+
export function createDevHostCheck(hostname: string | undefined, origins: readonly (string | undefined)[]): (request: Request) => Response | undefined {
|
|
18
|
+
const names = new Set<string>()
|
|
19
|
+
if (hostname !== undefined)
|
|
20
|
+
names.add(hostnameOf(hostname) ?? hostname)
|
|
21
|
+
for (const origin of origins) {
|
|
22
|
+
if (origin !== undefined && URL.canParse(origin))
|
|
23
|
+
names.add(new URL(origin).hostname)
|
|
24
|
+
}
|
|
25
|
+
return (request) => {
|
|
26
|
+
const host = request.headers.get('host') ?? ''
|
|
27
|
+
const name = hostnameOf(host)
|
|
28
|
+
if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
|
|
29
|
+
return undefined
|
|
30
|
+
return new Response(`prunelle dev: refused Host "${name ?? host}": a dev server answers only localhost, an IP address, its --host and the hosts of site and trustedOrigins in prunelle.config.ts, so that a page on another domain cannot reach it by DNS rebinding. Add the origin you open it under to trustedOrigins.\n`, { status: 421, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/dev/index.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { Server } from 'bun'
|
|
5
5
|
import type { BuildCacheStats } from '../build/graph'
|
|
6
6
|
import type { PrunelleApp } from '../server/index'
|
|
7
|
+
import type { TrustProxy } from '../server/security'
|
|
7
8
|
import type { RecycleReason } from './protocol'
|
|
8
9
|
import type { PendingBuild } from './queue'
|
|
9
10
|
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
@@ -15,6 +16,7 @@ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
|
|
|
15
16
|
import { createServer } from '../server/index'
|
|
16
17
|
import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
|
|
17
18
|
import { createModuleStore } from './modules'
|
|
19
|
+
import { createDevHostCheck } from './host-check'
|
|
18
20
|
import { handleOpenEditorRequest } from './open-editor'
|
|
19
21
|
import { DEV_CLIENT_IP_HEADER } from './protocol'
|
|
20
22
|
import { createRebuildQueue } from './queue'
|
|
@@ -39,12 +41,12 @@ export interface DevServerOptions {
|
|
|
39
41
|
|
|
40
42
|
const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
|
|
41
43
|
|
|
42
|
-
/** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.
|
|
44
|
+
/** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
|
|
43
45
|
function cleanDevArtifacts(devRoot: string): void {
|
|
44
46
|
if (!existsSync(devRoot))
|
|
45
47
|
return
|
|
46
48
|
for (const entry of readdirSync(devRoot)) {
|
|
47
|
-
if (entry !== 'last-errors.
|
|
49
|
+
if (entry !== 'last-errors.jsonl')
|
|
48
50
|
rmSync(join(devRoot, entry), { recursive: true, force: true })
|
|
49
51
|
}
|
|
50
52
|
}
|
|
@@ -73,23 +75,29 @@ async function handleAppFetch(
|
|
|
73
75
|
state: {
|
|
74
76
|
root: string
|
|
75
77
|
unix: string | undefined
|
|
78
|
+
checkHost: ((request: Request) => Response | undefined) | undefined
|
|
76
79
|
hub: ReturnType<typeof createReloadHub> | undefined
|
|
77
80
|
reloadAssets: ReturnType<typeof makeDevReloadAssets>
|
|
78
81
|
lastError: string | undefined
|
|
79
82
|
app: PrunelleApp | undefined
|
|
83
|
+
trustedOrigins: readonly string[] | undefined
|
|
84
|
+
trustProxy: TrustProxy | undefined
|
|
80
85
|
},
|
|
81
86
|
): Promise<Response> {
|
|
87
|
+
const refused = state.checkHost?.(request)
|
|
88
|
+
if (refused !== undefined)
|
|
89
|
+
return refused
|
|
82
90
|
const { pathname } = new URL(request.url)
|
|
83
91
|
if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
|
|
84
92
|
srv.timeout(request, 0)
|
|
85
93
|
return state.hub.events(request)
|
|
86
94
|
}
|
|
95
|
+
const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
|
|
87
96
|
if (pathname === state.reloadAssets.openEditorPath)
|
|
88
|
-
return handleOpenEditorRequest(request, state.root)
|
|
97
|
+
return handleOpenEditorRequest(request, state.root, { trustedOrigins: state.trustedOrigins, trustProxy: state.trustProxy, remoteIp: remoteIp ?? '' })
|
|
89
98
|
if (state.lastError !== undefined)
|
|
90
99
|
return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
|
|
91
100
|
|
|
92
|
-
const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
|
|
93
101
|
const res = await state.app!.handle(request, remoteIp)
|
|
94
102
|
const ct = res.headers.get('content-type') ?? ''
|
|
95
103
|
const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
|
|
@@ -108,7 +116,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
108
116
|
const root = resolve(options.root)
|
|
109
117
|
const devRoot = join(root, '.prunelle-dev')
|
|
110
118
|
const initialCfg = await loadConfig(root, { dev: true })
|
|
111
|
-
// Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.
|
|
119
|
+
// Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.jsonl.
|
|
112
120
|
cleanDevArtifacts(devRoot)
|
|
113
121
|
let activeCfg = initialCfg
|
|
114
122
|
let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
|
|
@@ -132,7 +140,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
132
140
|
routesDir: options.routesDir,
|
|
133
141
|
schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
|
|
134
142
|
})
|
|
135
|
-
const serverOptions = { root, dev: true, compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
|
|
143
|
+
const serverOptions = { root, dev: true, devHost: options.hostname ?? '127.0.0.1', compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
|
|
136
144
|
|
|
137
145
|
let buildNum = 0
|
|
138
146
|
let current: { app: PrunelleApp, outDir: string } | undefined
|
|
@@ -219,11 +227,13 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
219
227
|
}
|
|
220
228
|
|
|
221
229
|
const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
|
|
230
|
+
// Behind the supervisor's socket, the supervisor has checked the Host already.
|
|
231
|
+
const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
|
|
222
232
|
const { server, url } = startDevHttpServer(
|
|
223
233
|
options,
|
|
224
234
|
runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
|
|
225
235
|
initialCfg.port,
|
|
226
|
-
(request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, hub, reloadAssets, lastError, app: current?.app }),
|
|
236
|
+
(request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app, trustedOrigins: activeCfg.trustedOrigins, trustProxy: activeCfg.trustProxy }),
|
|
227
237
|
)
|
|
228
238
|
let stopPromise: Promise<void> | undefined
|
|
229
239
|
|