prunelle 0.1.1 → 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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -6,17 +6,17 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
6
6
  return config
7
7
  }
8
8
 
9
- /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`). */
9
+ /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`, `autoPrerender`). */
10
10
  export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRuntimeConfig {
11
11
  if (config === undefined)
12
12
  return {}
13
- const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, ...runtime } = config
13
+ const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, autoPrerender: _ap, ...runtime } = config
14
14
  return runtime
15
15
  }
16
16
 
17
17
  // Typed as records so that a key added to the config types without being listed here fails the typecheck.
18
- const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, onError: true, plugins: true }
19
- const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true }
18
+ const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
19
+ const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
20
20
  const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
21
21
  const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
22
22
 
@@ -38,13 +38,14 @@ function editDistance(a: string, b: string): number {
38
38
  return previous[b.length]!
39
39
  }
40
40
 
41
- /** The name of `names` within two edits of `name` (one for a name under four letters), the nearest first: the one a typo meant. */
41
+ /** The name of `names` within two edits of `name` (one when either name is under four letters), the nearest first: the one a typo meant. */
42
42
  export function closestName(name: string, names: readonly string[]): string | undefined {
43
43
  let best: string | undefined
44
- let bestDistance = name.length < 4 ? 2 : 3
44
+ let bestDistance = 3
45
45
  for (const known of names) {
46
+ const maxDistance = Math.min(name.length, known.length) < 4 ? 1 : 2
46
47
  const far = editDistance(name, known)
47
- if (far < bestDistance) {
48
+ if (far <= maxDistance && far < bestDistance) {
48
49
  best = known
49
50
  bestDistance = far
50
51
  }
@@ -61,6 +61,21 @@ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
61
61
  return appStorage.run(ctx, fn)
62
62
  }
63
63
 
64
+ // Bun does not carry an AsyncLocalStorage store into the top level of a module imported inside `run()` (1.4.5), so the context of a config being imported is also kept here.
65
+ let importing: AppRuntimeContext | undefined
66
+
67
+ /** Imports with `ctx` as the app context, the imported modules' top-level code included. */
68
+ export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
69
+ const outer = importing
70
+ importing = ctx
71
+ try {
72
+ return await runWithAppContext(ctx, load)
73
+ }
74
+ finally {
75
+ importing = outer
76
+ }
77
+ }
78
+
64
79
  export function getAppContext(): AppRuntimeContext | undefined {
65
- return appStorage.getStore()
80
+ return appStorage.getStore() ?? importing
66
81
  }
@@ -7,8 +7,8 @@ export { createAppContext, getAppContext, runWithAppContext } from './context'
7
7
  export type { AppRuntimeContext, CreateAppContextOptions } from './context'
8
8
  export { loadConfig } from './load'
9
9
  export { resolvePlugins } from './order'
10
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
11
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
10
+ export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, WEB_MANIFEST_SERVICE, serviceKey } from './services'
11
+ export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey, WebManifestIcon, WebManifestInfo } from './services'
12
12
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
13
13
  export type { ConsentConfig } from '../server/consent'
14
14
  export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -2,20 +2,37 @@
2
2
 
3
3
  import type { AppRuntimeContext } from './context'
4
4
  import type { PrunelleConfig } from './types'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
6
  import { existsSync, readFileSync } from 'node:fs'
6
- import { join, relative, resolve } from 'node:path'
7
+ import { join, relative, resolve, sep } from 'node:path'
7
8
  import { assertKnownConfigKeys } from './config'
8
- import { createAppContext, getAppContext, runWithAppContext } from './context'
9
+ import { devFromEnv } from '../server/env'
10
+ import { createAppContext, getAppContext, importWithAppContext } from './context'
9
11
 
10
12
  let configReloadSeq = 0
13
+ const PRUNELLE_SRC_DIR = resolve(import.meta.dir, '..')
14
+ const freshConfigStorage = new AsyncLocalStorage<boolean>()
11
15
 
12
- // In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
13
- function configSpecifier(configPath: string, fresh: boolean, isDev: boolean): string {
16
+ /** Runs `fn` with every nested `loadConfig()` bypassing Bun's module cache (used by long-lived processes such as `prunelle mcp`). */
17
+ export function runWithFreshConfig<T>(fn: () => T): T {
18
+ return freshConfigStorage.run(true, fn)
19
+ }
20
+
21
+ function evictLocalConfigImports(absRoot: string): void {
22
+ const rootPrefix = absRoot.endsWith(sep) ? absRoot : `${absRoot}${sep}`
23
+ const pruPrefix = PRUNELLE_SRC_DIR.endsWith(sep) ? PRUNELLE_SRC_DIR : `${PRUNELLE_SRC_DIR}${sep}`
24
+ const nmSegment = `${sep}node_modules${sep}`
25
+ for (const cached of Object.keys(require.cache)) {
26
+ if (cached.startsWith(rootPrefix) && !cached.includes(nmSegment) && !cached.startsWith(pruPrefix))
27
+ delete require.cache[cached]
28
+ }
29
+ }
30
+
31
+ // Query follows file content so unchanged configs reuse loaded plugin instances while edits reload immediately; `fresh` forces a new evaluation.
32
+ function configSpecifier(configPath: string, fresh: boolean): string {
14
33
  if (fresh)
15
34
  return `${configPath}?v=fresh-${++configReloadSeq}`
16
- if (isDev)
17
- return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
18
- return configPath
35
+ return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
19
36
  }
20
37
 
21
38
  export async function loadConfig(
@@ -27,9 +44,12 @@ export async function loadConfig(
27
44
  if (!existsSync(configPath))
28
45
  return {}
29
46
  const active = options?.appContext ?? getAppContext()
30
- const isDev = options?.dev ?? active?.dev ?? (process.env.PRUNELLE_DEV === '1')
47
+ const isDev = options?.dev ?? active?.dev ?? devFromEnv()
31
48
  const resolvedNodeEnv = options?.nodeEnv ?? active?.nodeEnv
32
- const spec = configSpecifier(configPath, options?.fresh === true, isDev)
49
+ const isFresh = options?.fresh ?? (freshConfigStorage.getStore() === true)
50
+ if (isFresh)
51
+ evictLocalConfigImports(absRoot)
52
+ const spec = configSpecifier(configPath, isFresh)
33
53
  const ctx = active !== undefined && active.root === absRoot
34
54
  ? active
35
55
  : createAppContext({
@@ -42,7 +62,7 @@ export async function loadConfig(
42
62
  })
43
63
  let mod: { default?: PrunelleConfig }
44
64
  try {
45
- mod = await runWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
65
+ mod = await importWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
46
66
  }
47
67
  catch (error) {
48
68
  // Several syntax errors arrive together; the first one names the line to fix.
@@ -7,6 +7,43 @@ function enforceRank(plugin: PrunellePlugin): number {
7
7
  return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
8
8
  }
9
9
 
10
+ function splitScope(name: string): { scope: string | undefined, pkg: string } {
11
+ if (name.startsWith('@')) {
12
+ const slash = name.indexOf('/')
13
+ if (slash > 1 && slash < name.length - 1)
14
+ return { scope: name.slice(0, slash), pkg: name.slice(slash + 1) }
15
+ }
16
+ return { scope: undefined, pkg: name }
17
+ }
18
+
19
+ // Compares scoped plugin names without their shared `@scope/` prefix so short official plugins (`@prunellejs/cms` vs `@prunellejs/mcp`, `@prunellejs/seo` vs `@prunellejs/spa`) never false-positive as typos.
20
+ function closestPluginName(depName: string, names: readonly string[]): string | undefined {
21
+ const dep = splitScope(depName)
22
+ if (dep.scope === undefined)
23
+ return closestName(depName, names.filter(n => splitScope(n).scope === undefined))
24
+
25
+ const sameScopePkgs: string[] = []
26
+ const byPkg = new Map<string, string>()
27
+ const samePkgScopes: string[] = []
28
+ const byScope = new Map<string, string>()
29
+ for (const known of names) {
30
+ const parts = splitScope(known)
31
+ if (parts.scope === dep.scope) {
32
+ sameScopePkgs.push(parts.pkg)
33
+ byPkg.set(parts.pkg, known)
34
+ }
35
+ else if (parts.scope !== undefined && parts.pkg === dep.pkg) {
36
+ samePkgScopes.push(parts.scope)
37
+ byScope.set(parts.scope, known)
38
+ }
39
+ }
40
+ const nearPkg = closestName(dep.pkg, sameScopePkgs)
41
+ if (nearPkg !== undefined)
42
+ return byPkg.get(nearPkg)
43
+ const nearScope = closestName(dep.scope, samePkgScopes)
44
+ return nearScope !== undefined ? byScope.get(nearScope) : undefined
45
+ }
46
+
10
47
  /**
11
48
  * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
12
49
  * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
@@ -44,7 +81,7 @@ export function resolvePlugins(plugins: readonly PrunellePlugin[] | undefined):
44
81
  const depIdx = indexByName.get(depName)
45
82
  // A name no plugin has is an optional dependency that is not installed, unless it is one typo away from one that is.
46
83
  if (depIdx === undefined) {
47
- const near = closestName(depName, names)
84
+ const near = closestPluginName(depName, names)
48
85
  if (near !== undefined)
49
86
  throw new Error(`prunelle: plugin "${base[i]!.name}" runs \`after\` "${depName}", which no plugin is named: did you mean "${near}"?`)
50
87
  continue
@@ -1,12 +1,15 @@
1
1
  // `prunelle/config`: what `prunelle.config.ts` and plugin packages use.
2
2
 
3
+ export { a11y, auditAccessibility, draftAccessibilityStatement, formatA11yReport, rgaaCriteriaForAxeRule } from '../a11y/index'
4
+ export type { A11yAuditOptions, A11yAuditReport, A11yImpact, A11yPluginOptions, A11yRouteReport, A11yViolation, A11yViolationNode, AccessibilityDeclarationOptions, AccessibilityDeclarationResult, ComplianceStatus, RgaaCriterion } from '../a11y/index'
3
5
  export { isInside } from '../build/is-inside'
4
6
  export { distLocator, firstLoadUrls, measureFirstLoad } from '../build/first-load'
5
7
  export type { FirstLoad, Locate } from '../build/first-load'
6
8
  export { brotliSize } from '../build/precompress'
9
+ export { minifyCss } from '../build/style-bundles'
7
10
  export { defineConfig, definePlugin } from './config'
8
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
9
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
11
+ export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, serviceKey, UI_KUI_LAYER_SERVICE, WEB_MANIFEST_SERVICE } from './services'
12
+ export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey, WebManifestIcon, WebManifestInfo } from './services'
10
13
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
11
14
  export type { ConsentConfig } from '../server/consent'
12
- export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
15
+ export type { BudgetConfig, BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -1,5 +1,8 @@
1
1
  // Service keys: `serviceKey` for any plugin, and the keys shared between two plugins, kept in core as contracts so neither depends on the other.
2
2
 
3
+ import type { RequestContext } from '../server/http'
4
+ import type { StandardSchemaV1 } from '../server/standard-schema'
5
+
3
6
  declare const SERVICE_TYPE: unique symbol
4
7
 
5
8
  /** Names a service and the type of its value; `provide` and `inject` take one instead of a string. */
@@ -20,6 +23,9 @@ export interface ActiveI18nConfig {
20
23
 
21
24
  export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('prunelle.i18n.config')
22
25
 
26
+ /** Set by `@prunellejs/ui` when it emits its grammar layer, so `@prunellejs/tailwind` places the `kui` layer between its base and utilities layers. */
27
+ export const UI_KUI_LAYER_SERVICE = serviceKey<boolean>('prunelle.ui.kuiLayer')
28
+
23
29
  export interface ContentImageResult {
24
30
  src: string
25
31
  srcset?: string | undefined
@@ -33,3 +39,81 @@ export interface ContentImageResult {
33
39
  export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
34
40
 
35
41
  export const CONTENT_IMAGE_RESOLVER_SERVICE = serviceKey<ContentImageResolver>('prunelle.content.imageResolver')
42
+
43
+ export interface ContentCollectionEntrySummary {
44
+ readonly slug: string
45
+ readonly locale?: string | undefined
46
+ readonly file?: string | undefined
47
+ readonly data: Record<string, unknown>
48
+ readonly body: string
49
+ }
50
+
51
+ export interface ContentCollectionDescriptor {
52
+ /** Collection identifier (directory basename or explicit name). */
53
+ readonly name: string
54
+ /** Optional URL prefix registered via feeds or collection config (e.g. '/blog'). */
55
+ readonly linkPrefix?: string | undefined
56
+ /** Absolute directory path for file-backed collections; undefined for loader-backed collections. */
57
+ readonly dir?: string | undefined
58
+ readonly localized: boolean
59
+ readonly defaultLocale: string
60
+ readonly locales?: readonly string[] | undefined
61
+ readonly schema?: StandardSchemaV1 | undefined
62
+ all(locale?: string): readonly ContentCollectionEntrySummary[] | Promise<readonly ContentCollectionEntrySummary[]>
63
+ get(slug: string, locale?: string): ContentCollectionEntrySummary | undefined | Promise<ContentCollectionEntrySummary | undefined>
64
+ clearCache(): void
65
+ }
66
+
67
+ export interface AccessedContentEntry {
68
+ readonly collection: string
69
+ readonly slug: string
70
+ readonly locale?: string | undefined
71
+ }
72
+
73
+ export interface ContentCollectionsService {
74
+ list(root?: string): readonly ContentCollectionDescriptor[] | Promise<readonly ContentCollectionDescriptor[]>
75
+ discover?(root: string): Promise<readonly ContentCollectionDescriptor[]>
76
+ /** Returns file-backed content entries accessed during the given dev request (primary `get()` entries first). */
77
+ accessedEntries?(ctx: RequestContext): readonly AccessedContentEntry[]
78
+ }
79
+
80
+ export const CONTENT_COLLECTIONS_SERVICE = serviceKey<ContentCollectionsService>('prunelle.content.collections')
81
+
82
+ /** Provided by `@prunellejs/cms` in dev mode when in-page editing is enabled so `@prunellejs/content` emits body anchor comments. */
83
+ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inline')
84
+
85
+ export interface JobsQueueOptions {
86
+ attempts?: number | undefined
87
+ backoff?: 'exponential' | 'fixed' | number | undefined
88
+ }
89
+
90
+ export interface JobsEnqueueOptions {
91
+ delay?: number | undefined
92
+ key?: string | undefined
93
+ }
94
+
95
+ export interface JobsService {
96
+ queue<T = unknown>(name: string, handler: (data: T) => void | Promise<void>, options?: JobsQueueOptions): void
97
+ enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions): Promise<void> | void
98
+ drain?(options?: { now?: number | undefined, includeDelayed?: boolean | undefined }): Promise<number>
99
+ }
100
+
101
+ export const JOBS_SERVICE = serviceKey<JobsService>('prunelle.jobs.service')
102
+
103
+ export interface WebManifestIcon {
104
+ readonly src: string
105
+ readonly sizes?: string | undefined
106
+ readonly type?: string | undefined
107
+ readonly purpose?: string | undefined
108
+ }
109
+
110
+ export interface WebManifestInfo {
111
+ readonly name?: string | undefined
112
+ readonly shortName?: string | undefined
113
+ readonly startUrl?: string | undefined
114
+ readonly display?: string | undefined
115
+ readonly icons?: readonly WebManifestIcon[] | undefined
116
+ readonly source?: string | undefined
117
+ }
118
+
119
+ export const WEB_MANIFEST_SERVICE = serviceKey<WebManifestInfo>('prunelle.webManifest')
@@ -4,12 +4,16 @@ import type { BunPlugin } from 'bun'
4
4
  import type { RouteManifestEntry } from '../build/index'
5
5
  import type { ComplianceConfig } from '../compiler/compliance'
6
6
  import type { ConsentConfig } from '../server/consent'
7
+ import type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from '../server/health'
7
8
  import type { Middleware, RequestContext } from '../server/index'
8
9
  import type { RateLimit, RateLimiter } from '../server/rate-limit'
10
+ import type { RouteCacheOptions } from '../server/route-cache'
9
11
  import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
12
  import type { NavigationConfig } from '../ssr/navigation'
11
13
  import type { ServiceKey } from './services'
12
14
 
15
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult }
16
+
13
17
  export type BuildPluginTarget = 'client' | 'server' | 'compile'
14
18
 
15
19
  export interface BuildPluginContext {
@@ -21,14 +25,22 @@ export interface BuildPluginContext {
21
25
  readonly isStatic: boolean
22
26
  readonly dev: boolean
23
27
  readonly routes: readonly RouteManifestEntry[]
28
+ /** Reachable source files (layouts, page, islands, local imports) for each route path. */
29
+ readonly routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
30
+ /** Reachable source files of the root layout and status/error pages (shared across the site). */
31
+ readonly globalSourceFiles?: readonly string[] | undefined
24
32
  /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_pru/<relPath>`). */
25
33
  emitAsset(relPath: string, content: string | Uint8Array): string
26
34
  /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
27
35
  emitPublic(relPath: string, content: string | Uint8Array): string
28
36
  /** Add a stylesheet URL to <head> on every page. */
29
37
  addStyle(href: string): void
38
+ /** Prepend a global stylesheet URL before app stylesheets (preserving plugin-before-app cascade order). */
39
+ prependStyle?(href: string): void
30
40
  /** Add a stylesheet URL to <head> on a specific route path only. */
31
41
  addRouteStyle(routePath: string, href: string): void
42
+ /** Prepend a route-specific stylesheet URL before that route's app stylesheets. */
43
+ prependRouteStyle?(routePath: string, href: string): void
32
44
  /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
33
45
  addHead(html: string): void
34
46
  /** Add raw HTML to <head> on a specific route path only. */
@@ -44,6 +56,8 @@ export interface BuildPluginContext {
44
56
  export interface FinalizeBuildContext {
45
57
  readonly root: string
46
58
  readonly outDir: string
59
+ /** Base directory that `route.prerendered` relative paths resolve against (equals `stageDir` in `--static`, `outDir` otherwise). */
60
+ readonly prerenderDir?: string | undefined
47
61
  readonly assetPrefix: string
48
62
  readonly site?: string | undefined
49
63
  readonly minify: boolean
@@ -53,6 +67,8 @@ export interface FinalizeBuildContext {
53
67
  readonly routes: readonly RouteManifestEntry[]
54
68
  /** Relative paths of all public files known so far (including files registered during prerender). */
55
69
  readonly publicFiles: readonly string[]
70
+ /** Relative paths of all client build assets under `dist/client/` (served at `${assetPrefix}/<rel>`). */
71
+ readonly assets?: readonly string[] | undefined
56
72
  /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_pru/<relPath>`). */
57
73
  emitAsset(relPath: string, content: string | Uint8Array): string
58
74
  /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
@@ -68,16 +84,24 @@ export interface FinalizeBuildContext {
68
84
  export interface CheckPluginContext {
69
85
  readonly root: string
70
86
  readonly routesDir: string
87
+ /** The app's own static folder (`publicDir`, `public/` by default), as `prunelle check` resolved it. */
88
+ readonly publicDir?: string | undefined
71
89
  /** Report a validation error from `prunelle check`. */
72
90
  error(message: string): void
73
91
  /** Report what may be intended but usually is not; `prunelle check --strict` fails on it. */
74
92
  warn(message: string): void
93
+ /** Register a check-scoped service for downstream plugins. */
94
+ provide?<T>(key: ServiceKey<T>, value: T): void
95
+ /** Look up a check-scoped service registered by an earlier plugin. */
96
+ inject?<T>(key: ServiceKey<T>): T | undefined
75
97
  }
76
98
 
77
99
  export interface RequiresPluginContext {
78
100
  readonly root: string
79
101
  /** `PrunelleConfig.site`, when the app sets it. */
80
102
  readonly site: string | undefined
103
+ /** The categories `consent.categories` declares, `essential` left out; empty when the app declares none. */
104
+ readonly consentCategories: readonly string[]
81
105
  }
82
106
 
83
107
  export interface PluginRouteOptions {
@@ -89,6 +113,11 @@ export interface PluginRouteOptions {
89
113
  trustProxy?: TrustProxy | undefined
90
114
  /** How often one client may call the route: past `max` per `windowMs`, it answers 429 with `Retry-After` before the handler runs. */
91
115
  rateLimit?: RateLimit<RequestContext> | undefined
116
+ /**
117
+ * Let the route's catch-all take a segment with an encoded `/`, `\` or NUL (`%2F`, `%5C`, `%00`), which every route refuses by default.
118
+ * Such a segment reaches the param still encoded, never as a separator: for a route that reads it as text (a QR code of a URL), never one that joins it into a file path.
119
+ */
120
+ encodedSlashes?: boolean | undefined
92
121
  }
93
122
 
94
123
  export interface MiddlewareOptions {
@@ -107,6 +136,8 @@ export interface ServerPluginAPI {
107
136
  readonly assetPrefix: string
108
137
  readonly site?: string | undefined
109
138
  readonly dev: boolean
139
+ /** True when `prunelle dev --host` binds an address other machines reach (`0.0.0.0`, a LAN address): a dev-only route that writes or reveals data then needs a guard. */
140
+ readonly devExposed: boolean
110
141
  /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
111
142
  readonly trustProxy: TrustProxy
112
143
  readonly trustedOrigins: readonly string[]
@@ -116,7 +147,7 @@ export interface ServerPluginAPI {
116
147
  use(middleware: Middleware, options?: MiddlewareOptions): void
117
148
  /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
118
149
  route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
119
- /** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait. */
150
+ /** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait, and `peek(key)` answers the same without counting. */
120
151
  rateLimiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
121
152
  /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
122
153
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
@@ -126,6 +157,8 @@ export interface ServerPluginAPI {
126
157
  inject<T>(key: ServiceKey<T>): T | undefined
127
158
  /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
128
159
  getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
160
+ /** Register a named health check evaluated on `GET ${assetPrefix}/health`. */
161
+ healthCheck(name: string, fn: HealthCheckFn): void
129
162
  /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
130
163
  onShutdown(fn: () => void | Promise<void>): void
131
164
  }
@@ -134,6 +167,7 @@ export interface ServerErrorInfo {
134
167
  error: unknown
135
168
  request: Request
136
169
  source: 'route' | 'action' | 'plugin'
170
+ requestId?: string | undefined
137
171
  }
138
172
 
139
173
  export interface DocumentHeadContext {
@@ -170,7 +204,7 @@ export interface PrunellePlugin {
170
204
  /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
171
205
  transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
172
206
  /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
173
- bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
207
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget, lang?: string | undefined }) => BunPlugin[]) | undefined
174
208
  /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
175
209
  css?: string[] | undefined
176
210
  /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
@@ -215,6 +249,10 @@ export interface ServerRuntimeConfig {
215
249
  /** CNIL/RGPD consent categories, cookie name, retention, and POST endpoint. */
216
250
  consent?: ConsentConfig | undefined
217
251
  compress?: boolean | undefined
252
+ /** Bounded in-memory cache for routes exporting `export const cache = ...` (default: 500 entries / 32 MiB; set `false` to disable). */
253
+ routeCache?: RouteCacheOptions | false | undefined
254
+ /** Health check function or named check map evaluated on `GET ${assetPrefix}/health`. */
255
+ healthCheck?: HealthCheckConfig | undefined
218
256
  onError?: ((info: ServerErrorInfo) => void) | undefined
219
257
  plugins?: PrunellePlugin[] | undefined
220
258
  }
@@ -226,4 +264,15 @@ export interface PrunelleConfig extends ServerRuntimeConfig {
226
264
  publicDir?: string | undefined
227
265
  /** French web law compliance checks (RGAA, RGPD, LCEN) configuration and rule silencing. */
228
266
  compliance?: ComplianceConfig | undefined
267
+ /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
268
+ autoPrerender?: boolean | undefined
269
+ /** Page weight caps `prunelle build` fails on: bytes, or a size like `'40kb'`. */
270
+ budget?: BudgetConfig | undefined
271
+ }
272
+
273
+ export interface BudgetConfig {
274
+ /** Eager JS per route, gzipped (`--max-js` overrides it for one run). */
275
+ js?: number | string | undefined
276
+ /** What a first visit downloads, brotli: the stylesheets, scripts and fonts, and on a prerendered page its HTML and every image. */
277
+ firstLoad?: number | string | undefined
229
278
  }
@@ -176,6 +176,8 @@ export function removeSub(link: Link): void {
176
176
 
177
177
  function unlink(l: Link): void {
178
178
  const { s, pd, nd } = l
179
+ if (s.c === l)
180
+ s.c = nd
179
181
  if (pd)
180
182
  pd.nd = nd
181
183
  else
@@ -184,10 +186,18 @@ function unlink(l: Link): void {
184
186
  nd.pd = pd
185
187
  else
186
188
  s.dt = pd
189
+ l.pd = l.nd = undefined
187
190
  if (!(s.f & F.UNOBSERVED))
188
191
  removeSub(l)
189
192
  }
190
193
 
194
+ export function unlinkSubs(dep: DepNode): void {
195
+ for (let l = dep.s, next: Link | undefined; l; l = next) {
196
+ next = l.ns
197
+ unlink(l)
198
+ }
199
+ }
200
+
191
201
  export function unlinkRemaining(sub: SubNode): void {
192
202
  let l = sub.c
193
203
  const e = sub.e
@@ -2,7 +2,7 @@
2
2
  // Glitch-free lazy computed values, O(1) link/unlink, compact internal fields for tiny bundle size.
3
3
 
4
4
  import type { DepNode, Link, Owned, Owner, ReadonlySignal, Signal, SubNode } from './graph'
5
- import { adopt, linkSub, throwErrors, unadopt, unlinkAll, unlinkRemaining, unobserve } from './graph'
5
+ import { adopt, linkSub, throwErrors, unadopt, unlinkAll, unlinkRemaining, unlinkSubs, unobserve } from './graph'
6
6
 
7
7
  export type { IdScope, Owner, ReadonlySignal, Signal } from './graph'
8
8
 
@@ -34,16 +34,24 @@ let writes = 0
34
34
  let propWave = 0
35
35
 
36
36
  // A child effect can sit ahead of its parent in the queue; the parent runs first, since its run may dispose the child.
37
- function runParentFirst(sub: SubNode): void {
38
- sub.f &= ~F.PENDING
37
+ function runParentFirst(sub: SubNode, errors: unknown[]): void {
38
+ sub.f &= ~(F.PENDING | F.QUEUED)
39
39
  for (let o = sub.o; o; o = o.o) {
40
40
  if (o.f & (F.PENDING | F.QUEUED)) {
41
- runParentFirst(o as unknown as SubNode)
41
+ runParentFirst(o as unknown as SubNode, errors)
42
42
  break
43
43
  }
44
44
  }
45
- if (!(sub.f & F.DISPOSED) && shouldRun(sub))
46
- sub.r()
45
+ if (!(sub.f & F.DISPOSED)) {
46
+ try {
47
+ if (shouldRun(sub))
48
+ sub.r()
49
+ }
50
+ catch (err) {
51
+ if (!catchEffectError?.(sub, err))
52
+ errors.push(err)
53
+ }
54
+ }
47
55
  }
48
56
 
49
57
  function enqueue(sub: SubNode): void {
@@ -94,15 +102,8 @@ function flush(): void {
94
102
  for (const node of round)
95
103
  node.f = (node.f & ~F.QUEUED) | F.PENDING
96
104
  for (const node of round) {
97
- if (node.f & F.PENDING) {
98
- try {
99
- runParentFirst(node)
100
- }
101
- catch (err) {
102
- if (!catchEffectError?.(node, err))
103
- errors.push(err)
104
- }
105
- }
105
+ if (node.f & F.PENDING)
106
+ runParentFirst(node, errors)
106
107
  }
107
108
  round.length = 0
108
109
  }
@@ -344,7 +345,9 @@ export function disposeOwner(node: Owner): void {
344
345
  unadopt(node)
345
346
  if (f & (F.COMPUTED | F.EFFECT))
346
347
  unlinkAll(node as unknown as SubNode)
347
- if (!(f & F.COMPUTED))
348
+ if (f & F.COMPUTED)
349
+ unlinkSubs(node as unknown as DepNode)
350
+ else
348
351
  releaseOwned(node)
349
352
  }
350
353
 
@@ -417,6 +420,11 @@ export function isObserving(): boolean {
417
420
  return !!currentSub && !(currentSub.f & (F.UNOBSERVED | F.DISPOSED))
418
421
  }
419
422
 
423
+ /** Internal: total signal writes so far, used by selector() to detect un-flushed changes without importing computed. */
424
+ export function writeCount(): number {
425
+ return writes
426
+ }
427
+
420
428
  /** Internal: signal that runs `onUnsub` and bumps its version when its last subscriber detaches. */
421
429
  export function watchedSignal<T>(initial: T, onUnsub: () => void): Signal<T> {
422
430
  const s = new SignalNode(initial)
@@ -1,7 +1,7 @@
1
1
  // O(1) row selection primitive: zero WeakSet overhead per row.
2
2
 
3
3
  import type { Signal } from './index'
4
- import { effect, isObserving, isTracking, watchedSignal } from './index'
4
+ import { effect, isObserving, isTracking, untrack, watchedSignal, writeCount } from './index'
5
5
 
6
6
  export interface Selector<K> {
7
7
  is(key: K): boolean
@@ -11,9 +11,31 @@ export function selector<K>(source: () => K): Selector<K> {
11
11
  const subs = new Map<K, Signal<boolean>>()
12
12
  let current: K | undefined
13
13
  let active = false
14
+ let checked = -1
15
+ let latest: K | undefined
16
+ let pending: Set<K> | undefined
17
+
18
+ const readLatest = (): K => {
19
+ const w = writeCount()
20
+ if (checked !== w) {
21
+ latest = untrack(source)
22
+ checked = w
23
+ }
24
+ return latest as K
25
+ }
14
26
 
15
27
  effect(() => {
16
28
  const next = source()
29
+ latest = next
30
+ checked = writeCount()
31
+ if (pending !== undefined) {
32
+ for (const k of pending) {
33
+ const s = subs.get(k)
34
+ if (s !== undefined)
35
+ s.value = Object.is(next, k)
36
+ }
37
+ pending = undefined
38
+ }
17
39
  if (active && Object.is(current, next))
18
40
  return
19
41
 
@@ -35,17 +57,22 @@ export function selector<K>(source: () => K): Selector<K> {
35
57
  if (!active)
36
58
  return Object.is(source(), key)
37
59
  if (!isObserving())
38
- return isTracking() ? Object.is(source(), key) : Object.is(current, key)
60
+ return Object.is(isTracking() ? source() : readLatest(), key)
39
61
 
62
+ const val = readLatest()
63
+ const matched = Object.is(val, key)
40
64
  let sub = subs.get(key)
41
65
  if (sub === undefined) {
42
- sub = watchedSignal(Object.is(current, key), () => {
66
+ sub = watchedSignal(matched, () => {
43
67
  if (subs.get(key) === sub)
44
68
  subs.delete(key)
45
69
  })
46
70
  subs.set(key, sub)
71
+ if (!Object.is(current, val))
72
+ (pending ??= new Set()).add(key)
47
73
  }
48
- return sub.value
74
+ sub.value
75
+ return matched
49
76
  },
50
77
  }
51
78
  }