prunelle 0.6.0 → 0.7.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.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +15 -14
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +19 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +33 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +26 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +145 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +52 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +16 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +32 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. 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
+ }
@@ -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 mistake(`$hydrate on <${tag}>`, filename, 'only components can be islands; drop $hydrate, or move it onto a component tag')
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,52 @@
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 { BindingFacts } from './interactivity'
5
+ import type { CompilerWarning } from './mistakes'
6
+ import { unwrapTsExpr } from './shared'
7
+
8
+ function isFunction(node: Node | null | undefined): node is FunctionNode {
9
+ return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
10
+ }
11
+
12
+ // The functions a top-level statement declares: `function C`, `export default function`, `const C = () => ...`.
13
+ function declaredFunctions(stmt: Node): FunctionNode[] {
14
+ const decl = stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration' ? stmt.declaration : stmt
15
+ if (decl === null || decl === undefined)
16
+ return []
17
+ if (isFunction(decl))
18
+ return [decl]
19
+ if (decl.type !== 'VariableDeclaration')
20
+ return []
21
+ const found: FunctionNode[] = []
22
+ for (const d of decl.declarations) {
23
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
24
+ if (isFunction(init))
25
+ found.push(init)
26
+ }
27
+ return found
28
+ }
29
+
30
+ /** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
31
+ export function checkBodyPropsDestructure(program: Program, code: string, bindings: readonly BindingFacts[], filename: string, warnings: CompilerWarning[]): void {
32
+ const inBrowser = bindings.filter(b => b.fact !== undefined)
33
+ for (const stmt of program.body) {
34
+ if (!inBrowser.some(b => b.start >= stmt.start && b.end <= stmt.end))
35
+ continue
36
+ for (const fn of declaredFunctions(stmt)) {
37
+ const param = fn.params[0]
38
+ if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement')
39
+ continue
40
+ for (const inner of fn.body.body) {
41
+ if (inner.type !== 'VariableDeclaration')
42
+ continue
43
+ for (const d of inner.declarations) {
44
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
45
+ if (d.id.type !== 'ObjectPattern' || init?.type !== 'Identifier' || init.name !== param.name)
46
+ continue
47
+ 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.` })
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
@@ -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 {
@@ -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 { mistake } from './mistakes'
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 mistake(`$hydrate on <${tag}>`, filename, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`)
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
@@ -1,8 +1,8 @@
1
- // Persists the last dev build error, child crash, and recent runtime errors under `.prunelle-dev/last-errors.json`
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 { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
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.json')
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
- /** Reads `.prunelle-dev/last-errors.json` safely, returning `undefined` when missing or unreadable. */
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 parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
46
- if (typeof parsed !== 'object' || parsed === null)
48
+ const rec = JSON.parse(line) as Record<string, unknown>
49
+ if (typeof rec.at !== 'string')
47
50
  return undefined
48
- const rec = parsed as Record<string, unknown>
49
- const updatedAt = typeof rec.updatedAt === 'string' ? rec.updatedAt : new Date(0).toISOString()
50
- const buildError = typeof rec.buildError === 'string' && rec.buildError.length > 0 ? rec.buildError : undefined
51
- const crashError = typeof rec.crashError === 'string' && rec.crashError.length > 0 ? rec.crashError : undefined
52
- const runtimeErrors = Array.isArray(rec.runtimeErrors) ? rec.runtimeErrors.filter(isDevErrorEntry) : []
53
- return {
54
- updatedAt,
55
- ...(buildError !== undefined ? { buildError } : {}),
56
- ...(crashError !== undefined ? { crashError } : {}),
57
- runtimeErrors,
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
- function writeDevErrorLog(root: string, log: DevErrorLog): void {
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, payload, 'utf8')
121
+ writeFileSync(tmp, recordsOf(log).map(r => `${JSON.stringify(r)}\n`).join(''), 'utf8')
72
122
  renameSync(tmp, file)
73
123
  }
74
124
  catch {
75
- try {
76
- mkdirSync(dirname(file), { recursive: true })
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
- const now = new Date().toISOString()
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
- const now = new Date().toISOString()
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.json`, keeping the last 20 entries. */
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 now = new Date().toISOString()
117
- const log = loadOrCreateLog(root, now)
118
- log.runtimeErrors.push({
119
- kind: 'runtime',
120
- timestamp: now,
121
- message: entry.message,
122
- ...(entry.source !== undefined ? { source: entry.source } : {}),
123
- ...(entry.method !== undefined ? { method: entry.method } : {}),
124
- ...(entry.path !== undefined ? { path: entry.path } : {}),
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,26 @@
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
+
6
+ function hostnameOf(host: string): string | undefined {
7
+ return URL.canParse(`http://${host}`) ? new URL(`http://${host}`).hostname : undefined
8
+ }
9
+
10
+ /** Refuses with `421` a request whose `Host` is not loopback, `*.localhost`, an IP address, the bound `hostname` or the host of one of `origins`. */
11
+ export function createDevHostCheck(hostname: string | undefined, origins: readonly (string | undefined)[]): (request: Request) => Response | undefined {
12
+ const names = new Set<string>()
13
+ if (hostname !== undefined)
14
+ names.add(hostnameOf(hostname) ?? hostname)
15
+ for (const origin of origins) {
16
+ if (origin !== undefined && URL.canParse(origin))
17
+ names.add(new URL(origin).hostname)
18
+ }
19
+ return (request) => {
20
+ const host = request.headers.get('host') ?? ''
21
+ const name = hostnameOf(host)
22
+ if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
23
+ return undefined
24
+ 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' } })
25
+ }
26
+ }
package/src/dev/index.ts CHANGED
@@ -15,6 +15,7 @@ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
15
15
  import { createServer } from '../server/index'
16
16
  import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
17
17
  import { createModuleStore } from './modules'
18
+ import { createDevHostCheck } from './host-check'
18
19
  import { handleOpenEditorRequest } from './open-editor'
19
20
  import { DEV_CLIENT_IP_HEADER } from './protocol'
20
21
  import { createRebuildQueue } from './queue'
@@ -39,12 +40,12 @@ export interface DevServerOptions {
39
40
 
40
41
  const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
41
42
 
42
- /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.json` intact across child recycles. */
43
+ /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
43
44
  function cleanDevArtifacts(devRoot: string): void {
44
45
  if (!existsSync(devRoot))
45
46
  return
46
47
  for (const entry of readdirSync(devRoot)) {
47
- if (entry !== 'last-errors.json')
48
+ if (entry !== 'last-errors.jsonl')
48
49
  rmSync(join(devRoot, entry), { recursive: true, force: true })
49
50
  }
50
51
  }
@@ -73,12 +74,16 @@ async function handleAppFetch(
73
74
  state: {
74
75
  root: string
75
76
  unix: string | undefined
77
+ checkHost: ((request: Request) => Response | undefined) | undefined
76
78
  hub: ReturnType<typeof createReloadHub> | undefined
77
79
  reloadAssets: ReturnType<typeof makeDevReloadAssets>
78
80
  lastError: string | undefined
79
81
  app: PrunelleApp | undefined
80
82
  },
81
83
  ): Promise<Response> {
84
+ const refused = state.checkHost?.(request)
85
+ if (refused !== undefined)
86
+ return refused
82
87
  const { pathname } = new URL(request.url)
83
88
  if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
84
89
  srv.timeout(request, 0)
@@ -108,7 +113,7 @@ export async function devServer(options: DevServerOptions): Promise<{
108
113
  const root = resolve(options.root)
109
114
  const devRoot = join(root, '.prunelle-dev')
110
115
  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.json.
116
+ // Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.jsonl.
112
117
  cleanDevArtifacts(devRoot)
113
118
  let activeCfg = initialCfg
114
119
  let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
@@ -132,7 +137,7 @@ export async function devServer(options: DevServerOptions): Promise<{
132
137
  routesDir: options.routesDir,
133
138
  schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
134
139
  })
135
- const serverOptions = { root, dev: true, compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
140
+ const serverOptions = { root, dev: true, devHost: options.hostname ?? '127.0.0.1', compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
136
141
 
137
142
  let buildNum = 0
138
143
  let current: { app: PrunelleApp, outDir: string } | undefined
@@ -219,11 +224,13 @@ export async function devServer(options: DevServerOptions): Promise<{
219
224
  }
220
225
 
221
226
  const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
227
+ // Behind the supervisor's socket, the supervisor has checked the Host already.
228
+ const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
222
229
  const { server, url } = startDevHttpServer(
223
230
  options,
224
231
  runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
225
232
  initialCfg.port,
226
- (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, hub, reloadAssets, lastError, app: current?.app }),
233
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app }),
227
234
  )
228
235
  let stopPromise: Promise<void> | undefined
229
236
 
@@ -3,6 +3,7 @@
3
3
  import { existsSync, realpathSync } from 'node:fs'
4
4
  import { relative, resolve } from 'node:path'
5
5
  import { isInside } from '../build/is-inside'
6
+ import { verifyOrigin } from '../server/security'
6
7
 
7
8
  export const OPEN_EDITOR_SUBPATH = 'open-editor'
8
9
 
@@ -175,7 +176,7 @@ export function openInEditor(
175
176
  return { ok: true, command }
176
177
  }
177
178
 
178
- /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener. */
179
+ /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener: a same-origin JSON body only, so another site cannot open the editor with a form or a no-cors fetch. */
179
180
  export async function handleOpenEditorRequest(
180
181
  request: Request,
181
182
  root: string,
@@ -183,17 +184,20 @@ export async function handleOpenEditorRequest(
183
184
  ): Promise<Response> {
184
185
  if (request.method !== 'POST')
185
186
  return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
187
+ const originCheck = verifyOrigin(request)
188
+ if (!originCheck.ok)
189
+ return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
190
+ if (!(request.headers.get('content-type') ?? '').startsWith('application/json'))
191
+ return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
186
192
 
187
- let rawSrc = new URL(request.url).searchParams.get('src') ?? ''
188
- if (rawSrc === '') {
189
- try {
190
- const body = await request.json() as unknown
191
- if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
192
- rawSrc = (body as { src: string }).src
193
- }
194
- catch {
195
- return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
196
- }
193
+ let rawSrc = ''
194
+ try {
195
+ const body = await request.json() as unknown
196
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
197
+ rawSrc = (body as { src: string }).src
198
+ }
199
+ catch {
200
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
197
201
  }
198
202
 
199
203
  if (rawSrc.trim() === '')
@@ -12,6 +12,8 @@ export interface DevChildOptions {
12
12
  root: string
13
13
  routesDir?: string | undefined
14
14
  unix: string
15
+ /** The address the parent binds, which the app's plugins see as `api.devExposed`. */
16
+ hostname?: string | undefined
15
17
  maxRequestBodySize?: number | undefined
16
18
  maxRssMb?: number | undefined
17
19
  }