prunelle 0.9.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.
- package/llms.txt +18 -18
- package/package.json +2 -2
- package/src/a11y/declaration.ts +4 -7
- package/src/build/bundle.ts +6 -2
- package/src/build/index.ts +3 -1
- package/src/build/island-promote.ts +42 -2
- package/src/build/islands.ts +59 -8
- package/src/build/manifest.ts +98 -0
- package/src/build/plugin-host.ts +11 -1
- package/src/build/prerender.ts +6 -1
- package/src/build/reach.ts +4 -3
- package/src/build/resolve.ts +5 -1
- package/src/build/routes.ts +18 -0
- package/src/cli/check-forms.ts +8 -0
- package/src/cli/check-links.ts +14 -5
- package/src/cli/check.ts +12 -6
- package/src/cli/commands.ts +5 -3
- package/src/cli/form-opaque-children.ts +40 -0
- package/src/compiler/analyze.ts +20 -14
- package/src/compiler/cacheability-private.ts +13 -3
- package/src/compiler/compliance-contrast.ts +48 -10
- package/src/compiler/compliance-rules.ts +72 -0
- package/src/compiler/compliance.ts +6 -66
- package/src/compiler/dom-attrs.ts +178 -22
- package/src/compiler/dom.ts +31 -44
- package/src/compiler/emit.ts +17 -6
- package/src/compiler/expr-context.ts +260 -207
- package/src/compiler/props-body.ts +263 -21
- package/src/compiler/props.ts +155 -5
- package/src/compiler/signal-reads.ts +142 -29
- package/src/compiler/spread-handlers.ts +25 -13
- package/src/compiler/ssr-emit.ts +3 -3
- package/src/compiler/ssr-helpers.ts +0 -5
- package/src/compiler/ssr.ts +4 -2
- package/src/dev/host-check.ts +2 -1
- package/src/dev/reload.ts +4 -1
- package/src/dom/attrs.ts +93 -25
- package/src/dom/extras.ts +89 -49
- package/src/dom/field-marks.ts +9 -1
- package/src/dom/index.ts +19 -13
- package/src/dom/loop.ts +259 -188
- package/src/dom/prefetch.ts +4 -1
- package/src/dom/regions.ts +25 -8
- package/src/dom/swap.ts +11 -10
- package/src/dom/trusted.ts +4 -4
- package/src/eco/declaration.ts +5 -1
- package/src/eco/index.ts +3 -0
- package/src/index.ts +3 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/public.ts +4 -0
- package/src/plugins/types.ts +8 -1
- package/src/reactivity/graph.ts +244 -41
- package/src/reactivity/hmr.ts +14 -3
- package/src/reactivity/index.ts +219 -235
- package/src/reactivity/resource.ts +17 -3
- package/src/reactivity/seed.ts +118 -16
- package/src/reactivity/selector.ts +85 -47
- package/src/reactivity/server-seed.ts +31 -23
- package/src/reactivity/store.ts +316 -136
- package/src/server/action-protect.ts +3 -0
- package/src/server/action-registry.ts +5 -1
- package/src/server/cache-invalidation.ts +4 -3
- package/src/server/compress.ts +52 -17
- package/src/server/consent.ts +5 -3
- package/src/server/cookies.ts +27 -8
- package/src/server/cors.ts +98 -0
- package/src/server/csp-report.ts +8 -4
- package/src/server/health.ts +9 -0
- package/src/server/http.ts +3 -1
- package/src/server/index.ts +25 -13
- package/src/server/loader.ts +1 -0
- package/src/server/plugin-host.ts +41 -9
- package/src/server/plugin-route-shadow.ts +24 -0
- package/src/server/rate-limit.ts +13 -3
- package/src/server/region.ts +19 -2
- package/src/server/request-handler.ts +58 -22
- package/src/server/request-log.ts +1 -1
- package/src/server/route-cache.ts +14 -2
- package/src/server/route-table.ts +21 -11
- package/src/server/router.ts +2 -1
- package/src/server/routing.ts +100 -42
- package/src/server/sanitize-html.ts +3 -1
- package/src/server/serve-handlers.ts +10 -4
- package/src/server/served-file.ts +19 -14
- package/src/server/shared-store.ts +10 -1
- package/src/server/static-dir.ts +21 -3
- package/src/server/webhook.ts +6 -4
- package/src/ssr/context.ts +149 -51
- package/src/ssr/index.ts +41 -46
- package/src/ssr/region.ts +9 -3
- package/src/style.ts +12 -5
- package/src/test/browser.ts +3 -1
- package/src/test/build-reuse.ts +22 -7
- package/src/test/index.ts +7 -3
- package/src/ts-plugin/diagnostics.ts +56 -18
- package/ts-plugin.cjs +465 -131
package/src/build/manifest.ts
CHANGED
|
@@ -29,6 +29,8 @@ export interface RouteManifestEntry {
|
|
|
29
29
|
file: string
|
|
30
30
|
layouts: string[]
|
|
31
31
|
middlewares: string[]
|
|
32
|
+
/** True when the route is an API endpoint (exports no `default` page or handles `GET` directly). */
|
|
33
|
+
isApi?: boolean | undefined
|
|
32
34
|
hasLoad?: boolean | undefined
|
|
33
35
|
isIsland?: boolean | undefined
|
|
34
36
|
islandChunk?: string | undefined
|
|
@@ -44,6 +46,10 @@ export interface RouteManifestEntry {
|
|
|
44
46
|
usesRenderContext?: boolean | undefined
|
|
45
47
|
/** The route, a layout or a component it renders imports `<Region>`. */
|
|
46
48
|
usesRegion?: boolean | undefined
|
|
49
|
+
/** `false` when static analysis proves no reachable module can emit `data-pru-keep-scroll`. */
|
|
50
|
+
usesKeepScroll?: boolean | undefined
|
|
51
|
+
/** `false` when static analysis proves no reachable module reads `currentRequest()` or calls a server action. */
|
|
52
|
+
usesRequestScope?: boolean | undefined
|
|
47
53
|
prerender?: boolean | undefined
|
|
48
54
|
/** Prerendered only because `autoPrerender` found it static, so the build may render it at request time instead. */
|
|
49
55
|
autoPrerender?: boolean | undefined
|
|
@@ -107,6 +113,82 @@ export interface RouteEntries {
|
|
|
107
113
|
globalSourceFiles: string[]
|
|
108
114
|
}
|
|
109
115
|
|
|
116
|
+
const JSX_SPREAD_RE = /\{\s*\.\.\./
|
|
117
|
+
const RAW_SPECIFIERS = new Set(['raw', '*'])
|
|
118
|
+
const REQUEST_SCOPE_SPECIFIERS = new Set(['currentRequest', 'action', 'getActionError', 'getLocale', 'ConsentBanner', 'ConsentPreferences', 'CookieTable', '*'])
|
|
119
|
+
|
|
120
|
+
function isKnownSafeExternal(source: string): boolean {
|
|
121
|
+
return source === 'prunelle' || source.startsWith('prunelle/') || source.startsWith('node:') || source === 'bun' || source.endsWith('.css')
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function createRouteFlagScanner(graph: ModuleGraph): (file: string) => { keepScroll: boolean, requestScope: boolean } {
|
|
125
|
+
const memo = new Map<string, { keepScroll: boolean, requestScope: boolean }>()
|
|
126
|
+
return (file: string) => {
|
|
127
|
+
const cached = memo.get(file)
|
|
128
|
+
if (cached !== undefined)
|
|
129
|
+
return cached
|
|
130
|
+
const analysis = graph.analyses.get(file)
|
|
131
|
+
if (analysis === undefined) {
|
|
132
|
+
const unknown = { keepScroll: true, requestScope: true }
|
|
133
|
+
memo.set(file, unknown)
|
|
134
|
+
return unknown
|
|
135
|
+
}
|
|
136
|
+
const code = graph.source(file)
|
|
137
|
+
let keepScroll = code.includes('data-pru-keep-scroll')
|
|
138
|
+
|| code.includes('innerHTML')
|
|
139
|
+
|| code.includes('dangerouslySetInnerHTML')
|
|
140
|
+
|| code.includes('pru.html')
|
|
141
|
+
|| code.includes('require(')
|
|
142
|
+
|| JSX_SPREAD_RE.test(code)
|
|
143
|
+
|| analysis.dynamicImports.length > 0
|
|
144
|
+
let requestScope = code.includes('currentRequest')
|
|
145
|
+
|| code.includes('pru.request')
|
|
146
|
+
|| code.includes('require(')
|
|
147
|
+
|| analysis.dynamicImports.length > 0
|
|
148
|
+
|
|
149
|
+
for (const imp of analysis.imports) {
|
|
150
|
+
if (keepScroll && requestScope)
|
|
151
|
+
break
|
|
152
|
+
if (graph.resolve(file, imp.source) !== undefined)
|
|
153
|
+
continue
|
|
154
|
+
if (!isKnownSafeExternal(imp.source)) {
|
|
155
|
+
keepScroll = true
|
|
156
|
+
requestScope = true
|
|
157
|
+
break
|
|
158
|
+
}
|
|
159
|
+
if (imp.source === 'prunelle' || imp.source.startsWith('prunelle/')) {
|
|
160
|
+
for (const spec of imp.specifiers) {
|
|
161
|
+
if (RAW_SPECIFIERS.has(spec.imported))
|
|
162
|
+
keepScroll = true
|
|
163
|
+
if (REQUEST_SCOPE_SPECIFIERS.has(spec.imported))
|
|
164
|
+
requestScope = true
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if ((!keepScroll || !requestScope) && analysis.reexports !== undefined) {
|
|
169
|
+
for (const re of analysis.reexports) {
|
|
170
|
+
if (graph.resolve(file, re.source) !== undefined)
|
|
171
|
+
continue
|
|
172
|
+
if (!isKnownSafeExternal(re.source)) {
|
|
173
|
+
keepScroll = true
|
|
174
|
+
requestScope = true
|
|
175
|
+
break
|
|
176
|
+
}
|
|
177
|
+
if (re.source === 'prunelle' || re.source.startsWith('prunelle/')) {
|
|
178
|
+
if (re.local === '*' || RAW_SPECIFIERS.has(re.local))
|
|
179
|
+
keepScroll = true
|
|
180
|
+
if (re.local === '*' || REQUEST_SCOPE_SPECIFIERS.has(re.local))
|
|
181
|
+
requestScope = true
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const result = { keepScroll, requestScope }
|
|
187
|
+
memo.set(file, result)
|
|
188
|
+
return result
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
110
192
|
export function buildRouteEntries(options: {
|
|
111
193
|
graph: ModuleGraph
|
|
112
194
|
islands: IslandPlan
|
|
@@ -125,6 +207,7 @@ export function buildRouteEntries(options: {
|
|
|
125
207
|
}): RouteEntries {
|
|
126
208
|
const { graph, islands, islandChunks, routesDir, toOutRel } = options
|
|
127
209
|
const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
|
|
210
|
+
const scanFlags = createRouteFlagScanner(graph)
|
|
128
211
|
|
|
129
212
|
const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
|
|
130
213
|
const rootLayout = join(routesDir, '_layout.tsx')
|
|
@@ -157,15 +240,28 @@ export function buildRouteEntries(options: {
|
|
|
157
240
|
}
|
|
158
241
|
const routePath = fileToRoutePath(routesDir, file)
|
|
159
242
|
routeSourceFiles.set(routePath, [...reachableFiles])
|
|
243
|
+
let usesKeepScroll = false
|
|
244
|
+
let usesRequestScope = false
|
|
245
|
+
for (const f of reachableFiles) {
|
|
246
|
+
const flags = scanFlags(f)
|
|
247
|
+
if (flags.keepScroll)
|
|
248
|
+
usesKeepScroll = true
|
|
249
|
+
if (flags.requestScope)
|
|
250
|
+
usesRequestScope = true
|
|
251
|
+
if (usesKeepScroll && usesRequestScope)
|
|
252
|
+
break
|
|
253
|
+
}
|
|
160
254
|
const middlewareSrcs = ancestorFiles(routesDir, file, MIDDLEWARE_NAMES)
|
|
161
255
|
const cacheable = isRouteCacheable({ graph, islands, file, layoutSrcs, middlewareCount: middlewareSrcs.length, routePath })
|
|
162
256
|
const cache = analysis?.cache
|
|
163
257
|
const autoPre = options.autoPrerender === true && cacheable && cache === undefined
|
|
258
|
+
const isApi = analysis !== undefined && (!analysis.exportedNames.includes('default') || analysis.exportedNames.includes('GET'))
|
|
164
259
|
return {
|
|
165
260
|
path: routePath,
|
|
166
261
|
file: toOutRel(file),
|
|
167
262
|
layouts: layoutSrcs.map(toOutRel),
|
|
168
263
|
middlewares: middlewareSrcs.map(toOutRel),
|
|
264
|
+
...(isApi ? { isApi: true } : {}),
|
|
169
265
|
hasLoad: analysis?.hasLoadExport,
|
|
170
266
|
isIsland: page?.interactive,
|
|
171
267
|
islandChunk: islandChunks.get(`${file}#default`),
|
|
@@ -176,6 +272,8 @@ export function buildRouteEntries(options: {
|
|
|
176
272
|
styles: [...styles],
|
|
177
273
|
usesRenderContext,
|
|
178
274
|
usesRegion,
|
|
275
|
+
...(usesKeepScroll ? {} : { usesKeepScroll: false }),
|
|
276
|
+
...(usesRequestScope ? {} : { usesRequestScope: false }),
|
|
179
277
|
prerender: analysis?.hasPrerender || options.isStatic || autoPre,
|
|
180
278
|
...(autoPre && analysis?.hasPrerender !== true && !options.isStatic ? { autoPrerender: true } : {}),
|
|
181
279
|
...(cache !== undefined ? { cache } : {}),
|
package/src/build/plugin-host.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import type { AppRuntimeContext } from '../plugins/context'
|
|
4
4
|
import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
|
|
5
5
|
import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
|
|
6
|
-
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
7
|
import { dirname, join, resolve } from 'node:path'
|
|
8
8
|
import { relPosix } from './files'
|
|
9
9
|
import { isInside } from './is-inside'
|
|
@@ -171,10 +171,19 @@ export function createPluginHost(options: PluginHostOptions) {
|
|
|
171
171
|
const precompressed = new Set<string>()
|
|
172
172
|
const styles = createStyleMutators(styleUrls, globalStyles, routes, statusPages)
|
|
173
173
|
|
|
174
|
+
// A file rewritten after it was precompressed loses its sidecars, so the next precompressOutput() writes them from the final content.
|
|
175
|
+
function dropSidecars(abs: string): void {
|
|
176
|
+
if (precompressed.delete(abs)) {
|
|
177
|
+
rmSync(`${abs}.br`, { force: true })
|
|
178
|
+
rmSync(`${abs}.gz`, { force: true })
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
174
182
|
function emitAsset(plugin: string, relPath: string, content: string | Uint8Array): string {
|
|
175
183
|
const clean = confinedRel(plugin, 'emitAsset', clientDir, relPath)
|
|
176
184
|
const dst = join(clientDir, clean)
|
|
177
185
|
mkdirSync(dirname(dst), { recursive: true })
|
|
186
|
+
dropSidecars(dst)
|
|
178
187
|
writeFileSync(dst, content)
|
|
179
188
|
if (!assetSet.has(clean)) {
|
|
180
189
|
assetSet.add(clean)
|
|
@@ -187,6 +196,7 @@ export function createPluginHost(options: PluginHostOptions) {
|
|
|
187
196
|
const clean = options.publicFiles.register(confinedRel(plugin, 'emitPublic', outPublicDir, relPath))
|
|
188
197
|
const dst = join(outPublicDir, clean)
|
|
189
198
|
mkdirSync(dirname(dst), { recursive: true })
|
|
199
|
+
dropSidecars(dst)
|
|
190
200
|
writeFileSync(dst, content)
|
|
191
201
|
return `/${clean}`
|
|
192
202
|
}
|
package/src/build/prerender.ts
CHANGED
|
@@ -71,7 +71,7 @@ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic:
|
|
|
71
71
|
const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
|
|
72
72
|
const ext = extname(lastSeg).toLowerCase()
|
|
73
73
|
const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
|
|
74
|
-
const inferredExt = !
|
|
74
|
+
const inferredExt = !isHtml && ext === '' ? extForContentType(contentType) : ''
|
|
75
75
|
const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
|
|
76
76
|
const rel = pathname === '/'
|
|
77
77
|
? 'index.html'
|
|
@@ -226,6 +226,11 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
226
226
|
const res = await app.handle(request)
|
|
227
227
|
const isExplicit404 = u === '/404' && res.status === 404
|
|
228
228
|
if (res.status !== 200 && !isExplicit404) {
|
|
229
|
+
// An API route (a module with no default export) answering 204 or 405 to GET has nothing to export; only a page answering non-200 fails the export.
|
|
230
|
+
if (isStatic && res.status < 500 && typeof (entry?.modules?.[task.route.file] as { default?: unknown } | undefined)?.default !== 'function') {
|
|
231
|
+
console.warn(`prunelle build --static: skipping API route "${u}" (${routeSource(options, task.route)}) because its GET answered HTTP ${res.status}, so a static host answers 404 for it: give it a GET that answers 200, or ignore this if it is meant for other methods.`)
|
|
232
|
+
continue
|
|
233
|
+
}
|
|
229
234
|
if (isStatic || res.status >= 500) {
|
|
230
235
|
failed = true
|
|
231
236
|
throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
|
package/src/build/reach.ts
CHANGED
|
@@ -105,9 +105,10 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
|
|
|
105
105
|
if (chunk === undefined)
|
|
106
106
|
continue
|
|
107
107
|
reach.chunks.add(chunk)
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
// Each use counts on its own: `$hydrate="load"` is eager whatever the island file says, and a use with no `$hydrate` takes the file's mode.
|
|
109
|
+
const fileLoads = target.defaultHydrate === undefined || target.defaultHydrate === 'load'
|
|
110
|
+
const uses = analysis.hydrateUses.get(localName)
|
|
111
|
+
if (uses === undefined ? fileLoads : [...uses].some(mode => mode === 'load' || (mode === '' && fileLoads)))
|
|
111
112
|
reach.eager.add(chunk)
|
|
112
113
|
}
|
|
113
114
|
return false
|
package/src/build/resolve.ts
CHANGED
|
@@ -7,10 +7,14 @@ import pkg from '../../package.json' with { type: 'json' }
|
|
|
7
7
|
export const PRUNELLE_SRC_ROOT = resolve(import.meta.dir, '..')
|
|
8
8
|
|
|
9
9
|
|
|
10
|
+
const JS_SUFFIX_RE = /\.(?:js|jsx|mjs)$/
|
|
11
|
+
|
|
10
12
|
export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
|
|
11
13
|
if (specifier.startsWith('.')) {
|
|
12
14
|
const base = resolve(dirname(fromFile), specifier)
|
|
13
|
-
|
|
15
|
+
// NodeNext projects write `./Counter.js` for `Counter.tsx`: the source file stands behind the suffix, as for TypeScript.
|
|
16
|
+
const bare = base.replace(JS_SUFFIX_RE, '')
|
|
17
|
+
const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts'), ...bare === base ? [] : [`${bare}.tsx`, `${bare}.ts`]]
|
|
14
18
|
for (const c of candidates) {
|
|
15
19
|
if (statSync(c, { throwIfNoEntry: false })?.isFile())
|
|
16
20
|
return c
|
package/src/build/routes.ts
CHANGED
|
@@ -98,8 +98,26 @@ const SPECIAL_FILE_DEFAULTS = new Map([
|
|
|
98
98
|
['_503', '503 status page component'],
|
|
99
99
|
])
|
|
100
100
|
|
|
101
|
+
// A file or folder name the router cannot match: a parameter beside text (`pre-[id]`), or an optional catch-all (`[[...rest]]`).
|
|
102
|
+
function routeSegmentProblem(file: string, routesRel: string): string | undefined {
|
|
103
|
+
const inside = file.startsWith(`${routesRel}/`) ? file.slice(routesRel.length + 1) : file
|
|
104
|
+
for (const part of inside.replace(TS_EXT_RE, '').split('/')) {
|
|
105
|
+
if (!part.includes('[') || isRouteGroupSegment(part))
|
|
106
|
+
continue
|
|
107
|
+
const optional = OPTIONAL_PARAM_SEG_RE.exec(part)
|
|
108
|
+
if (optional?.[1]?.startsWith('...') === true)
|
|
109
|
+
return `${file} names a route "${part}", an optional catch-all prunelle does not route: name it [${optional[1]}] for the sub-paths and add an index route for the bare path.`
|
|
110
|
+
if (!OPTIONAL_PARAM_SEG_RE.test(part) && !CATCH_ALL_SEG_RE.test(part) && !PARAM_SEG_RE.test(part))
|
|
111
|
+
return `${file} names a route "${part}" that mixes text and a parameter, which the router never matches: make the whole name the parameter (such as [id]), or put the text in a folder (such as pre/[id]).`
|
|
112
|
+
}
|
|
113
|
+
return undefined
|
|
114
|
+
}
|
|
115
|
+
|
|
101
116
|
/** For a route file or a special route file (`_layout`, `_middleware`, `_error`, `_404`, `_401`, `_403`, `_429`, `_503`), reports missing default export or non-route files. */
|
|
102
117
|
export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
|
|
118
|
+
const segmentProblem = routeSegmentProblem(file, routesRel)
|
|
119
|
+
if (segmentProblem !== undefined)
|
|
120
|
+
return segmentProblem
|
|
103
121
|
const name = basename(file)
|
|
104
122
|
if (SPECIAL_ROUTE_FILES.has(name))
|
|
105
123
|
return analysis.exportedNames.includes('default') ? undefined : `${file} has no default export: export default its ${SPECIAL_FILE_DEFAULTS.get(name.replace(TS_EXT_RE, ''))}.`
|
package/src/cli/check-forms.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { resolveExportTarget } from '../build/island-promote'
|
|
|
15
15
|
import { isInside } from '../build/is-inside'
|
|
16
16
|
import { resolvePrunelleSpecifier } from '../build/resolve'
|
|
17
17
|
import { walk } from '../compiler/ast'
|
|
18
|
+
import { hasOpaqueChild } from './form-opaque-children'
|
|
18
19
|
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
19
20
|
import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
|
|
20
21
|
import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
|
|
@@ -382,11 +383,18 @@ function collectFormFields(formNode: JSXElement, enclosingRoot: Node, rootFile:
|
|
|
382
383
|
const analysis = graph.analyses.get(file)
|
|
383
384
|
if (analysis === undefined) return
|
|
384
385
|
|
|
386
|
+
if (!externalOnly && Array.isArray(target) && hasOpaqueChild(target, analysis.program)) hasOpaqueFields = true
|
|
387
|
+
|
|
385
388
|
walk(target, (node) => {
|
|
389
|
+
if (node.type === 'JSXFragment') {
|
|
390
|
+
if (!externalOnly && hasOpaqueChild(node.children, analysis.program)) hasOpaqueFields = true
|
|
391
|
+
return undefined
|
|
392
|
+
}
|
|
386
393
|
if (node.type !== 'JSXElement') return undefined
|
|
387
394
|
if (node === formNode) return false
|
|
388
395
|
const tag = jsxTagName(node.openingElement.name)
|
|
389
396
|
if (!externalOnly && tag === 'form') return false
|
|
397
|
+
if (!externalOnly && tag !== 'select' && hasOpaqueChild(node.children, analysis.program)) hasOpaqueFields = true
|
|
390
398
|
|
|
391
399
|
if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
|
|
392
400
|
const match = controlFormMatch(node.openingElement.attributes, propsScope, formId, hasDynamicId, externalOnly)
|
package/src/cli/check-links.ts
CHANGED
|
@@ -17,18 +17,21 @@ import { createAppContext, I18N_CONFIG_SERVICE, pickRuntimeConfig, runWithAppCon
|
|
|
17
17
|
import { BUILTIN_PARAM_MATCHERS, extractMatcherFn } from '../server/param-matchers'
|
|
18
18
|
import { compileDynamicPatterns, type DynamicSegment, normalizePathname, patternMatchesPrefix, patternMatchesTemplate, staticPrefixOfPattern } from './check-links-patterns'
|
|
19
19
|
import { decodeRequestPath } from '../server/request-path'
|
|
20
|
+
import { type PluginRouteClaim, shadowedPages, shadowMessage } from '../server/plugin-route-shadow'
|
|
20
21
|
import { Router } from '../server/router'
|
|
21
22
|
|
|
22
23
|
export interface LinkCheckInput {
|
|
23
24
|
root: string; routesDir: string; publicDir: string; assetPrefix: string; site?: string | undefined
|
|
24
25
|
config: PrunelleConfig; plugins: readonly PrunellePlugin[]; routeFiles: readonly string[]
|
|
25
26
|
analyses: ReadonlyMap<string, ModuleAnalysis>; sources: ReadonlyMap<string, string>
|
|
27
|
+
/** Receives the errors found beside the link warnings: a plugin route that hides a page. */
|
|
28
|
+
errors?: string[] | undefined
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
interface RouteEntry { pattern: string, fileRel?: string | undefined, isDynamic: boolean, knownPaths?: ReadonlySet<string> | undefined, knownPathList?: readonly string[] | undefined }
|
|
29
32
|
interface LinkTarget { kind: 'exact' | 'prefix' | 'template', value: string, parts?: readonly string[] | undefined, offset: number, parentOffset: number }
|
|
30
33
|
interface LinkResolver { checkExact: (raw: string) => string | undefined, checkPrefix: (raw: string) => string | undefined, checkTemplate: (parts: readonly string[]) => string | undefined }
|
|
31
|
-
interface PluginProbeResult { pluginRoutes: string[], emittedPublic: string[], locales: string[] }
|
|
34
|
+
interface PluginProbeResult { pluginRoutes: string[], claims: PluginRouteClaim[], emittedPublic: string[], locales: string[] }
|
|
32
35
|
|
|
33
36
|
const LINK_ATTRS = new Set(['href', 'action', 'formaction', 'formAction'])
|
|
34
37
|
const LINK_IGNORE_TOKENS = new Set(['link', 'broken-link', 'link/broken'])
|
|
@@ -160,7 +163,7 @@ async function probeSinglePlugin(
|
|
|
160
163
|
plugin: PrunellePlugin,
|
|
161
164
|
config: PrunelleConfig,
|
|
162
165
|
paths: { root: string, outDir: string, assetPrefix: string, site: string | undefined },
|
|
163
|
-
state: { routes: string[], emitted: string[], services: Map<string, unknown>, shutdowns: (() => void | Promise<void>)[], provide: <T>(k: { readonly name: string }, v: T) => void },
|
|
166
|
+
state: { routes: string[], claims: PluginRouteClaim[], emitted: string[], services: Map<string, unknown>, shutdowns: (() => void | Promise<void>)[], provide: <T>(k: { readonly name: string }, v: T) => void },
|
|
164
167
|
): Promise<void> {
|
|
165
168
|
const { root, outDir, assetPrefix, site } = paths
|
|
166
169
|
const inject = <T>(key: { readonly name: string }) => state.services.get(key.name) as T | undefined
|
|
@@ -170,7 +173,7 @@ async function probeSinglePlugin(
|
|
|
170
173
|
trustProxy: config.trustProxy ?? false, trustedOrigins: config.trustedOrigins ?? [],
|
|
171
174
|
config: pickRuntimeConfig(config) as Readonly<Record<string, unknown>>,
|
|
172
175
|
use: (_mw, opts) => { if (plugin.name === '@prunellejs/seo' && typeof opts?.scope === 'string' && opts.scope.startsWith('/')) state.routes.push(opts.scope) },
|
|
173
|
-
route: (
|
|
176
|
+
route: (method, path) => { state.routes.push(path); state.claims.push({ plugin: plugin.name, method, path }) },
|
|
174
177
|
rateLimiter: () => ({ hit: () => 0, peek: () => 0 }), rewrite: () => {}, provide: state.provide,
|
|
175
178
|
inject: key => inject(key) as never, getBuildData: () => undefined, healthCheck: () => {},
|
|
176
179
|
onShutdown: fn => { state.shutdowns.push(fn) },
|
|
@@ -201,11 +204,12 @@ async function probePlugins(
|
|
|
201
204
|
const services = new Map<string, unknown>()
|
|
202
205
|
const shutdowns: (() => void | Promise<void>)[] = []
|
|
203
206
|
const routes: string[] = []
|
|
207
|
+
const claims: PluginRouteClaim[] = []
|
|
204
208
|
const emitted: string[] = []
|
|
205
209
|
const provide = <T>(key: { readonly name: string }, value: T): void => { services.set(key.name, value); appCtx.provide(key, value) }
|
|
206
210
|
try {
|
|
207
211
|
await runWithAppContext(appCtx, async () => {
|
|
208
|
-
for (const plugin of plugins) await probeSinglePlugin(plugin, config, paths, { routes, emitted, services, shutdowns, provide })
|
|
212
|
+
for (const plugin of plugins) await probeSinglePlugin(plugin, config, paths, { routes, claims, emitted, services, shutdowns, provide })
|
|
209
213
|
})
|
|
210
214
|
}
|
|
211
215
|
finally {
|
|
@@ -225,7 +229,7 @@ async function probePlugins(
|
|
|
225
229
|
}
|
|
226
230
|
}
|
|
227
231
|
}
|
|
228
|
-
return { pluginRoutes: routes, emittedPublic: emitted, locales: [...locales] }
|
|
232
|
+
return { pluginRoutes: routes, claims, emittedPublic: emitted, locales: [...locales] }
|
|
229
233
|
}
|
|
230
234
|
|
|
231
235
|
function collectPublicPaths(publicDir: string, emittedPublic: readonly string[]): Set<string> {
|
|
@@ -521,6 +525,11 @@ export async function checkAppLinks(input: LinkCheckInput): Promise<string[]> {
|
|
|
521
525
|
register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList.map(decodePathname)) : undefined, knownPathList })
|
|
522
526
|
}
|
|
523
527
|
probe.pluginRoutes.forEach(p => register(p, { pattern: p, isDynamic: p.includes(':') || p.includes('*') }))
|
|
528
|
+
if (input.errors !== undefined) {
|
|
529
|
+
const pages = pageFiles.map(file => ({ path: fileToRoutePath(routesDir, file), file: relPosix(root, file) }))
|
|
530
|
+
for (const shadow of shadowedPages(pages, probe.claims))
|
|
531
|
+
input.errors.push(formatDiagnostic(`${shadow.file}:1:1`, `prunelle check: ${shadowMessage(shadow)}`))
|
|
532
|
+
}
|
|
524
533
|
if (config.consent !== undefined) {
|
|
525
534
|
const rawEp = (config.consent.endpoint ?? '/_pru/consent').trim()
|
|
526
535
|
const ep = rawEp.startsWith('/') ? rawEp : `/${rawEp}`
|
package/src/cli/check.ts
CHANGED
|
@@ -73,6 +73,8 @@ export interface CheckDiagnostic {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
const DIAGNOSTIC_RE = /^(.+?):(\d+):(\d+): (error|warning): ([\s\S]*)$/
|
|
76
|
+
// The `[pwa/manifest-missing]` tag a plugin's warning names its rule with.
|
|
77
|
+
const PLUGIN_RULE_RE = /\[([a-z0-9-]+\/[a-z0-9-]+)\]/
|
|
76
78
|
|
|
77
79
|
export function diagnosticData(text: string, severity: 'error' | 'warning'): CheckDiagnostic {
|
|
78
80
|
const m = DIAGNOSTIC_RE.exec(text)
|
|
@@ -188,9 +190,9 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
|
|
|
188
190
|
}
|
|
189
191
|
}
|
|
190
192
|
|
|
191
|
-
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
|
|
192
|
-
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[], store: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
|
|
193
|
-
const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store } = paths
|
|
193
|
+
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts, and a warning whose `[ns/rule]` tag `compliance.ignore` lists is dropped.
|
|
194
|
+
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[], store: string | undefined, ignore: readonly string[] }, errors: string[], warnings: string[]): Promise<void> {
|
|
195
|
+
const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store, ignore } = paths
|
|
194
196
|
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
|
|
195
197
|
const placed = (message: string, severity: 'error' | 'warning'): string =>
|
|
196
198
|
DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
|
|
@@ -200,7 +202,11 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
|
|
|
200
202
|
publicDir,
|
|
201
203
|
site,
|
|
202
204
|
error: message => errors.push(placed(message, 'error')),
|
|
203
|
-
warn: message =>
|
|
205
|
+
warn: (message) => {
|
|
206
|
+
const rule = PLUGIN_RULE_RE.exec(message)?.[1]
|
|
207
|
+
if (rule === undefined || !ignore.includes(rule))
|
|
208
|
+
warnings.push(placed(message, 'warning'))
|
|
209
|
+
},
|
|
204
210
|
provide: appCtx.provide,
|
|
205
211
|
inject: appCtx.inject,
|
|
206
212
|
}
|
|
@@ -420,11 +426,11 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
420
426
|
warnings.push(...cookieWarnings(loadedConfig.consent !== undefined, files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
|
|
421
427
|
|
|
422
428
|
// 3e. Broken internal link & region target checks (#3, #379)
|
|
423
|
-
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
|
|
429
|
+
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources, errors }))
|
|
424
430
|
errors.push(...checkRegionTargets({ graph, routesDir, pageFiles, locate: (file, offset) => locOf(root, file, sources, offset) }))
|
|
425
431
|
|
|
426
432
|
// 3f. Plugin check(ctx) hooks
|
|
427
|
-
await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store: loadedConfig.store }, errors, warnings)
|
|
433
|
+
await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store: loadedConfig.store, ignore: compliance?.ignore ?? [] }, errors, warnings)
|
|
428
434
|
|
|
429
435
|
const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
|
|
430
436
|
|
package/src/cli/commands.ts
CHANGED
|
@@ -233,7 +233,8 @@ function a11yCommand(cwd: string): Commands[string] {
|
|
|
233
233
|
? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: rawRate === '' ? Number.NaN : Number(rawRate) }
|
|
234
234
|
: undefined
|
|
235
235
|
if (manualAudit !== undefined) {
|
|
236
|
-
|
|
236
|
+
// A day that does not exist (2026-02-30) rolls over to the next month instead of turning NaN, so it must round-trip.
|
|
237
|
+
if (Number.isNaN(manualAudit.date.getTime()) || manualAudit.date.toISOString().slice(0, 10) !== values['audit-date'])
|
|
237
238
|
return badUsage('--audit-date must be a valid YYYY-MM-DD date, e.g. --audit-date 2026-03-31')
|
|
238
239
|
if (!(manualAudit.rate >= 0 && manualAudit.rate <= 100))
|
|
239
240
|
return badUsage(`--rate must be a percentage from 0 to 100, got "${values.rate}"`)
|
|
@@ -273,13 +274,14 @@ function ecoCommand(cwd: string): Commands[string] {
|
|
|
273
274
|
run: async (args) => {
|
|
274
275
|
const { values, positionals: [dir] } = parse(args, 'prunelle eco [options] [dir]: builds the app and reports what it saw of the RGESN 2024 criteria, leaving every verdict to a person', {
|
|
275
276
|
declaration: { type: 'string', optional: { bare: '' }, description: 'write an editable RGESN 2024 eco-design declaration page (default: src/routes/ecoconception.tsx)' },
|
|
277
|
+
force: { type: 'boolean', description: 'overwrite an existing declaration file when used with --declaration' },
|
|
276
278
|
service: { type: 'string', description: 'the service\'s name, written into --declaration' },
|
|
277
279
|
org: { type: 'string', description: 'the entity running the evaluation, written into --declaration' },
|
|
278
280
|
contact: { type: 'string', description: 'the contact email, written into --declaration' },
|
|
279
281
|
root: ROOT,
|
|
280
|
-
}, { positionals: ['[dir]'], exits: [OK, [1, 'the build failed'], USAGE_EXIT] })
|
|
282
|
+
}, { positionals: ['[dir]'], exits: [OK, [1, 'the build failed, or the file --declaration would write exists without --force'], USAGE_EXIT] })
|
|
281
283
|
const { formatEcoResult, runEco } = await import('../eco/index')
|
|
282
|
-
const result = await failing('eco', () => runEco({ root: rootOf(cwd, values.root, dir), declaration: values.declaration, service: values.service, organization: values.org, contactEmail: values.contact }))
|
|
284
|
+
const result = await failing('eco', () => runEco({ root: rootOf(cwd, values.root, dir), declaration: values.declaration, force: values.force === true, service: values.service, organization: values.org, contactEmail: values.contact }))
|
|
283
285
|
console.log(formatEcoResult(result))
|
|
284
286
|
return 0
|
|
285
287
|
},
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Which children of a form hide the controls they render from `prunelle check`'s field matching (#401).
|
|
2
|
+
import type { Node, Program } from 'oxc-parser'
|
|
3
|
+
import { walk } from '../compiler/ast'
|
|
4
|
+
import { unwrapTsExpr } from '../compiler/shared'
|
|
5
|
+
|
|
6
|
+
function containsJsx(node: Node): boolean {
|
|
7
|
+
let found = false
|
|
8
|
+
walk(node, (n) => {
|
|
9
|
+
if (n.type === 'JSXElement' || n.type === 'JSXFragment') found = true
|
|
10
|
+
return found ? false : undefined
|
|
11
|
+
})
|
|
12
|
+
return found
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const jsxBindingsByProgram = new WeakMap<Program, ReadonlySet<string>>()
|
|
16
|
+
|
|
17
|
+
/** The names a file binds to JSX: a variable holding an element, or a function returning one. */
|
|
18
|
+
function jsxBindings(program: Program): ReadonlySet<string> {
|
|
19
|
+
const cached = jsxBindingsByProgram.get(program)
|
|
20
|
+
if (cached !== undefined) return cached
|
|
21
|
+
const names = new Set<string>()
|
|
22
|
+
walk(program, (node) => {
|
|
23
|
+
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && node.init !== null && containsJsx(node.init)) names.add(node.id.name)
|
|
24
|
+
else if (node.type === 'FunctionDeclaration' && node.id !== null && node.body !== null && containsJsx(node.body)) names.add(node.id.name)
|
|
25
|
+
return undefined
|
|
26
|
+
})
|
|
27
|
+
jsxBindingsByProgram.set(program, names)
|
|
28
|
+
return names
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A child like `{props.children}`, `{fields}` or `{renderFields()}`, `fields` and `renderFields` bound to JSX in the file: the check cannot see which controls it renders. Text such as `{errors.email}` or `{t('title')}` is not. */
|
|
32
|
+
export function hasOpaqueChild(children: readonly Node[], program: Program): boolean {
|
|
33
|
+
return children.some((child) => {
|
|
34
|
+
if (child.type !== 'JSXExpressionContainer' || child.expression.type === 'JSXEmptyExpression') return false
|
|
35
|
+
const expr = unwrapTsExpr(child.expression)
|
|
36
|
+
if (expr.type === 'Identifier') return expr.name === 'children' || jsxBindings(program).has(expr.name)
|
|
37
|
+
if (expr.type === 'MemberExpression') return !expr.computed && expr.property.type === 'Identifier' && expr.property.name === 'children'
|
|
38
|
+
return expr.type === 'CallExpression' && expr.callee.type === 'Identifier' && jsxBindings(program).has(expr.callee.name)
|
|
39
|
+
})
|
|
40
|
+
}
|
package/src/compiler/analyze.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { bindingUnits, checkStaticSpreadHandlers, collectUnitInits, findSpreadIn
|
|
|
24
24
|
|
|
25
25
|
const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction', 'resource'])
|
|
26
26
|
// Primitives whose result is reactive state another module can import and read.
|
|
27
|
-
const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
|
|
27
|
+
const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store', 'resource'])
|
|
28
28
|
const PRUNELLE_SOURCES = new Set(['prunelle'])
|
|
29
29
|
const PRUNELLE_SSR_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
|
|
30
30
|
const PRUNELLE_SERVER_SOURCES = new Set(['prunelle/server'])
|
|
@@ -63,7 +63,8 @@ export interface ModuleAnalysis extends Interactivity {
|
|
|
63
63
|
hasPaths: boolean
|
|
64
64
|
usesRenderContext: boolean
|
|
65
65
|
defaultHydrate: string | undefined
|
|
66
|
-
|
|
66
|
+
/** Per component tag, the `$hydrate` modes of its uses (`''` for a use with none, which takes the island file's own mode). */
|
|
67
|
+
hydrateUses: Map<string, Set<string>>
|
|
67
68
|
/** `$hydrate` modes the module writes; `*` stands for one computed at runtime. */
|
|
68
69
|
hydrateModes: Set<string>
|
|
69
70
|
/** Component tags the module renders, `NS.Tag` included. */
|
|
@@ -267,7 +268,7 @@ function scanPrunelleImport(scan: ImportScan, source: string, imported: string,
|
|
|
267
268
|
guarded(start, () => { throw islandRemoved(filename, start) })
|
|
268
269
|
if (STATE_PRIMITIVES.has(imported))
|
|
269
270
|
scan.stateCallees.add(local)
|
|
270
|
-
if (imported === 'signal' || imported === 'computed')
|
|
271
|
+
if (imported === 'signal' || imported === 'computed' || imported === 'resource')
|
|
271
272
|
scan.signalCallees.add(local)
|
|
272
273
|
if (imported === 'effect')
|
|
273
274
|
scan.effectCallees.add(local)
|
|
@@ -308,10 +309,10 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
308
309
|
scan.localInits.set(d.id.name, d.init)
|
|
309
310
|
}
|
|
310
311
|
}
|
|
311
|
-
// `import X from './x'; export default X` (or `export { X }`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`.
|
|
312
|
+
// `import X from './x'; export default X` (or `export { X }`, or `export const Y = X`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`; a namespace import follows like `export * as X from './x'`.
|
|
312
313
|
const reexportImported = (exported: string, local: string, start: number): void => {
|
|
313
314
|
for (const imp of imports.imports) {
|
|
314
|
-
const spec = imp.specifiers.find(s => s.local === local
|
|
315
|
+
const spec = imp.specifiers.find(s => s.local === local)
|
|
315
316
|
if (spec !== undefined) {
|
|
316
317
|
scan.reexports.push({ exported, local: spec.imported, source: imp.source, start })
|
|
317
318
|
return
|
|
@@ -337,7 +338,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
337
338
|
}
|
|
338
339
|
else if (stmt.type === 'ExportAllDeclaration') {
|
|
339
340
|
if (stmt.exportKind !== 'type')
|
|
340
|
-
scan.reexports.push({ exported: '*', local: '*', source: stmt.source.value, start: stmt.start })
|
|
341
|
+
scan.reexports.push({ exported: (stmt.exported === null ? undefined : exportedName(stmt.exported)) ?? '*', local: '*', source: stmt.source.value, start: stmt.start })
|
|
341
342
|
}
|
|
342
343
|
else if (stmt.type === 'ExportDefaultDeclaration') {
|
|
343
344
|
const decl = unwrapTsExpr(stmt.declaration)
|
|
@@ -367,7 +368,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
367
368
|
scan.defaultLocal = local
|
|
368
369
|
}
|
|
369
370
|
if (stmt.declaration !== null)
|
|
370
|
-
scanExportedDeclaration(scan, stmt.declaration, filename, imports, collectInits, addExport)
|
|
371
|
+
scanExportedDeclaration(scan, stmt.declaration, filename, imports, collectInits, addExport, reexportImported)
|
|
371
372
|
}
|
|
372
373
|
}
|
|
373
374
|
const hydrateLocal = scan.defaultHydrate === undefined ? scan.exportLocals.get('hydrate') : undefined
|
|
@@ -376,7 +377,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
376
377
|
return scan
|
|
377
378
|
}
|
|
378
379
|
|
|
379
|
-
function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<ExportNamedDeclaration['declaration']>, filename: string, imports: ImportScan, collectInits: (decl: VariableDeclaration) => void, addExport: (exported: string, local: string) => void): void {
|
|
380
|
+
function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<ExportNamedDeclaration['declaration']>, filename: string, imports: ImportScan, collectInits: (decl: VariableDeclaration) => void, addExport: (exported: string, local: string) => void, reexportImported: (exported: string, local: string, start: number) => void): void {
|
|
380
381
|
if (decl.type === 'FunctionDeclaration' && decl.id !== null) {
|
|
381
382
|
if (decl.async === true)
|
|
382
383
|
scan.asyncLocals.add(decl.id.name)
|
|
@@ -392,6 +393,8 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
|
|
|
392
393
|
continue
|
|
393
394
|
const name = d.id.name
|
|
394
395
|
addExport(name, name)
|
|
396
|
+
if (d.init?.type === 'Identifier')
|
|
397
|
+
reexportImported(name, d.init.name, d.start)
|
|
395
398
|
if (name === 'prerender' && d.init?.type === 'Literal') {
|
|
396
399
|
if (d.init.value === true)
|
|
397
400
|
scan.hasPrerender = true
|
|
@@ -412,7 +415,8 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
|
|
|
412
415
|
interface BodyScan {
|
|
413
416
|
hasJsx: boolean
|
|
414
417
|
usesRenderContext: boolean
|
|
415
|
-
|
|
418
|
+
/** Per component tag, the `$hydrate` modes of its uses (`''` for a use with none, which takes the island file's own mode). */
|
|
419
|
+
hydrateUses: Map<string, Set<string>>
|
|
416
420
|
hydrateModes: Set<string>
|
|
417
421
|
jsxTags: Set<string>
|
|
418
422
|
dynamicImports: { source: string, start: number }[]
|
|
@@ -425,7 +429,7 @@ const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSa
|
|
|
425
429
|
// Walks each top-level binding for JSX, mistakes, action() placement and what makes it run in the browser.
|
|
426
430
|
function scanBody(program: Program, filename: string, code: string, imports: ImportScan, decls: DeclarationScan, warnings: CompilerWarning[], loadCode: ReadonlySet<Node>): BodyScan {
|
|
427
431
|
const units = bindingUnits(program)
|
|
428
|
-
const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext,
|
|
432
|
+
const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext, hydrateUses: new Map(), hydrateModes: new Set(), jsxTags: new Set(), dynamicImports: [], bindings: [], units }
|
|
429
433
|
const tracked = new Set(units.map(u => u.name))
|
|
430
434
|
for (const imp of imports.imports) {
|
|
431
435
|
for (const spec of imp.specifiers)
|
|
@@ -512,6 +516,7 @@ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>,
|
|
|
512
516
|
binding.serverOnlyTag ??= member
|
|
513
517
|
}
|
|
514
518
|
}
|
|
519
|
+
let useMode = ''
|
|
515
520
|
for (const attr of node.attributes) {
|
|
516
521
|
if (attr.type === 'JSXSpreadAttribute') {
|
|
517
522
|
if (!isComponent && tag !== '') {
|
|
@@ -528,13 +533,14 @@ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>,
|
|
|
528
533
|
const mode = hydrateMode(attr.value)
|
|
529
534
|
guarded(attr.start, () => checkHydrateMode(mode, `$hydrate="${mode}"`, filename))
|
|
530
535
|
body.hydrateModes.add(mode)
|
|
531
|
-
|
|
532
|
-
body.deferredIslandTags.add(tag)
|
|
536
|
+
useMode = mode
|
|
533
537
|
}
|
|
534
538
|
// A handler or ref on a component tag is a prop for that component; only a DOM element binds it in the browser.
|
|
535
539
|
if (!isComponent && tag !== '' && (EVENT_ATTR.test(attrName) || attrName === 'ref'))
|
|
536
540
|
binding.fact ??= { reason: `uses ${attrName}`, offset: attr.start }
|
|
537
541
|
}
|
|
542
|
+
if (isComponent)
|
|
543
|
+
body.hydrateUses.set(tag, (body.hydrateUses.get(tag) ?? new Set()).add(useMode))
|
|
538
544
|
}
|
|
539
545
|
|
|
540
546
|
// `prunelle.signal(...)`, `prunelle.Head` and the like, through a namespace import of prunelle.
|
|
@@ -549,7 +555,7 @@ function scanPrunelleMember(node: Extract<Node, { type: 'MemberExpression' }>, b
|
|
|
549
555
|
binding.fact ??= { reason: `calls ${callee}`, offset: node.start }
|
|
550
556
|
if (STATE_PRIMITIVES.has(member))
|
|
551
557
|
imports.stateCallees.add(callee)
|
|
552
|
-
if (member === 'signal' || member === 'computed')
|
|
558
|
+
if (member === 'signal' || member === 'computed' || member === 'resource')
|
|
553
559
|
imports.signalCallees.add(callee)
|
|
554
560
|
if (RENDER_CONTEXT_IMPORTS.has(member))
|
|
555
561
|
body.usesRenderContext = true
|
|
@@ -644,7 +650,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
|
|
|
644
650
|
hasPaths: decls.hasPaths,
|
|
645
651
|
usesRenderContext: body.usesRenderContext,
|
|
646
652
|
defaultHydrate: decls.defaultHydrate,
|
|
647
|
-
|
|
653
|
+
hydrateUses: body.hydrateUses,
|
|
648
654
|
hydrateModes: body.hydrateModes,
|
|
649
655
|
jsxTags: body.jsxTags,
|
|
650
656
|
asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get('default') ?? 'default']) : decls.asyncLocals,
|