prunelle 0.7.1 → 0.7.3

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 (45) hide show
  1. package/llms.txt +5 -5
  2. package/package.json +1 -1
  3. package/src/a11y/declaration.ts +4 -0
  4. package/src/a11y/index.ts +11 -0
  5. package/src/build/bundle.ts +2 -2
  6. package/src/build/files.ts +9 -0
  7. package/src/build/first-load.ts +2 -3
  8. package/src/build/index.ts +6 -12
  9. package/src/build/island-promote.ts +69 -8
  10. package/src/build/output.ts +3 -6
  11. package/src/build/plugin-host.ts +4 -2
  12. package/src/build/precompress.ts +1 -1
  13. package/src/build/prerender.ts +7 -4
  14. package/src/build/reach.ts +92 -28
  15. package/src/build/static-headers.ts +27 -8
  16. package/src/cli/check-forms.ts +60 -34
  17. package/src/cli/check-imports.ts +9 -3
  18. package/src/cli/check.ts +5 -15
  19. package/src/cli/new.ts +1 -1
  20. package/src/cli/upgrade.ts +4 -8
  21. package/src/compiler/analyze.ts +19 -41
  22. package/src/compiler/cacheability-private.ts +566 -0
  23. package/src/compiler/cacheability.ts +21 -322
  24. package/src/compiler/compliance-eco.ts +4 -4
  25. package/src/compiler/compliance-urls.ts +5 -3
  26. package/src/compiler/compliance.ts +68 -17
  27. package/src/compiler/expr-context.ts +113 -44
  28. package/src/compiler/spread-handlers.ts +295 -0
  29. package/src/dom/extras.ts +28 -26
  30. package/src/dom/island.ts +49 -34
  31. package/src/eco/declaration.ts +87 -16
  32. package/src/eco/index.ts +7 -3
  33. package/src/plugins/config.ts +13 -8
  34. package/src/reactivity/store.ts +19 -7
  35. package/src/server/action.ts +137 -40
  36. package/src/server/errors.ts +3 -0
  37. package/src/server/form-schema.ts +6 -12
  38. package/src/server/index.ts +6 -6
  39. package/src/server/page.ts +15 -0
  40. package/src/server/route-cache.ts +99 -3
  41. package/src/server/route-table.ts +23 -13
  42. package/src/server/standard-schema.ts +17 -0
  43. package/src/ssr/context.ts +1 -1
  44. package/src/ssr/index.ts +4 -2
  45. package/src/ssr/region.ts +18 -9
@@ -12,6 +12,7 @@ import { createRenderContext, runWithRenderContext } from '../ssr/context'
12
12
  import { raw, renderDocument, ssrChild } from '../ssr/index'
13
13
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
14
14
  import { wantsJson } from './http'
15
+ import { hasPublicFavicon } from './page'
15
16
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
16
17
  import { decodeRequestPath, pathPrefix } from './request-path'
17
18
  import { Router } from './router'
@@ -241,6 +242,7 @@ export interface FallbackPagesOptions {
241
242
  lang: string
242
243
  alwaysLoadRuntime: boolean
243
244
  navigation?: string | undefined
245
+ hasFavicon?: boolean | undefined
244
246
  dev: boolean
245
247
  document: DocumentHooks
246
248
  htmlHeaders: HtmlHeaders
@@ -263,6 +265,7 @@ export function createFallbackPages(options: FallbackPagesOptions) {
263
265
  chunkImports: manifest.chunkImports,
264
266
  alwaysLoadRuntime: options.alwaysLoadRuntime,
265
267
  navigation: options.navigation,
268
+ hasFavicon: options.hasFavicon ?? hasPublicFavicon(manifest),
266
269
  lang: options.lang,
267
270
  }
268
271
  const fallbackHeadStyleHashes = headTagStyleHashes(baseDoc.headTags)
@@ -27,13 +27,7 @@ export type ExtractedFormSchema =
27
27
  vendor: string
28
28
  }
29
29
 
30
- interface JsonSchemaCapable {
31
- '~standard'?: {
32
- vendor?: unknown
33
- jsonSchema?: {
34
- input?: (opts: { target: string }) => Record<string, unknown>
35
- } | undefined
36
- } | undefined
30
+ interface LegacyJsonSchemaCapable {
37
31
  toJSONSchema?: (() => Record<string, unknown>) | undefined
38
32
  jsonSchema?: Record<string, unknown> | undefined
39
33
  }
@@ -47,10 +41,9 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
47
41
  }
48
42
 
49
43
  function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
50
- const candidate = schema as unknown as JsonSchemaCapable
51
- const stdJson = candidate['~standard']?.jsonSchema
44
+ const stdJson = schema['~standard']?.jsonSchema
52
45
  if (stdJson !== undefined && typeof stdJson.input === 'function') {
53
- for (const target of ['draft-2020-12', 'draft-07']) {
46
+ for (const target of ['draft-2020-12', 'draft-07'] as const) {
54
47
  try {
55
48
  const out = stdJson.input({ target })
56
49
  if (isRecord(out))
@@ -61,6 +54,7 @@ function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> |
61
54
  }
62
55
  }
63
56
  }
57
+ const candidate = schema as unknown as LegacyJsonSchemaCapable
64
58
  if (typeof candidate.toJSONSchema === 'function') {
65
59
  try {
66
60
  const out = candidate.toJSONSchema()
@@ -313,7 +307,7 @@ export function lookupFieldConstraint(
313
307
  const direct = fields.get(name)
314
308
  if (direct !== undefined)
315
309
  return direct
316
- if (name.endsWith('[]'))
310
+ if (name.length > 2 && name.endsWith('[]'))
317
311
  return fields.get(name.slice(0, -2))
318
312
  return undefined
319
313
  }
@@ -326,7 +320,7 @@ export function extractFormSchema(schema: StandardSchemaV1): ExtractedFormSchema
326
320
 
327
321
  const raw = readRawJsonSchema(schema)
328
322
  if (raw === undefined) {
329
- const rawVendor = (schema as unknown as JsonSchemaCapable)['~standard']?.vendor
323
+ const rawVendor: unknown = schema['~standard']?.vendor
330
324
  const vendor = typeof rawVendor === 'string' && rawVendor.trim() !== '' ? rawVendor : 'unknown'
331
325
  const result: ExtractedFormSchema = { ok: false, vendor }
332
326
  schemaCache.set(schema, result)
@@ -34,7 +34,7 @@ import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './doc
34
34
  import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
35
35
  import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
36
36
  import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
37
- import { stripHeadBody } from './page'
37
+ import { hasPublicFavicon, stripHeadBody } from './page'
38
38
  import { resolveParamMatchers } from './param-matchers'
39
39
  import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
40
40
 
@@ -73,7 +73,7 @@ export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './rout
73
73
  export { DEFAULT_COOP, DEFAULT_CORP, DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isLoopbackHost, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
74
74
  export type { SecurityHeadersOptions, TrustProxy } from './security'
75
75
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
76
- export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
76
+ export type { InferInput, InferOutput, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
77
77
 
78
78
  // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
79
79
  const DEFAULT_STREAM_TIMEOUT = 30_000
@@ -409,13 +409,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
409
409
  const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
410
410
  const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
411
411
  registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
412
- const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
413
- renderError = fallbacks.renderError
414
- renderDenied = fallbacks.renderDenied
412
+ const hasFavicon = hasPublicFavicon(manifest, publicMap, serverPublicDir)
413
+ const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, dev: isDev, document, htmlHeaders, notifyError, finish })
414
+ ;({ renderError, renderDenied } = fallbacks)
415
415
  renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
416
416
  ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
417
417
  ;({ router, fastStaticPages } = compileRouteTable({
418
- manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
418
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor,
419
419
  pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
420
420
  fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
421
421
  }))
@@ -4,6 +4,8 @@ import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
4
  import type { Html } from '../jsx-runtime'
5
5
  import type { Middleware, RequestContext } from './http'
6
6
  import type { PrunelleLocals } from './index'
7
+ import { existsSync } from 'node:fs'
8
+ import { join } from 'node:path'
7
9
 
8
10
  export interface LoadedPageModule {
9
11
  default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
@@ -36,6 +38,19 @@ export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntr
36
38
  : manifest.headTags
37
39
  }
38
40
 
41
+ /** Whether the app ships a `/favicon.ico` in `public/` (or via `emitPublic`), so SSR should not inject an empty `data:,` icon. */
42
+ export function hasPublicFavicon(
43
+ manifest: BuildManifest,
44
+ publicMap?: ReadonlyMap<string, unknown>,
45
+ publicDir?: string,
46
+ ): boolean {
47
+ if (publicMap?.has('/favicon.ico'))
48
+ return true
49
+ if (manifest.publicFiles?.some(f => f === 'favicon.ico' || f === '/favicon.ico'))
50
+ return true
51
+ return publicDir !== undefined && existsSync(join(publicDir, 'favicon.ico'))
52
+ }
53
+
39
54
  export function allowedMethodsHeader(mod: LoadedPageModule): string {
40
55
  const allowed = new Set<string>()
41
56
  if (typeof mod.default === 'function') {
@@ -1,6 +1,7 @@
1
1
  // Bounded in-memory route response cache with stale-while-revalidate (SWR) and per-encoding compression reuse.
2
2
 
3
3
  import type { CompressionCache, CompressionEncoding } from './compress'
4
+ import type { RequestContext } from './http'
4
5
  import { ACTION_ERROR_COOKIE } from './action'
5
6
  import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
6
7
  import { etagMatches } from './http'
@@ -56,7 +57,7 @@ const MIN_COMPRESS_BYTES = 256
56
57
  const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
57
58
  // Campaign and click identifiers: they change who is counted, never what the page shows.
58
59
  const TRACKING_PARAM_RE = /^(?:utm_.+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)$/
59
- const TRACKING_SEARCH_RE = /[?&](?:utm_|gclid=|gbraid=|wbraid=|dclid=|fbclid=|msclkid=|mc_cid=|mc_eid=)/
60
+ const TRACKING_SEARCH_RE = /[?&](?:utm_|(?:gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)(?:[=&]|$))/
60
61
 
61
62
  const UNIT_MS: Record<string, number> = {
62
63
  ms: 1,
@@ -134,8 +135,16 @@ export function withCacheControl(headers: Record<string, string>, cacheControl:
134
135
  export function routeCacheKey(url: URL): string {
135
136
  if (!TRACKING_SEARCH_RE.test(url.search))
136
137
  return `${url.host}${url.pathname}${url.search}`
137
- const kept = [...url.searchParams].filter(([name]) => !TRACKING_PARAM_RE.test(name))
138
- return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${new URLSearchParams(kept)}`}`
138
+ const kept: string[] = []
139
+ for (const part of url.search.slice(1).split('&')) {
140
+ if (part.length === 0)
141
+ continue
142
+ const eq = part.indexOf('=')
143
+ const name = eq === -1 ? part : part.slice(0, eq)
144
+ if (!TRACKING_PARAM_RE.test(name))
145
+ kept.push(part)
146
+ }
147
+ return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${kept.join('&')}`}`
139
148
  }
140
149
 
141
150
  function weakEtagOf(html: string): string {
@@ -443,3 +452,90 @@ export function createRouteCache(option: RouteCacheOptions | false | undefined,
443
452
  return undefined
444
453
  return new RouteCache(option)
445
454
  }
455
+
456
+ const PRIVATE_HEADER_NAMES = new Set(['cookie', 'authorization'])
457
+ const BULK_HEADER_KEYS = new Set<PropertyKey>(['entries', 'values', 'keys', 'forEach', 'toJSON', 'getSetCookie', Symbol.iterator])
458
+
459
+ export interface PrivateReadTracker {
460
+ readonly ctx: RequestContext
461
+ readonly locals: RequestContext['locals']
462
+ readonly consent: RequestContext['consent']
463
+ readonly didReadPrivate: () => boolean
464
+ }
465
+
466
+ function wrapTrackedHeaders(headers: Headers, mark: () => void): Headers {
467
+ return new Proxy(headers, {
468
+ get(target, prop) {
469
+ if (prop === 'get' || prop === 'has') {
470
+ const fn = target[prop].bind(target) as (name: string) => unknown
471
+ return (name: string) => {
472
+ if (PRIVATE_HEADER_NAMES.has(String(name).toLowerCase()))
473
+ mark()
474
+ return fn(name)
475
+ }
476
+ }
477
+ if (BULK_HEADER_KEYS.has(prop) || (typeof prop === 'string' && PRIVATE_HEADER_NAMES.has(prop.toLowerCase())))
478
+ mark()
479
+ const value = Reflect.get(target, prop, target)
480
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
481
+ },
482
+ ownKeys(target) {
483
+ mark()
484
+ return Reflect.ownKeys(target)
485
+ },
486
+ })
487
+ }
488
+
489
+ /** Tracks runtime reads of per-visitor request data on a cached route so private HTML is never stored or shared. */
490
+ export function trackPrivateReads(ctx: RequestContext): PrivateReadTracker {
491
+ let readPrivate = false
492
+ const mark = (): void => { readPrivate = true }
493
+ const locals = new Proxy(ctx.locals, {
494
+ get(target, prop, receiver) {
495
+ mark()
496
+ return Reflect.get(target, prop, receiver)
497
+ },
498
+ has(target, prop) {
499
+ mark()
500
+ return Reflect.has(target, prop)
501
+ },
502
+ ownKeys(target) {
503
+ mark()
504
+ return Reflect.ownKeys(target)
505
+ },
506
+ })
507
+ const consent: RequestContext['consent'] = ctx.consent !== undefined
508
+ ? new Proxy(ctx.consent, {
509
+ get(target, prop) {
510
+ mark()
511
+ const value = Reflect.get(target, prop, target)
512
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
513
+ },
514
+ })
515
+ : ctx.consent
516
+ let headersProxy: Headers | undefined
517
+ const request = new Proxy(ctx.request, {
518
+ get(target, prop) {
519
+ if (prop === 'headers')
520
+ return headersProxy ??= wrapTrackedHeaders(target.headers, mark)
521
+ const value = Reflect.get(target, prop, target)
522
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
523
+ },
524
+ })
525
+ const trackedCtx: RequestContext = {
526
+ url: ctx.url,
527
+ params: ctx.params,
528
+ requestId: ctx.requestId,
529
+ region: ctx.region,
530
+ json: ctx.json,
531
+ text: ctx.text,
532
+ redirect: ctx.redirect,
533
+ deny: ctx.deny,
534
+ get request() { return request },
535
+ get cookies() { mark(); return ctx.cookies },
536
+ get locals() { return locals },
537
+ get consent() { mark(); return consent },
538
+ get ip() { mark(); return ctx.ip },
539
+ }
540
+ return { ctx: trackedCtx, locals, consent, didReadPrivate: () => readPrivate }
541
+ }
@@ -16,7 +16,7 @@ import type { Middleware, RequestContext } from './http'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
18
18
  import type { RequestKind } from './plugin-host'
19
- import type { RouteCache, RouteCacheSingleflightResult, RouteCacheSpec } from './route-cache'
19
+ import type { PrivateReadTracker, RouteCache, RouteCacheSingleflightResult, RouteCacheSpec } from './route-cache'
20
20
  import type { FastHandler, FastStaticPageOptions } from './routing'
21
21
  import type { TrustProxy } from './security'
22
22
  import type { StreamTracker } from './stream'
@@ -28,10 +28,10 @@ import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled }
28
28
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
29
29
  import { endTimer, startTimer } from './health'
30
30
  import { isNotFound, makeRequestContext, runChain } from './http'
31
- import { allowedMethodsHeader, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
31
+ import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
32
32
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
33
33
  import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
34
- import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, withCacheControl } from './route-cache'
34
+ import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
35
35
  import { Router } from './router'
36
36
  import { createFastStaticPageHandler, methodNotAllowed } from './routing'
37
37
  import { styleHashesOf } from './security'
@@ -62,7 +62,7 @@ export interface CompiledRoute {
62
62
  headStyleHashes: string[]
63
63
  }
64
64
 
65
- function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation']): DocumentOptions {
65
+ function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation'], hasFavicon: boolean): DocumentOptions {
66
66
  return {
67
67
  body: '',
68
68
  headTags: mergedHeadTags(manifest, entry),
@@ -71,6 +71,7 @@ function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, lang:
71
71
  chunkImports: manifest.chunkImports,
72
72
  alwaysLoadRuntime,
73
73
  navigation,
74
+ hasFavicon,
74
75
  regionScript: entry.usesRegion === true ? manifest.regionScript : undefined,
75
76
  styles: entry.styles ?? manifest.styles,
76
77
  }
@@ -85,6 +86,7 @@ export interface RouteTableOptions {
85
86
  lang: string
86
87
  alwaysLoadRuntime: boolean
87
88
  navigation: DocumentOptions['navigation']
89
+ hasFavicon?: boolean | undefined
88
90
  middlewaresFor: (path: string, kind?: RequestKind) => readonly Middleware[]
89
91
  /** Whether a plugin rewrite, head hook, HTML transform or route may change what `path` answers. */
90
92
  pluginIntercepts: (path: string) => boolean
@@ -93,6 +95,7 @@ export interface RouteTableOptions {
93
95
 
94
96
  export function compileRouteTable(options: RouteTableOptions): { router: Router<CompiledRoute>, fastStaticPages: Map<string, FastHandler> } {
95
97
  const { manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation, middlewaresFor, pluginIntercepts, fast } = options
98
+ const hasFavicon = options.hasFavicon ?? hasPublicFavicon(manifest)
96
99
  const router = new Router<CompiledRoute>(paramMatchers ?? BUILTIN_PARAM_MATCHERS)
97
100
  const fastStaticPages = new Map<string, FastHandler>()
98
101
  for (const entry of manifest.routes) {
@@ -101,7 +104,7 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
101
104
  const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
102
105
  const hasLoad = Boolean(entry.hasLoad && typeof mod.load === 'function')
103
106
  const dynamic = entry.path.includes(':') || entry.path.includes('*')
104
- const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation)
107
+ const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation, hasFavicon)
105
108
 
106
109
  // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, no route cache, and no intercepting plugin hook
107
110
  const canFastPath = middlewaresFor(entry.path, hasLoad ? 'dynamic' : 'static').length === 0
@@ -181,11 +184,12 @@ async function renderPageDocument(
181
184
  hasFlash: boolean,
182
185
  disableTimeout?: () => void,
183
186
  timing?: DevTiming,
187
+ privateTracker?: PrivateReadTracker,
184
188
  ): Promise<RenderedPageOutput> {
185
189
  const { entry, doc } = route
186
190
  const renderStart = startTimer(timing)
187
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId))
188
- const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
191
+ const rctx = createRenderContext(undefined, undefined, privateTracker !== undefined ? privateTracker.consent : ctx.consent, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId))
192
+ const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
189
193
  if (hasFlash)
190
194
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
191
195
  const docHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
@@ -244,10 +248,11 @@ async function revalidateCompiledRoute(
244
248
  let rendered: RenderedPageOutput | undefined
245
249
  let nonCacheable = false
246
250
  const res = await runChain(ctx, middlewares, async () => {
251
+ const tracker = trackPrivateReads(ctx)
247
252
  let data: unknown
248
253
  if (route.entry.hasLoad && typeof route.mod.load === 'function') {
249
254
  try {
250
- data = await route.mod.load(ctx)
255
+ data = await route.mod.load(tracker.ctx)
251
256
  }
252
257
  catch (error) {
253
258
  if (isNotFound(error)) {
@@ -261,8 +266,10 @@ async function revalidateCompiledRoute(
261
266
  return data instanceof Response ? data : new Response(null, { status: 404 })
262
267
  }
263
268
  }
264
- const pageProps: Record<string, unknown> = { params: ctx.params, locals: ctx.locals, url: ctx.url, ...(data !== undefined ? { data } : {}) }
265
- rendered = await renderPageDocument(deps, route, data, pageProps, ctx, false)
269
+ const pageProps: Record<string, unknown> = { params: ctx.params, locals: tracker.locals, url: ctx.url, ...(data !== undefined ? { data } : {}) }
270
+ rendered = await renderPageDocument(deps, route, data, pageProps, ctx, false, undefined, undefined, tracker)
271
+ if (tracker.didReadPrivate())
272
+ nonCacheable = true
266
273
  return rendered.kind === 'html'
267
274
  ? new Response(null, { status: 200, headers: rendered.headers })
268
275
  : rendered.response
@@ -378,10 +385,11 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
378
385
  }
379
386
 
380
387
  try {
381
- const loaded = await runCompiledRouteLoad(deps, route, ctx, timing)
388
+ const privateTracker = cacheSpec !== undefined ? trackPrivateReads(ctx) : undefined
389
+ const loaded = await runCompiledRouteLoad(deps, route, privateTracker?.ctx ?? ctx, timing)
382
390
  if (loaded.kind === 'response')
383
391
  return loaded.response
384
- const pageProps: Record<string, unknown> = { params: ctx.params, locals: ctx.locals, url: ctx.url, ...(loaded.data !== undefined ? { data: loaded.data } : {}) }
392
+ const pageProps: Record<string, unknown> = { params: ctx.params, locals: privateTracker?.locals ?? ctx.locals, url: ctx.url, ...(loaded.data !== undefined ? { data: loaded.data } : {}) }
385
393
 
386
394
  if (isRegion) {
387
395
  return respondRegion(
@@ -392,9 +400,11 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
392
400
  )
393
401
  }
394
402
 
395
- const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, disableTimeout, timing)
403
+ const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, disableTimeout, timing, privateTracker)
396
404
  if (rendered.kind === 'stream')
397
405
  return rendered.response
406
+ if (privateTracker?.didReadPrivate())
407
+ return compressedHtmlResponse(rendered.html, 200, withCacheControl(rendered.headers, 'private, no-store'), ctx.request, deps.compressCache)
398
408
  if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined && !cookieStore.hasChanges) {
399
409
  const cachedHeaders = withCacheControl(rendered.headers, cacheSpec.cacheControl)
400
410
  const stored = deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec)
@@ -5,6 +5,22 @@ export interface StandardSchemaIssue {
5
5
  readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
6
6
  }
7
7
 
8
+ export type StandardJSONSchemaTarget =
9
+ | 'draft-2020-12'
10
+ | 'draft-07'
11
+ | 'openapi-3.0'
12
+ | ({} & string)
13
+
14
+ export interface StandardJSONSchemaOptions {
15
+ readonly target: StandardJSONSchemaTarget
16
+ readonly libraryOptions?: Record<string, unknown> | undefined
17
+ }
18
+
19
+ export interface StandardJSONSchemaConverter {
20
+ readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>
21
+ readonly output?: ((options: StandardJSONSchemaOptions) => Record<string, unknown>) | undefined
22
+ }
23
+
8
24
  export interface StandardSchemaV1<Input = unknown, Output = Input> {
9
25
  readonly '~standard': {
10
26
  readonly version: 1
@@ -17,6 +33,7 @@ export interface StandardSchemaV1<Input = unknown, Output = Input> {
17
33
  | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
18
34
  >
19
35
  readonly types?: { readonly input: Input, readonly output: Output } | undefined
36
+ readonly jsonSchema?: StandardJSONSchemaConverter | undefined
20
37
  }
21
38
  }
22
39
 
@@ -392,7 +392,7 @@ async function settle(
392
392
  }
393
393
 
394
394
  /** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
395
- export const PRUNELLE_STREAM_SCRIPT = `(()=>{const w=n=>{if(n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const s=document.getElementById('k-s-'+n.dataset.ks);if(s){s.replaceWith(n.content);n.remove()}}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect()},{once:true})})()`
395
+ export const PRUNELLE_STREAM_SCRIPT = `(()=>{const q=new Map(),w=n=>{if(n.isConnected&&n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const id=n.dataset.ks,s=document.getElementById('k-s-'+id);if(s){q.delete(id);s.replaceWith(n.content);n.remove();for(const t of q.values())w(t)}else q.set(id,n)}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect();q.clear()},{once:true})})()`
396
396
 
397
397
  export function streamChunkScript(id: number, resolvedHtml: string): string {
398
398
  return `<template data-ks="${id}">${resolvedHtml}</template>`
package/src/ssr/index.ts CHANGED
@@ -553,6 +553,8 @@ export interface DocumentOptions {
553
553
  styles?: Iterable<string> | undefined
554
554
  hasIslands?: boolean | undefined
555
555
  hasSuspense?: boolean | undefined
556
+ /** True when the app ships `/favicon.ico` in `public/`, so no empty `data:,` fallback icon is injected. */
557
+ hasFavicon?: boolean | undefined
556
558
  // The head markup every page shares for the `navigation` settings: see `createNavigation`.
557
559
  navigation?: string | undefined
558
560
  }
@@ -563,7 +565,7 @@ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
563
565
  const EMPTY_ICON = '<link rel="icon" href="data:,">'
564
566
 
565
567
  export function renderDocument(options: DocumentOptions): string {
566
- const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, navigation } = options
568
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
567
569
  let headExtra = head
568
570
 
569
571
  if (headTags !== undefined) {
@@ -571,7 +573,7 @@ export function renderDocument(options: DocumentOptions): string {
571
573
  headExtra += tag
572
574
  }
573
575
 
574
- if (!TAB_ICON_RE.test(headExtra))
576
+ if (!hasFavicon && !TAB_ICON_RE.test(headExtra))
575
577
  headExtra += EMPTY_ICON
576
578
 
577
579
  if (styles !== undefined) {
package/src/ssr/region.ts CHANGED
@@ -165,15 +165,24 @@ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOpt
165
165
  let html = ctx.regionHtml
166
166
  if (html === undefined)
167
167
  return undefined
168
- for (let i = 0; i < ctx.pending.length; i++) {
169
- const chunk = ctx.pending[i]!
170
- const range = findPlaceholderRange(html, chunk.id)
171
- if (range === undefined)
172
- continue
173
- const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
174
- if ('error' in settled)
175
- reportError(chunk.id, settled.error)
176
- html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
168
+ const resolved = new Set<number>()
169
+ let progressed = true
170
+ while (progressed) {
171
+ progressed = false
172
+ for (let i = 0; i < ctx.pending.length; i++) {
173
+ const chunk = ctx.pending[i]!
174
+ if (resolved.has(chunk.id))
175
+ continue
176
+ const range = findPlaceholderRange(html, chunk.id)
177
+ if (range === undefined)
178
+ continue
179
+ resolved.add(chunk.id)
180
+ const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
181
+ if ('error' in settled)
182
+ reportError(chunk.id, settled.error)
183
+ html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
184
+ progressed = true
185
+ }
177
186
  }
178
187
  return html
179
188
  }