prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -4,15 +4,21 @@ import type { BuildManifest } from '../build/index'
4
4
  import type { AppRuntimeContext } from '../plugins/context'
5
5
  import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
6
6
  import type { HealthCheckEntry } from './health'
7
+ import type { RequestHook } from './request-log'
8
+ import type { NotifyError } from './errors'
7
9
  import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
8
10
 
9
11
  import type { TrustProxy } from './security'
10
12
  import { runWithAppContext } from '../plugins/context'
11
13
  import { enforceRequirements } from '../plugins/requires'
12
14
  import { normalizeConsentConfig, registerConsentRoute } from './consent'
13
- import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
15
+ import { registerCspReportRoute } from './csp-report'
16
+ import { appSurface } from './surface'
17
+ import { assertRateLimit, createServerRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
18
+ import { openSharedStore, SHARED_STORE } from './shared-store'
14
19
  import type { RequestPath } from './request-path'
15
20
  import type { RouteMatch } from './router'
21
+ import { shadowedPages, shadowMessage } from './plugin-route-shadow'
16
22
  import { Router } from './router'
17
23
 
18
24
  export interface PluginRouteDef {
@@ -23,11 +29,14 @@ export interface PluginRouteDef {
23
29
  trustProxy: TrustProxy
24
30
  /** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
25
31
  encodedSlashes: boolean
32
+ /** The path as the plugin registered it (`/reset/:token`), told to `onRequestEnd` hooks as the route. */
33
+ path: string
26
34
  }
27
35
 
28
36
  interface ScopedMiddleware {
29
37
  mw: Middleware
30
38
  scope: 'all' | 'rendered' | 'dynamic' | string
39
+ exact?: boolean | undefined
31
40
  }
32
41
 
33
42
  /** What a request reaches, as middleware scopes see it: a page built ahead of time, a page with no `load` that renders the same for everyone, or anything else answered per request. */
@@ -49,9 +58,11 @@ export interface ServerPluginHostOptions {
49
58
  trustProxy: TrustProxy
50
59
  trustedOriginsList: readonly string[]
51
60
  trustedOrigins: Set<string> | undefined
61
+ notifyError: NotifyError
52
62
  }
53
63
 
54
- function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, kind: RequestKind): boolean {
64
+ function middlewareAppliesToPath(entry: ScopedMiddleware, path: string, kind: RequestKind): boolean {
65
+ const { scope, exact } = entry
55
66
  if (scope === 'all')
56
67
  return true
57
68
  if (scope === 'rendered')
@@ -60,11 +71,30 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
60
71
  return kind === 'dynamic'
61
72
  const normScope = scope.length > 1 && scope.endsWith('/') ? scope.slice(0, -1) : scope
62
73
  const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
74
+ if (exact === true)
75
+ return normPath === normScope
63
76
  if (normScope === '/')
64
77
  return normPath.startsWith('/')
65
78
  return normPath === normScope || normPath.startsWith(`${normScope}/`)
66
79
  }
67
80
 
81
+ /** Whether a path scope covers some URL of a route pattern: `/m/vip` covers `/m/:id` for `/m/vip`, and `/m` covers it whole. */
82
+ function scopeMayCover(scope: string, routePath: string, exact?: boolean): boolean {
83
+ const scopeSegs = scope.split('/').filter(Boolean)
84
+ const routeSegs = routePath.split('/').filter(Boolean)
85
+ if (exact === true && scopeSegs.length !== routeSegs.length) {
86
+ if (!(routeSegs.length > 0 && routeSegs.at(-1)!.startsWith('*') && routeSegs.length - 1 <= scopeSegs.length))
87
+ return false
88
+ }
89
+ for (const [i, seg] of scopeSegs.entries()) {
90
+ const routeSeg = routeSegs[i]
91
+ if (routeSeg === undefined) return false
92
+ if (routeSeg.startsWith('*')) return true
93
+ if (!routeSeg.startsWith(':') && routeSeg !== seg) return false
94
+ }
95
+ return true
96
+ }
97
+
68
98
  /** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
69
99
  export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
70
100
  if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
@@ -103,32 +133,39 @@ function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[])
103
133
  const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
104
134
  // With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
105
135
  const byKind: Record<RequestKind, readonly Middleware[]> = {
106
- prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
107
- static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
136
+ prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m, '/', 'prerendered')).map(m => m.mw),
137
+ static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m, '/', 'static')).map(m => m.mw),
108
138
  dynamic: allMiddlewares,
109
139
  }
110
140
  const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
111
141
  if (!hasPathScopedMiddlewares)
112
142
  return byKind[kind]
113
- return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
143
+ return scopedMiddlewares.filter(m => middlewareAppliesToPath(m, path, kind)).map(m => m.mw)
114
144
  }
115
145
  const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
116
146
  if (!hasPathScopedMiddlewares)
117
147
  return byKind[kind]
118
148
  return scopedMiddlewares
119
- .filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
149
+ .filter(m => paths.some(path => middlewareAppliesToPath(m, path, kind)))
120
150
  .map(m => m.mw)
121
151
  }
122
- return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths }
152
+ // A middleware scoped to a path guards that part of the site; one scoped to a request kind (sessions, locales, analytics) runs everywhere and only feeds `ctx.locals`.
153
+ const isGatedByPlugin = (routePath: string): boolean =>
154
+ hasPathScopedMiddlewares && scopedMiddlewares.some(m => !isKindScope(m.scope) && scopeMayCover(m.scope, routePath, m.exact))
155
+ return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, isGatedByPlugin }
123
156
  }
124
157
 
125
158
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
126
159
  const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
160
+ const shared = config.store === undefined ? undefined : openSharedStore(config.store, options.root)
161
+ if (shared !== undefined)
162
+ appCtx.provide(SHARED_STORE, shared)
127
163
  // The counters of every limited route and action of this server, dropped with it.
128
- const rateLimits = createRateLimitStore()
164
+ const rateLimits = createServerRateLimitStore({ shared })
129
165
  const scopedMiddlewares: ScopedMiddleware[] = []
130
166
  const healthChecks: HealthCheckEntry[] = []
131
167
  const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
168
+ const requestHooks: RequestHook[] = []
132
169
  const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
133
170
  const router = new Router<Map<string, PluginRouteDef>>()
134
171
  const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
@@ -164,9 +201,9 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
164
201
  let limited = handler
165
202
  if (limit !== undefined) {
166
203
  assertRateLimit(limit, `${upperMethod} ${normPath} from "${pluginName}"`)
167
- const limiter = rateLimits.limiter(limit)
168
- limited = (ctx) => {
169
- const retryAfter = hitFor(limiter, limit, ctx)
204
+ const limiter = rateLimits.limiter(limit, `route:${upperMethod} ${normPath}`)
205
+ limited = async (ctx) => {
206
+ const retryAfter = await hitFor(limiter, limit, ctx)
170
207
  return retryAfter > 0 ? tooManyRequests(retryAfter) : handler(ctx)
171
208
  }
172
209
  }
@@ -177,6 +214,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
177
214
  trustedOrigins: routeTrustedOrigins,
178
215
  trustProxy: routeOptions?.trustProxy ?? trustProxy,
179
216
  encodedSlashes,
217
+ path: normPath,
180
218
  })
181
219
  }
182
220
 
@@ -194,6 +232,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
194
232
  console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
195
233
  }
196
234
  }
235
+ await shared?.close()
197
236
  }
198
237
 
199
238
  const {
@@ -212,12 +251,15 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
212
251
  const consentConfig = normalizeConsentConfig(config.consent)
213
252
  if (consentConfig !== undefined)
214
253
  registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
254
+ if (config.security !== false && config.security?.cspReports === true)
255
+ registerCspReportRoute(registerRouteFor('pru:csp-report'), options.notifyError)
215
256
 
216
257
  if (config.prerender !== true || config.static === true) {
217
258
  const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
218
- await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [] }, production))
259
+ await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [], store: config.store }, production))
219
260
  }
220
261
  for (const plugin of plugins) {
262
+ let limiters = 0
221
263
  if (plugin.server !== undefined) {
222
264
  const pluginApi: ServerPluginAPI = {
223
265
  root: options.root,
@@ -230,12 +272,12 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
230
272
  trustedOrigins: options.trustedOriginsList,
231
273
  config: readonlyRuntimeConfig,
232
274
  use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
233
- scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
275
+ scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all', exact: middlewareOptions?.exact })
234
276
  },
235
277
  route: registerRouteFor(plugin.name),
236
- rateLimiter(limit) {
278
+ rateLimiter(limit, name) {
237
279
  assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
238
- return rateLimits.limiter(limit)
280
+ return rateLimits.limiter(limit, `${plugin.name}:${name ?? `#${++limiters}`}`)
239
281
  },
240
282
  rewrite(fn) {
241
283
  rewrites.push(fn)
@@ -251,17 +293,25 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
251
293
  onShutdown(fn) {
252
294
  shutdownHooks.push({ plugin: plugin.name, hook: fn })
253
295
  },
296
+ onRequestEnd(fn) {
297
+ requestHooks.push({ owner: plugin.name, hook: fn })
298
+ },
299
+ surface: () => appSurface(manifest, config.modules),
254
300
  }
255
301
  await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
256
302
  }
257
303
  }
304
+ const claims = [...routeEntries].flatMap(([path, byMethod]) => [...byMethod].map(([method, def]) => ({ plugin: def.plugin, method, path })))
305
+ const [shadow] = shadowedPages(manifest.routes, claims)
306
+ if (shadow !== undefined)
307
+ throw new Error(`prunelle: ${shadowMessage(shadow)}`)
258
308
  }
259
309
  catch (error) {
260
310
  await dispose()
261
311
  throw error
262
312
  }
263
313
 
264
- return { router, rewrites, healthChecks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
314
+ return { router, rewrites, healthChecks, requestHooks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
265
315
  }
266
316
 
267
317
  export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
@@ -0,0 +1,24 @@
1
+ // A plugin route is matched before the app's pages, so one at a page's path answers in its place: start and `prunelle check` refuse the pair.
2
+
3
+ export interface PluginRouteClaim { plugin: string, method: string, path: string }
4
+
5
+ const PAGE_METHODS = new Set(['GET', 'HEAD', 'ALL'])
6
+ const withoutTrailingSlash = (path: string): string => path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
7
+
8
+ /** What `prunelle: ...` says for each page file a plugin route answers instead of, one line per pair. */
9
+ export function shadowedPages(pages: readonly { path: string, file: string }[], claims: readonly PluginRouteClaim[]): { plugin: string, method: string, path: string, file: string }[] {
10
+ const shadowed: { plugin: string, method: string, path: string, file: string }[] = []
11
+ for (const claim of claims) {
12
+ if (!PAGE_METHODS.has(claim.method.toUpperCase()))
13
+ continue
14
+ for (const page of pages) {
15
+ if (withoutTrailingSlash(page.path) === withoutTrailingSlash(claim.path))
16
+ shadowed.push({ plugin: claim.plugin, method: claim.method.toUpperCase(), path: page.path, file: page.file })
17
+ }
18
+ }
19
+ return shadowed
20
+ }
21
+
22
+ export function shadowMessage(shadow: { plugin: string, method: string, path: string, file: string }): string {
23
+ return `plugin "${shadow.plugin}" serves ${shadow.method} ${shadow.path}, which hides the page ${shadow.file} (plugin routes are matched before pages): move the page, or change the path the plugin serves.`
24
+ }
@@ -1,18 +1,29 @@
1
1
  // `prunelle/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
2
2
 
3
3
  export { action, getActionError } from './action'
4
+ export { invalidateCache } from './cache-invalidation'
5
+ export type { CacheTarget } from './cache-invalidation'
4
6
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
5
- export { deriveKey, safeEqual, signPayload, verifyPayload } from './app-secret'
7
+ export { deriveKey, safeEqual, signPayload, startSecret, verifyPayload } from './app-secret'
8
+ export { verifyWebhook } from './webhook'
9
+ export type { VerifyWebhookOptions, WebhookScheme } from './webhook'
6
10
  export type { ConsentConfig, RequestConsent } from './consent'
7
11
  export type { CookieOptions, Cookies } from './cookies'
8
12
  export { defineEnv, nodeEnv } from './env'
9
13
  export { notFound, wantsJson } from './http'
10
- export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
11
- export type { PrunelleLocals } from './index'
14
+ export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, RoutePattern, ServerOptions } from './http'
15
+
16
+ // Both declared here, the file `prunelle/server` resolves to: an augmentation reaches an interface only where it is declared, not through a re-export.
17
+ /** Request-scoped locals shared across middlewares, plugins, actions, layouts and pages; augment it with `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`. */
18
+ export interface PrunelleLocals {}
19
+ /** The app's route patterns, filled in by the `prunelle-routes.d.ts` that `prunelle dev`, `build` and `check` write beside the routes folder. */
20
+ export interface PrunelleRoutes {}
12
21
  export { createServer } from './loader'
13
22
  export { createRateLimitStore, rateLimitAddress } from './rate-limit'
14
23
  export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
15
24
  export { readStringFields } from './request-body'
25
+ export { parseStoreSpec, SHARED_STORE } from './shared-store'
26
+ export type { SharedStore } from './shared-store'
16
27
  export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeRedirect, verifyOrigin } from './security'
17
28
  export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
18
29
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
@@ -1,5 +1,6 @@
1
- // How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits.
1
+ // How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits, or in the app's shared store.
2
2
 
3
+ import type { SharedStore } from './shared-store'
3
4
  import { nodeEnv } from './env'
4
5
 
5
6
  export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
@@ -12,27 +13,31 @@ export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: stri
12
13
  }
13
14
 
14
15
  export interface RateLimiter {
15
- /** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. */
16
- hit(key: string): number
16
+ /** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. A promise when the app shares a `store`. */
17
+ hit(key: string): number | Promise<number>
17
18
  /** The seconds `hit(key)` would answer, counting nothing: 0 while `key` is under the limit. */
18
- peek(key: string): number
19
+ peek(key: string): number | Promise<number>
19
20
  }
20
21
 
21
22
  export interface RateLimitStore {
22
- /** A limiter counting in this store, apart from every other limiter's keys. */
23
- limiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
23
+ /** A limiter counting in this store, apart from every other limiter's keys; a `name` counts in the shared store, when there is one, with every process giving that name. */
24
+ limiter(limit: Pick<RateLimit, 'max' | 'windowMs'>, name?: string): RateLimiter
24
25
  /** Drops the hits older than their window, and the keys left with none; returns how many keys went. */
25
26
  sweep(now?: number): number
26
27
  readonly size: number
28
+ /** How many limiters count in this process's memory rather than in the shared store. */
29
+ readonly limiters: number
27
30
  /** Stops the sweep timer. */
28
31
  close(): void
29
32
  }
30
33
 
31
34
  export interface RateLimitStoreOptions {
32
- /** Keys kept before the least recently used go (default: 10 000). */
35
+ /** Keys each limiter keeps before its least recently used go (default: 10 000). */
33
36
  maxKeys?: number | undefined
34
- /** Hits kept across all keys before the least recently used keys go (default: 1 000 000, about 8 MB). */
37
+ /** Hits each limiter keeps across its keys before its least recently used keys go (default: 1 000 000, about 8 MB per limiter). */
35
38
  maxHits?: number | undefined
39
+ /** Where named limiters count, so every process of the app shares their windows. */
40
+ shared?: SharedStore | undefined
36
41
  }
37
42
 
38
43
  interface Bucket {
@@ -43,6 +48,17 @@ interface Bucket {
43
48
 
44
49
  const SWEEP_MS = 60_000
45
50
 
51
+ // Every store the app made itself and has not closed yet, so `--workers` can tell whether a limiter counts in this process's memory wherever the app made it. A server's own store is not listed: that server asks it directly, and another server's `--workers` warning must not count it.
52
+ const openStores = new Set<{ readonly limiters: number }>()
53
+
54
+ /** How many limiters of every open app-made store count in this process's memory. */
55
+ export function memoryLimiters(): number {
56
+ let total = 0
57
+ for (const store of openStores)
58
+ total += store.limiters
59
+ return total
60
+ }
61
+
46
62
  /** Throws when a `rateLimit` option cannot count anything, naming where it was set. */
47
63
  export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, where: string): void {
48
64
  if (!Number.isInteger(limit.max) || limit.max < 1)
@@ -52,12 +68,26 @@ export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, wher
52
68
  }
53
69
 
54
70
  export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateLimitStore {
71
+ return makeRateLimitStore(options, false)
72
+ }
73
+
74
+ /** A server's own store, which that server counts itself and `memoryLimiters()` leaves out. */
75
+ export function createServerRateLimitStore(options: RateLimitStoreOptions): RateLimitStore {
76
+ return makeRateLimitStore(options, true)
77
+ }
78
+
79
+ function makeRateLimitStore(options: RateLimitStoreOptions, own: boolean): RateLimitStore {
55
80
  const maxKeys = Math.max(1, options.maxKeys ?? 10_000)
56
81
  const maxHits = Math.max(1, options.maxHits ?? 1_000_000)
57
82
  // Each limiter owns a bounded LRU map so flooding one endpoint cannot evict keys from another.
58
83
  const buckets: Bucket[] = []
59
84
  let totalKeys = 0
60
85
  let timer: ReturnType<typeof setInterval> | undefined
86
+ const self = {
87
+ get limiters() {
88
+ return buckets.length
89
+ },
90
+ }
61
91
 
62
92
  function secondsUntilFree(hits: readonly number[], max: number, windowMs: number, now: number): number {
63
93
  return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
@@ -99,10 +129,15 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
99
129
  }
100
130
 
101
131
  return {
102
- limiter(limit) {
132
+ limiter(limit, name) {
103
133
  const { max, windowMs } = limit
134
+ const shared = options.shared
135
+ if (shared !== undefined && name !== undefined)
136
+ return { hit: async key => shared.hit(name, key, max, windowMs), peek: async key => shared.peek(name, key, max, windowMs) }
104
137
  const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
105
138
  buckets.push(bucket)
139
+ if (!own)
140
+ openStores.add(self)
106
141
  if (timer === undefined) {
107
142
  timer = setInterval(sweep, SWEEP_MS)
108
143
  timer.unref()
@@ -141,8 +176,12 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
141
176
  get size() {
142
177
  return totalKeys
143
178
  },
179
+ get limiters() {
180
+ return buckets.length
181
+ },
144
182
  close() {
145
183
  clearInterval(timer)
184
+ openStores.delete(self)
146
185
  timer = undefined
147
186
  },
148
187
  }
@@ -218,6 +257,6 @@ export function rateLimitKey<Ctx extends { ip?: string | undefined }>(limit: Rat
218
257
  }
219
258
 
220
259
  /** Counts `ctx` against `limiter` under `rateLimitKey`; returns 0 or the seconds to wait. */
221
- export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
260
+ export async function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): Promise<number> {
222
261
  return limiter.hit(rateLimitKey(limit, ctx))
223
262
  }
@@ -53,7 +53,17 @@ export function withRegionVary(headers: Record<string, string>, hasRegions: bool
53
53
 
54
54
  const TITLE_INNER_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/i
55
55
 
56
- /** Answers with the region's HTML and the page's title as it renders at this URL, in `x-pru-title` (percent-encoded), so the browser can retitle the tab without the head. */
56
+ // The href of the page's `<link rel="icon">`, whichever order its attributes come in.
57
+ const ICON_HREF_RE = /<link\b(?=[^>]*\brel="icon")[^>]*\bhref="([^"]*)"/i
58
+ // The escapes an attribute value comes out of `escAttr` with, Bun's own included.
59
+ const ATTR_ENTITY_RE = /&(?:amp|quot|lt|gt|#x27|#39);/g
60
+ const ATTR_ENTITIES: Record<string, string> = { '&amp;': '&', '&quot;': '"', '&lt;': '<', '&gt;': '>', '&#x27;': '\'', '&#39;': '\'' }
61
+ // A code point a header cannot carry, matched whole so an astral one is encoded and never split into lone surrogates.
62
+ const NOT_HEADER_SAFE_RE = /[^\x21-\x7E]/gu
63
+ // Above this the attributes are left out, so a proxy's response-header limit never fails the swap; the region then keeps its attributes.
64
+ const MAX_ATTRS_HEADER = 2048
65
+
66
+ /** Answers with the region's HTML, the page's title as it renders at this URL in `x-pru-title` and its icon in `x-pru-icon` (the title percent-encoded, the icon's address with its bytes outside printable ASCII percent-encoded), so the browser can retitle the tab without the head, and the region's own attributes in `x-pru-attrs` unless they pass 2 KB encoded. */
57
67
  export async function respondRegion(
58
68
  request: Request,
59
69
  mod: LoadedPageModule,
@@ -64,6 +74,7 @@ export async function respondRegion(
64
74
  streamTimeout?: number,
65
75
  onError?: (error: unknown) => void,
66
76
  transformHtml?: (html: string) => Promise<string>,
77
+ buildId?: string,
67
78
  ): Promise<Response> {
68
79
  const path = parseRegionPath(request.headers.get(REGION_HEADER))
69
80
  if (path === undefined || path.length === 0)
@@ -88,9 +99,18 @@ export async function respondRegion(
88
99
  })
89
100
  }
90
101
  const outHtml = request.method === 'HEAD' ? null : (transformHtml !== undefined ? await transformHtml(html) : html)
91
- const title = TITLE_INNER_RE.exec((await resolveHead(rctx)).head)?.[1]
102
+ const head = (await resolveHead(rctx)).head
103
+ const title = TITLE_INNER_RE.exec(head)?.[1]
104
+ const icon = ICON_HREF_RE.exec(head)?.[1]
105
+ const attrs = encodeURIComponent(rctx.regionAttrs)
92
106
  const headers: Record<string, string> = { ...htmlHeaders(rctx.hasIslands, false, true), 'vary': REGION_HEADER, [REGION_HEADER]: path.join('/') }
107
+ if (attrs.length <= MAX_ATTRS_HEADER)
108
+ headers['x-pru-attrs'] = attrs
93
109
  if (title !== undefined)
94
110
  headers['x-pru-title'] = encodeURIComponent(title)
111
+ if (icon !== undefined)
112
+ headers['x-pru-icon'] = icon.replace(ATTR_ENTITY_RE, entity => ATTR_ENTITIES[entity]!).replace(NOT_HEADER_SAFE_RE, encodeURIComponent)
113
+ if (buildId !== undefined)
114
+ headers['x-pru-build'] = buildId
95
115
  return new Response(outHtml, { status: 200, headers })
96
116
  }