prunelle 0.0.0-stage → 0.1.2

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/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +106 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +127 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +575 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +264 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +126 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +177 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +109 -0
  28. package/src/cli/check.ts +334 -0
  29. package/src/cli/commands.ts +265 -0
  30. package/src/cli/index.ts +70 -0
  31. package/src/cli/inspect.ts +316 -0
  32. package/src/cli/new.ts +41 -0
  33. package/src/cli/upgrade-names.ts +149 -0
  34. package/src/cli/upgrade.ts +258 -0
  35. package/src/compiler/analyze.ts +618 -0
  36. package/src/compiler/ast.ts +82 -0
  37. package/src/compiler/browser-globals.ts +127 -0
  38. package/src/compiler/compliance.ts +598 -0
  39. package/src/compiler/data-keys.ts +295 -0
  40. package/src/compiler/dom-attrs.ts +379 -0
  41. package/src/compiler/dom.ts +566 -0
  42. package/src/compiler/emit.ts +131 -0
  43. package/src/compiler/expr-context.ts +408 -0
  44. package/src/compiler/index.ts +8 -0
  45. package/src/compiler/interactivity.ts +366 -0
  46. package/src/compiler/mistakes.ts +499 -0
  47. package/src/compiler/node-env.ts +50 -0
  48. package/src/compiler/patch.ts +97 -0
  49. package/src/compiler/props.ts +460 -0
  50. package/src/compiler/scope.ts +568 -0
  51. package/src/compiler/server-only.ts +326 -0
  52. package/src/compiler/shared.ts +369 -0
  53. package/src/compiler/signal-reads.ts +242 -0
  54. package/src/compiler/slots.ts +227 -0
  55. package/src/compiler/ssr-helpers.ts +555 -0
  56. package/src/compiler/ssr-island.ts +90 -0
  57. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  58. package/src/compiler/ssr.ts +394 -0
  59. package/src/context.ts +165 -0
  60. package/src/dev/child.ts +30 -0
  61. package/src/dev/index.ts +208 -0
  62. package/src/dev/modules.ts +68 -0
  63. package/src/dev/protocol.ts +21 -0
  64. package/src/dev/queue.ts +79 -0
  65. package/src/dev/reload.ts +157 -0
  66. package/src/dev/supervisor.ts +187 -0
  67. package/src/dev/watchers.ts +215 -0
  68. package/src/dom/action.ts +161 -0
  69. package/src/dom/attrs.ts +72 -0
  70. package/src/dom/claim.ts +120 -0
  71. package/src/dom/extras.ts +562 -0
  72. package/src/dom/index.ts +289 -0
  73. package/src/dom/island.ts +284 -0
  74. package/src/dom/loop.ts +450 -0
  75. package/src/dom/revive.ts +36 -0
  76. package/src/index.ts +22 -0
  77. package/src/jsx-runtime.ts +566 -0
  78. package/src/plugins/config.ts +86 -0
  79. package/src/plugins/context.ts +66 -0
  80. package/src/plugins/index.ts +14 -0
  81. package/src/plugins/load.ts +70 -0
  82. package/src/plugins/order.ts +111 -0
  83. package/src/plugins/public.ts +12 -0
  84. package/src/plugins/requires.ts +47 -0
  85. package/src/plugins/services.ts +35 -0
  86. package/src/plugins/types.ts +234 -0
  87. package/src/reactivity/graph.ts +249 -0
  88. package/src/reactivity/index.ts +533 -0
  89. package/src/reactivity/selector.ts +51 -0
  90. package/src/reactivity/store.ts +208 -0
  91. package/src/server/action-registry.ts +78 -0
  92. package/src/server/action.ts +475 -0
  93. package/src/server/app-entry.ts +23 -0
  94. package/src/server/assets.ts +136 -0
  95. package/src/server/compress.ts +560 -0
  96. package/src/server/consent.ts +253 -0
  97. package/src/server/cookies.ts +139 -0
  98. package/src/server/document.ts +271 -0
  99. package/src/server/env.ts +33 -0
  100. package/src/server/errors.ts +153 -0
  101. package/src/server/http.ts +441 -0
  102. package/src/server/index.ts +616 -0
  103. package/src/server/lifecycle.ts +75 -0
  104. package/src/server/loader.ts +118 -0
  105. package/src/server/page.ts +107 -0
  106. package/src/server/plugin-host.ts +251 -0
  107. package/src/server/prerendered.ts +71 -0
  108. package/src/server/public.ts +19 -0
  109. package/src/server/rate-limit.ts +133 -0
  110. package/src/server/region.ts +96 -0
  111. package/src/server/request-body.ts +27 -0
  112. package/src/server/request-path.ts +73 -0
  113. package/src/server/request-scope.ts +22 -0
  114. package/src/server/route-table.ts +79 -0
  115. package/src/server/router.ts +184 -0
  116. package/src/server/routing.ts +339 -0
  117. package/src/server/security.ts +323 -0
  118. package/src/server/serve-handlers.ts +69 -0
  119. package/src/server/served-file.ts +128 -0
  120. package/src/server/standard-schema.ts +87 -0
  121. package/src/server/start.ts +99 -0
  122. package/src/server/static-dir.ts +167 -0
  123. package/src/server/stream.ts +192 -0
  124. package/src/ssr/context.ts +301 -0
  125. package/src/ssr/index.ts +477 -0
  126. package/src/ssr/navigation.ts +96 -0
  127. package/src/ssr/region.ts +171 -0
  128. package/src/style.ts +33 -0
  129. package/src/test/browser.ts +186 -0
  130. package/src/test/index.ts +177 -0
  131. package/src/unrenderable.ts +35 -0
  132. package/templates/_shared/AGENTS.md +10 -0
  133. package/templates/_shared/CLAUDE.md +1 -0
  134. package/templates/_shared/gitignore +3 -0
  135. package/templates/_shared/public/robots.txt +2 -0
  136. package/templates/_shared/src/routes/legal.tsx +8 -0
  137. package/templates/_shared/tsconfig.json +20 -0
  138. package/templates/app/.env.example +4 -0
  139. package/templates/app/package.json +21 -0
  140. package/templates/app/prunelle.config.ts +11 -0
  141. package/templates/app/src/auth.ts +14 -0
  142. package/templates/app/src/routes/_layout.tsx +32 -0
  143. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  144. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  145. package/templates/app/src/routes/index.tsx +15 -0
  146. package/templates/app/src/routes/login.tsx +34 -0
  147. package/templates/app/src/styles/app.css +7 -0
  148. package/templates/app/tests/app.test.ts +32 -0
  149. package/templates/blog/content/posts/welcome.md +9 -0
  150. package/templates/blog/package.json +22 -0
  151. package/templates/blog/prunelle.config.ts +23 -0
  152. package/templates/blog/src/posts.ts +26 -0
  153. package/templates/blog/src/routes/_layout.tsx +20 -0
  154. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  155. package/templates/blog/src/routes/index.tsx +29 -0
  156. package/templates/blog/src/styles/app.css +10 -0
  157. package/templates/fullstack/package.json +19 -0
  158. package/templates/fullstack/prunelle.config.ts +6 -0
  159. package/templates/fullstack/src/actions/greet.ts +19 -0
  160. package/templates/fullstack/src/components/Counter.tsx +10 -0
  161. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  162. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  163. package/templates/fullstack/src/routes/api/health.ts +5 -0
  164. package/templates/fullstack/src/routes/index.tsx +13 -0
  165. package/templates/fullstack/src/styles/app.css +29 -0
  166. package/templates/fullstack/tests/app.test.ts +37 -0
  167. package/templates/minimal/package.json +19 -0
  168. package/templates/minimal/prunelle.config.ts +6 -0
  169. package/templates/minimal/src/components/Counter.tsx +10 -0
  170. package/templates/minimal/src/routes/_layout.tsx +14 -0
  171. package/templates/minimal/src/routes/index.tsx +11 -0
  172. package/templates/minimal/src/styles/app.css +22 -0
  173. package/README.md +0 -3
@@ -0,0 +1,66 @@
1
+ // Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
2
+
3
+ import type { ServiceKey } from './services'
4
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
+
6
+ export interface AppRuntimeContext {
7
+ readonly root: string
8
+ readonly outDir: string
9
+ readonly publicDir: string
10
+ readonly assetPrefix: string
11
+ readonly site?: string | undefined
12
+ readonly dev: boolean
13
+ readonly nodeEnv?: string | undefined
14
+ provide<T>(key: ServiceKey<T>, value: T): void
15
+ inject<T>(key: ServiceKey<T>): T | undefined
16
+ registerPublicFile(relPath: string): void
17
+ }
18
+
19
+ export interface CreateAppContextOptions {
20
+ root: string
21
+ outDir: string
22
+ publicDir: string
23
+ assetPrefix: string
24
+ site?: string | undefined
25
+ dev: boolean
26
+ nodeEnv?: string | undefined
27
+ onRegisterPublicFile?: ((relPath: string) => void) | undefined
28
+ }
29
+
30
+ const APP_STORAGE_KEY = Symbol.for('pru.app.storage')
31
+ const appStorage: AsyncLocalStorage<AppRuntimeContext> = (
32
+ (globalThis as Record<symbol, AsyncLocalStorage<AppRuntimeContext> | undefined>)[APP_STORAGE_KEY]
33
+ ??= new AsyncLocalStorage<AppRuntimeContext>()
34
+ )
35
+
36
+ export function createAppContext(options: CreateAppContextOptions): AppRuntimeContext {
37
+ const services = new Map<string, unknown>()
38
+ const site = options.site?.replace(/\/$/, '')
39
+ return {
40
+ root: options.root,
41
+ outDir: options.outDir,
42
+ publicDir: options.publicDir,
43
+ assetPrefix: options.assetPrefix,
44
+ ...(site !== undefined && site !== '' ? { site } : {}),
45
+ dev: options.dev,
46
+ ...(options.nodeEnv !== undefined ? { nodeEnv: options.nodeEnv } : {}),
47
+ // Keyed by name: the natively loaded config and the bundled app each hold their own key object.
48
+ provide<T>(key: ServiceKey<T>, value: T): void {
49
+ services.set(key.name, value)
50
+ },
51
+ inject<T>(key: ServiceKey<T>): T | undefined {
52
+ return services.get(key.name) as T | undefined
53
+ },
54
+ registerPublicFile(relPath: string): void {
55
+ options.onRegisterPublicFile?.(relPath)
56
+ },
57
+ }
58
+ }
59
+
60
+ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
61
+ return appStorage.run(ctx, fn)
62
+ }
63
+
64
+ export function getAppContext(): AppRuntimeContext | undefined {
65
+ return appStorage.getStore()
66
+ }
@@ -0,0 +1,14 @@
1
+ // Prunelle public Plugin API & config helpers.
2
+ // Strict architectural rule: every non-core capability (@prunellejs/tailwind, @prunellejs/spa, @prunellejs/i18n, etc.)
3
+ // is built strictly through these public hooks - never hardcoded in @prunellejs/core.
4
+
5
+ export { defineConfig, definePlugin, pickRuntimeConfig, resolveServerConfig } from './config'
6
+ export { createAppContext, getAppContext, runWithAppContext } from './context'
7
+ export type { AppRuntimeContext, CreateAppContextOptions } from './context'
8
+ export { loadConfig } from './load'
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'
12
+ export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
13
+ export type { ConsentConfig } from '../server/consent'
14
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -0,0 +1,70 @@
1
+ // Native `prunelle.config.ts` load, for the build, check and dev steps that run beside the bundled app.
2
+
3
+ import type { AppRuntimeContext } from './context'
4
+ import type { PrunelleConfig } from './types'
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { join, relative, resolve } from 'node:path'
7
+ import { assertKnownConfigKeys } from './config'
8
+ import { createAppContext, getAppContext, runWithAppContext } from './context'
9
+
10
+ let configReloadSeq = 0
11
+
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 {
14
+ if (fresh)
15
+ return `${configPath}?v=fresh-${++configReloadSeq}`
16
+ if (isDev)
17
+ return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
18
+ return configPath
19
+ }
20
+
21
+ export async function loadConfig(
22
+ root: string,
23
+ options?: { fresh?: boolean | undefined, dev?: boolean | undefined, nodeEnv?: string | undefined, appContext?: AppRuntimeContext | undefined },
24
+ ): Promise<PrunelleConfig> {
25
+ const absRoot = resolve(root)
26
+ const configPath = join(absRoot, 'prunelle.config.ts')
27
+ if (!existsSync(configPath))
28
+ return {}
29
+ const active = options?.appContext ?? getAppContext()
30
+ const isDev = options?.dev ?? active?.dev ?? (process.env.PRUNELLE_DEV === '1')
31
+ const resolvedNodeEnv = options?.nodeEnv ?? active?.nodeEnv
32
+ const spec = configSpecifier(configPath, options?.fresh === true, isDev)
33
+ const ctx = active !== undefined && active.root === absRoot
34
+ ? active
35
+ : createAppContext({
36
+ root: absRoot,
37
+ outDir: join(absRoot, 'dist'),
38
+ publicDir: join(absRoot, 'dist', 'public'),
39
+ assetPrefix: '/_pru',
40
+ dev: isDev,
41
+ nodeEnv: resolvedNodeEnv,
42
+ })
43
+ let mod: { default?: PrunelleConfig }
44
+ try {
45
+ mod = await runWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
46
+ }
47
+ catch (error) {
48
+ // Several syntax errors arrive together; the first one names the line to fix.
49
+ const first: unknown = (error as AggregateError).errors?.[0] ?? error
50
+ throw new Error(`prunelle: ${configErrorLocation(first, configPath, absRoot)}: ${first instanceof Error ? first.message : String(first)}`, { cause: error })
51
+ }
52
+ const config = mod.default ?? {}
53
+ assertKnownConfigKeys(config)
54
+ return config
55
+ }
56
+
57
+ const STACK_LOCATION_RE = /:(\d+):(\d+)\)?$/
58
+
59
+ // Where a config failed: the syntax error's position, else the config's own frame in the stack, which names the line calling a throwing plugin factory.
60
+ function configErrorLocation(error: unknown, configPath: string, root: string): string {
61
+ const position = (error as { position?: { file?: string, line: number, column: number } }).position
62
+ if (position?.file !== undefined)
63
+ return `${relative(root, position.file)}:${position.line}:${position.column}`
64
+ for (const frame of String((error as Error).stack ?? '').split('\n')) {
65
+ const match = frame.includes(configPath) ? STACK_LOCATION_RE.exec(frame) : null
66
+ if (match !== null)
67
+ return `prunelle.config.ts:${match[1]}:${match[2]}`
68
+ }
69
+ return 'prunelle.config.ts'
70
+ }
@@ -0,0 +1,111 @@
1
+ // Plugin ordering: `enforce` buckets, `after` dependencies, and the `readsLocals`/`providesLocals` startup check.
2
+
3
+ import type { PrunellePlugin } from './types'
4
+ import { closestName } from './config'
5
+
6
+ function enforceRank(plugin: PrunellePlugin): number {
7
+ return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
8
+ }
9
+
10
+ /**
11
+ * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
12
+ * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
13
+ */
14
+ export function resolvePlugins(plugins: readonly PrunellePlugin[] | undefined): PrunellePlugin[] {
15
+ if (plugins === undefined || plugins.length === 0)
16
+ return []
17
+
18
+ // Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
19
+ const base = plugins
20
+ .map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
21
+ .sort((a, b) => a.rank - b.rank || a.index - b.index)
22
+ .map(entry => entry.plugin)
23
+
24
+ const n = base.length
25
+ // `after` lists and `manifest.pluginData` both find a plugin by its name, so two plugins sharing one would trample each other.
26
+ const indexByName = new Map<string, number>()
27
+ for (let i = 0; i < n; i++) {
28
+ const name = base[i]!.name
29
+ if (indexByName.has(name))
30
+ throw new Error(`prunelle: two plugins are named "${name}" in prunelle.config.ts: register it once, or give each instance its own \`name\`.`)
31
+ indexByName.set(name, i)
32
+ }
33
+ const names = [...indexByName.keys()]
34
+
35
+ // Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
36
+ const inDegree = new Int32Array(n)
37
+ const edges: number[][] = Array.from({ length: n }, () => [])
38
+ for (let i = 0; i < n; i++) {
39
+ const deps = base[i]!.after
40
+ if (deps === undefined)
41
+ continue
42
+ const seen = new Set<number>()
43
+ for (const depName of deps) {
44
+ const depIdx = indexByName.get(depName)
45
+ // A name no plugin has is an optional dependency that is not installed, unless it is one typo away from one that is.
46
+ if (depIdx === undefined) {
47
+ const near = closestName(depName, names)
48
+ if (near !== undefined)
49
+ throw new Error(`prunelle: plugin "${base[i]!.name}" runs \`after\` "${depName}", which no plugin is named: did you mean "${near}"?`)
50
+ continue
51
+ }
52
+ if (depIdx === i || seen.has(depIdx))
53
+ continue
54
+ seen.add(depIdx)
55
+ edges[depIdx]!.push(i)
56
+ inDegree[i] = (inDegree[i] ?? 0) + 1
57
+ }
58
+ }
59
+
60
+ const ready: number[] = []
61
+ for (let i = 0; i < n; i++) {
62
+ if (inDegree[i] === 0)
63
+ ready.push(i)
64
+ }
65
+
66
+ const sorted: PrunellePlugin[] = []
67
+ while (ready.length > 0) {
68
+ // Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
69
+ let bestPos = 0
70
+ for (let k = 1; k < ready.length; k++) {
71
+ if (ready[k]! < ready[bestPos]!)
72
+ bestPos = k
73
+ }
74
+ const u = ready.splice(bestPos, 1)[0]!
75
+ sorted.push(base[u]!)
76
+ for (const v of edges[u]!) {
77
+ inDegree[v] = (inDegree[v] ?? 0) - 1
78
+ if (inDegree[v] === 0)
79
+ ready.push(v)
80
+ }
81
+ }
82
+
83
+ if (sorted.length !== n) {
84
+ const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
85
+ throw new Error(`prunelle: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
86
+ }
87
+
88
+ // Validate that no plugin reads a ctx.locals key before another active plugin provides it.
89
+ const providerByLocal = new Map<string, { name: string, index: number }>()
90
+ for (let i = 0; i < sorted.length; i++) {
91
+ const plugin = sorted[i]!
92
+ for (const key of plugin.providesLocals ?? []) {
93
+ if (!providerByLocal.has(key))
94
+ providerByLocal.set(key, { name: plugin.name, index: i })
95
+ }
96
+ }
97
+
98
+ for (let i = 0; i < sorted.length; i++) {
99
+ const plugin = sorted[i]!
100
+ for (const key of plugin.readsLocals ?? []) {
101
+ const provider = providerByLocal.get(key)
102
+ if (provider !== undefined && provider.index > i) {
103
+ throw new Error(
104
+ `prunelle: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
105
+ )
106
+ }
107
+ }
108
+ }
109
+
110
+ return sorted
111
+ }
@@ -0,0 +1,12 @@
1
+ // `prunelle/config`: what `prunelle.config.ts` and plugin packages use.
2
+
3
+ export { isInside } from '../build/is-inside'
4
+ export { distLocator, firstLoadUrls, measureFirstLoad } from '../build/first-load'
5
+ export type { FirstLoad, Locate } from '../build/first-load'
6
+ export { brotliSize } from '../build/precompress'
7
+ 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'
10
+ export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
11
+ export type { ConsentConfig } from '../server/consent'
12
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -0,0 +1,47 @@
1
+ // What each plugin says it needs to run in production: refused at a production start, warned about everywhere else.
2
+
3
+ import type { PrunellePlugin, RequiresPluginContext } from './types'
4
+
5
+ export interface PluginRequirements {
6
+ /** One `<plugin>: <message>` line per setting a plugin lacks. */
7
+ unmet: string[]
8
+ /** One line per plugin whose `requires` threw. */
9
+ failed: string[]
10
+ }
11
+
12
+ export async function collectRequirements(plugins: readonly PrunellePlugin[], ctx: RequiresPluginContext): Promise<PluginRequirements> {
13
+ const unmet: string[] = []
14
+ const failed: string[] = []
15
+ for (const plugin of plugins) {
16
+ if (plugin.requires === undefined)
17
+ continue
18
+ try {
19
+ for (const message of await plugin.requires(ctx) ?? [])
20
+ unmet.push(`${plugin.name}: ${message}`)
21
+ }
22
+ catch (error) {
23
+ failed.push(`${plugin.name}: requires() threw: ${error instanceof Error ? error.message : String(error)}`)
24
+ }
25
+ }
26
+ return { unmet, failed }
27
+ }
28
+
29
+ // Once per process, on globalThis since each build's server bundle has its own copy of this module: `prunelle dev` and a test file start many servers on the same plugins.
30
+ const WARNED_KEY = Symbol.for('pru.requires.warned')
31
+ const warned: Set<string> = (globalThis as Record<symbol, Set<string> | undefined>)[WARNED_KEY] ??= new Set<string>()
32
+
33
+ /** Throws listing every unmet requirement when `production`, else warns once about each. */
34
+ export async function enforceRequirements(plugins: readonly PrunellePlugin[], ctx: RequiresPluginContext, production: boolean): Promise<void> {
35
+ const { unmet, failed } = await collectRequirements(plugins, ctx)
36
+ const lines = [...unmet, ...failed]
37
+ if (lines.length === 0)
38
+ return
39
+ if (production)
40
+ throw new Error(`prunelle: the app cannot start in production until its plugins get what they need:\n${lines.map(line => ` - ${line}`).join('\n')}`)
41
+ for (const line of lines) {
42
+ if (warned.has(line))
43
+ continue
44
+ warned.add(line)
45
+ console.warn(`prunelle: in production this would refuse to start: ${line}`)
46
+ }
47
+ }
@@ -0,0 +1,35 @@
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
+
3
+ declare const SERVICE_TYPE: unique symbol
4
+
5
+ /** Names a service and the type of its value; `provide` and `inject` take one instead of a string. */
6
+ export interface ServiceKey<T> {
7
+ readonly name: string
8
+ readonly [SERVICE_TYPE]?: T
9
+ }
10
+
11
+ export function serviceKey<T>(name: string): ServiceKey<T> {
12
+ return { name }
13
+ }
14
+
15
+ export interface ActiveI18nConfig {
16
+ readonly locales: readonly string[]
17
+ readonly defaultLocale: string
18
+ readonly prefixDefault: boolean
19
+ }
20
+
21
+ export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('prunelle.i18n.config')
22
+
23
+ export interface ContentImageResult {
24
+ src: string
25
+ srcset?: string | undefined
26
+ avifSrcset?: string | undefined
27
+ sizes?: string | undefined
28
+ width?: number | undefined
29
+ height?: number | undefined
30
+ loading?: 'lazy' | 'eager' | undefined
31
+ }
32
+
33
+ export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
34
+
35
+ export const CONTENT_IMAGE_RESOLVER_SERVICE = serviceKey<ContentImageResolver>('prunelle.content.imageResolver')
@@ -0,0 +1,234 @@
1
+ // The plugin contract: what a `PrunellePlugin` declares and what the build, check and server hosts hand its hooks.
2
+
3
+ import type { BunPlugin } from 'bun'
4
+ import type { RouteManifestEntry } from '../build/index'
5
+ import type { ComplianceConfig } from '../compiler/compliance'
6
+ import type { ConsentConfig } from '../server/consent'
7
+ import type { Middleware, RequestContext } from '../server/index'
8
+ import type { RateLimit, RateLimiter } from '../server/rate-limit'
9
+ import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
+ import type { NavigationConfig } from '../ssr/navigation'
11
+ import type { ServiceKey } from './services'
12
+
13
+ export type BuildPluginTarget = 'client' | 'server' | 'compile'
14
+
15
+ export interface BuildPluginContext {
16
+ readonly root: string
17
+ readonly outDir: string
18
+ readonly assetPrefix: string
19
+ readonly site?: string | undefined
20
+ readonly minify: boolean
21
+ readonly isStatic: boolean
22
+ readonly dev: boolean
23
+ readonly routes: readonly RouteManifestEntry[]
24
+ /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_pru/<relPath>`). */
25
+ emitAsset(relPath: string, content: string | Uint8Array): string
26
+ /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
27
+ emitPublic(relPath: string, content: string | Uint8Array): string
28
+ /** Add a stylesheet URL to <head> on every page. */
29
+ addStyle(href: string): void
30
+ /** Add a stylesheet URL to <head> on a specific route path only. */
31
+ addRouteStyle(routePath: string, href: string): void
32
+ /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
33
+ addHead(html: string): void
34
+ /** Add raw HTML to <head> on a specific route path only. */
35
+ addRouteHead(routePath: string, html: string): void
36
+ /** Register an explicit build-scoped service for other plugins or render-time helpers. */
37
+ provide<T>(key: ServiceKey<T>, value: T): void
38
+ /** Look up a build-scoped service registered by another plugin. */
39
+ inject<T>(key: ServiceKey<T>): T | undefined
40
+ /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
41
+ setData(data: Record<string, unknown>): void
42
+ }
43
+
44
+ export interface FinalizeBuildContext {
45
+ readonly root: string
46
+ readonly outDir: string
47
+ readonly assetPrefix: string
48
+ readonly site?: string | undefined
49
+ readonly minify: boolean
50
+ readonly isStatic: boolean
51
+ readonly dev: boolean
52
+ /** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
53
+ readonly routes: readonly RouteManifestEntry[]
54
+ /** Relative paths of all public files known so far (including files registered during prerender). */
55
+ readonly publicFiles: readonly string[]
56
+ /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_pru/<relPath>`). */
57
+ emitAsset(relPath: string, content: string | Uint8Array): string
58
+ /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
59
+ emitPublic(relPath: string, content: string | Uint8Array): string
60
+ /** Register a build-scoped service. */
61
+ provide<T>(key: ServiceKey<T>, value: T): void
62
+ /** Look up a build-scoped service. */
63
+ inject<T>(key: ServiceKey<T>): T | undefined
64
+ /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
65
+ setData(data: Record<string, unknown>): void
66
+ }
67
+
68
+ export interface CheckPluginContext {
69
+ readonly root: string
70
+ readonly routesDir: string
71
+ /** Report a validation error from `prunelle check`. */
72
+ error(message: string): void
73
+ /** Report what may be intended but usually is not; `prunelle check --strict` fails on it. */
74
+ warn(message: string): void
75
+ }
76
+
77
+ export interface RequiresPluginContext {
78
+ readonly root: string
79
+ /** `PrunelleConfig.site`, when the app sets it. */
80
+ readonly site: string | undefined
81
+ }
82
+
83
+ export interface PluginRouteOptions {
84
+ /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
85
+ csrf?: boolean | undefined
86
+ /** Additional trusted origins merged with `PrunelleConfig.trustedOrigins` for this route's CSRF check. */
87
+ trustedOrigins?: readonly string[] | undefined
88
+ /** Override `PrunelleConfig.trustProxy` for this route's CSRF check. */
89
+ trustProxy?: TrustProxy | undefined
90
+ /** How often one client may call the route: past `max` per `windowMs`, it answers 429 with `Retry-After` before the handler runs. */
91
+ rateLimit?: RateLimit<RequestContext> | undefined
92
+ /**
93
+ * Let the route's catch-all take a segment with an encoded `/`, `\` or NUL (`%2F`, `%5C`, `%00`), which every route refuses by default.
94
+ * 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.
95
+ */
96
+ encodedSlashes?: boolean | undefined
97
+ }
98
+
99
+ export interface MiddlewareOptions {
100
+ /**
101
+ * `'all'` (default) runs on every request, prerendered pages included.
102
+ * `'rendered'` skips prerendered pages, which were rendered at build time and never read `ctx.locals`: for middleware that only feeds rendering, such as a session.
103
+ * `'dynamic'` also skips pages with no `load`, which render the same for everyone.
104
+ * A path prefix runs on the pathnames under it.
105
+ */
106
+ scope?: 'all' | 'rendered' | 'dynamic' | string | undefined
107
+ }
108
+
109
+ export interface ServerPluginAPI {
110
+ readonly root: string
111
+ readonly outDir: string
112
+ readonly assetPrefix: string
113
+ readonly site?: string | undefined
114
+ readonly dev: boolean
115
+ /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
116
+ readonly trustProxy: TrustProxy
117
+ readonly trustedOrigins: readonly string[]
118
+ /** Readonly runtime config forwarded from `prunelle.config.ts` (minus build-only keys). */
119
+ readonly config?: Readonly<Record<string, unknown>> | undefined
120
+ /** Register global (or scoped) middleware that runs before route handlers. */
121
+ use(middleware: Middleware, options?: MiddlewareOptions): void
122
+ /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
123
+ route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
124
+ /** 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. */
125
+ rateLimiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
126
+ /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
127
+ rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
128
+ /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
129
+ provide<T>(key: ServiceKey<T>, value: T): void
130
+ /** Look up a server-scoped service registered by another plugin. */
131
+ inject<T>(key: ServiceKey<T>): T | undefined
132
+ /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
133
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
134
+ /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
135
+ onShutdown(fn: () => void | Promise<void>): void
136
+ }
137
+
138
+ export interface ServerErrorInfo {
139
+ error: unknown
140
+ request: Request
141
+ source: 'route' | 'action' | 'plugin'
142
+ }
143
+
144
+ export interface DocumentHeadContext {
145
+ /** Current document `lang` attribute (mutating sets `<html lang="...">`). */
146
+ lang: string
147
+ /** Extra attributes emitted on `<html>`. */
148
+ readonly htmlAttrs: Record<string, string>
149
+ /** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
150
+ title: string | undefined
151
+ /** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
152
+ readonly headHtml: string
153
+ /** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
154
+ add(html: string): void
155
+ }
156
+
157
+ export interface PrunellePlugin {
158
+ name: string
159
+ /** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
160
+ enforce?: 'pre' | 'post' | undefined
161
+ /** Names of plugins that must run before this plugin when present. */
162
+ after?: readonly string[] | undefined
163
+ /** `ctx.locals` keys this plugin populates (used for startup order validation). */
164
+ providesLocals?: readonly string[] | undefined
165
+ /** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
166
+ readsLocals?: readonly string[] | undefined
167
+ /** Register server routes, global middleware, URL rewrites, or runtime services. */
168
+ server?: (api: ServerPluginAPI) => void | Promise<void>
169
+ /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
170
+ onError?: (info: ServerErrorInfo) => void
171
+ /** Build hook run after route compilation, before prerender / --static / --compile. */
172
+ build?: (ctx: BuildPluginContext) => void | Promise<void>
173
+ /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
174
+ afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
175
+ /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
176
+ transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
177
+ /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
178
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
179
+ /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
180
+ css?: string[] | undefined
181
+ /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
182
+ head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
183
+ /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
184
+ transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
185
+ /** Expand or filter prerender URLs for a route (e.g. @prunellejs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
186
+ prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
187
+ /** Client bootstrap module path — bundled ONLY when this plugin is active. */
188
+ clientEntry?: string | undefined
189
+ /** Inline scripts the plugin writes into pages (from `head`, `transformHtml` or `addHead`), each as it stands between its tags: the CSP of every page allows them by hash. */
190
+ inlineScripts?: readonly string[] | undefined
191
+ /** Client module bundled on its own and loaded only on routes whose tree renders a `<Region>`; every other page stays free of it. */
192
+ regionClientEntry?: string | undefined
193
+ /**
194
+ * What the plugin needs to run in production, read from its options, the app's config and the environment: one message per unmet setting, naming it and its fix.
195
+ * A production start refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn.
196
+ */
197
+ requires?: (ctx: RequiresPluginContext) => readonly string[] | Promise<readonly string[]>
198
+ /** Validate plugin-specific invariants during `prunelle check` (e.g. missing i18n keys, content frontmatter). */
199
+ check?: (ctx: CheckPluginContext) => void | Promise<void>
200
+ /** Extra directories or files (relative to app root or absolute) for `prunelle dev` to watch. */
201
+ watchPaths?: string[] | ((root: string) => string[]) | undefined
202
+ /** Register custom CLI subcommands (e.g. `prunelle i18n check`). */
203
+ commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
204
+ }
205
+
206
+ /** Shared runtime server options inherited from `prunelle.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
207
+ export interface ServerRuntimeConfig {
208
+ /** Public origin of the site (e.g. 'https://example.com'), inherited by @prunellejs/seo, @prunellejs/i18n, @prunellejs/content, @prunellejs/images, and @prunellejs/auth. */
209
+ site?: string | undefined
210
+ lang?: string | undefined
211
+ assetPrefix?: string | undefined
212
+ security?: SecurityHeadersOptions | false | undefined
213
+ trustedOrigins?: string[] | undefined
214
+ trustProxy?: TrustProxy | undefined
215
+ maxRequestBodySize?: number | undefined
216
+ /** How plain page changes feel without client JS: view transitions between pages, Speculation Rules prefetch on hover, opt-in prerender. */
217
+ navigation?: NavigationConfig | undefined
218
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
219
+ streamTimeout?: number | undefined
220
+ /** CNIL/RGPD consent categories, cookie name, retention, and POST endpoint. */
221
+ consent?: ConsentConfig | undefined
222
+ compress?: boolean | undefined
223
+ onError?: ((info: ServerErrorInfo) => void) | undefined
224
+ plugins?: PrunellePlugin[] | undefined
225
+ }
226
+
227
+ export interface PrunelleConfig extends ServerRuntimeConfig {
228
+ port?: number | undefined
229
+ routesDir?: string | undefined
230
+ outDir?: string | undefined
231
+ publicDir?: string | undefined
232
+ /** French web law compliance checks (RGAA, RGPD, LCEN) configuration and rule silencing. */
233
+ compliance?: ComplianceConfig | undefined
234
+ }