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.
- package/llms.txt +5 -5
- package/package.json +1 -1
- package/src/a11y/declaration.ts +4 -0
- package/src/a11y/index.ts +11 -0
- package/src/build/bundle.ts +2 -2
- package/src/build/files.ts +9 -0
- package/src/build/first-load.ts +2 -3
- package/src/build/index.ts +6 -12
- package/src/build/island-promote.ts +69 -8
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +4 -2
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +7 -4
- package/src/build/reach.ts +92 -28
- package/src/build/static-headers.ts +27 -8
- package/src/cli/check-forms.ts +60 -34
- package/src/cli/check-imports.ts +9 -3
- package/src/cli/check.ts +5 -15
- package/src/cli/new.ts +1 -1
- package/src/cli/upgrade.ts +4 -8
- package/src/compiler/analyze.ts +19 -41
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +21 -322
- package/src/compiler/compliance-eco.ts +4 -4
- package/src/compiler/compliance-urls.ts +5 -3
- package/src/compiler/compliance.ts +68 -17
- package/src/compiler/expr-context.ts +113 -44
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/dom/extras.ts +28 -26
- package/src/dom/island.ts +49 -34
- package/src/eco/declaration.ts +87 -16
- package/src/eco/index.ts +7 -3
- package/src/plugins/config.ts +13 -8
- package/src/reactivity/store.ts +19 -7
- package/src/server/action.ts +137 -40
- package/src/server/errors.ts +3 -0
- package/src/server/form-schema.ts +6 -12
- package/src/server/index.ts +6 -6
- package/src/server/page.ts +15 -0
- package/src/server/route-cache.ts +99 -3
- package/src/server/route-table.ts +23 -13
- package/src/server/standard-schema.ts +17 -0
- package/src/ssr/context.ts +1 -1
- package/src/ssr/index.ts +4 -2
- package/src/ssr/region.ts +18 -9
package/llms.txt
CHANGED
|
@@ -45,13 +45,13 @@
|
|
|
45
45
|
- Params arrive percent-decoded; a segment holding an encoded `/`, `\` or NUL, or a `.`/`..` segment, matches no dynamic route (404) unless a plugin catch-all route sets `encodedSlashes`, so a param is safe to join into a path. Static pages, `public/` files and `prunelle start --static` decode by the same rule (`/a%2fb.txt` never serves `a/b.txt`).
|
|
46
46
|
- API routes: `.ts` files exporting standard `HTTP_METHOD_EXPORTS` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`) receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect(location, status?, { external? })`, `deny()`). `redirect()` stays on this site: a target on another origin throws unless `{ external: true }`, so never pass one read from the request. CSRF checks run on every method outside the safe allowlist (`GET`, `HEAD`, `OPTIONS`), trusting only the forwarded origin when `trustProxy` resolves one (or `trustedOrigins`). `export const csrf = false` opts out of origin checks (webhooks, bearer APIs).
|
|
47
47
|
- Prerendering: `export const prerender = true` (+ `export function paths() { return ['/posts/a'] }`, required for dynamic routes and for every dynamic page under `--static`, or `prunelle build` fails; unlisted params return `404`, and so does a listed URL that answered other than `200` at build, which the build warns about). Skipped in `prunelle dev`. Static pages that read nothing from the request or clock are reported `cacheable` by `prunelle inspect` and prerender automatically with `autoPrerender: true` or `prunelle build --auto-prerender`.
|
|
48
|
-
- Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d' }`) serves a bounded in-memory LRU render (`routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...` (`private, no-cache` under an app `_middleware.ts`, which may gate it; the server cache still serves it behind the middleware), with a weak `ETag` that a matching `If-None-Match` turns into a `304`. Its key leaves out `utm_*`, `gclid`, `gbraid`, `wbraid`, `dclid`, `fbclid`, `msclkid`, `mc_cid` and `mc_eid`, so a campaign link reuses the entry (a page showing them reads them uncached). A cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` headers, `getActionError()`,
|
|
49
|
-
- **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins). A page with no `<link rel="icon">` gets `<link rel="icon" href="data:,">`, so no `/favicon.ico`
|
|
48
|
+
- Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d' }`) serves a bounded in-memory LRU render (`routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...` (`private, no-cache` under an app `_middleware.ts`, which may gate it; the server cache still serves it behind the middleware), with a weak `ETag` that a matching `If-None-Match` turns into a `304`. Its key leaves out `utm_*`, `gclid`, `gbraid`, `wbraid`, `dclid`, `fbclid`, `msclkid`, `mc_cid` and `mc_eid`, so a campaign link reuses the entry (a page showing them reads them uncached). A cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` or dynamic/bulk headers, `getActionError()`, `<ConsentGate>`, or passing `ctx`/`props`/`request` to a helper that does (or cannot be followed) fails `prunelle check` and `prunelle build` naming the read; at runtime the route cache also refuses to store any render that reads private request data.
|
|
49
|
+
- **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins). A page with no `<link rel="icon">` and no `public/favicon.ico` gets `<link rel="icon" href="data:,">`, so no `/favicon.ico` 404.
|
|
50
50
|
- `<Suspense fallback={<p>Loading</p>} error={<p>Failed</p>}><AsyncComp /></Suspense>` streams resolved HTML inline with 0 KB external JS. It takes exactly one child; an async component anywhere but as the only child of `<Suspense>` fails build and check, even inside an async page. Boundaries nest, time out after `streamTimeout` (default `30000` ms), and their errors also fire `onError`.
|
|
51
51
|
- `<Catch fallback={<p>Failed</p> | (error, retry) => ...}>` renders its fallback in place of children that throw or an awaited child that rejects, on the server (firing `onError`; nothing streams) and in an island, where it also catches a child effect's later throw and `retry()` renders the children again (there it is written as a tag: calling `Catch()` as a function throws); errors thrown by event handlers are not caught.
|
|
52
52
|
- **Regions** (`<Region>` from `prunelle`, swapped by `regions()` from `@prunellejs/spa`): `<Region name="pane" as="section" ...attrs>children</Region>` is server-only like `Head` and renders `<section data-pru-region="pane">`. `<a href data-pru-target="pane">` and `<form data-pru-target="pane">` swap that region in place with the server's answer; without JS the link or form loads the whole page. Load more, live search, nested regions, `refreshRegion()` and the mistakes it reports: `node_modules/@prunellejs/spa/llms.txt`.
|
|
53
53
|
- **Actions (`prunelle/server` & `useAction` from `prunelle`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)`, a top-level named export so Prunelle can assign it a URL. `ctx` provides `redirect()` and `deny(status, message, fieldErrors?)`.
|
|
54
|
-
- Zero-JS form: `<form action={fn} method="post">`. Array fields are coerced from checkboxes/multi-selects. SSR adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern` and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute (0 B client JS, no implicit `<option>` tags). A validation failure sets an `HttpOnly` flash cookie, read with `getActionError(ctx.locals)` (the flash is signed with `PRUNELLE_FORM_SECRET` or `AUTH_SECRET`; its `values` are the fields the action schema declares, minus secrets such as password, token, card or `format: "password"`, or exactly `flashFields`; a schema with no JSON Schema output declares none, so list `flashFields`), and redirects `303` to the trusted Referer.
|
|
54
|
+
- Zero-JS form: `<form action={fn} method="post">`. Array fields are coerced from checkboxes/multi-selects (`name="tags"` or `name="tags[]"` always parses as an array `tags`, and dotted names like `name="address.city"` parse into nested objects `{ address: { city } }`). SSR adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern` and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute (0 B client JS, no implicit `<option>` tags). A validation failure sets an `HttpOnly` flash cookie, read with `getActionError(ctx.locals)` (the flash is signed with `PRUNELLE_FORM_SECRET` or `AUTH_SECRET`; its `values` are the fields the action schema declares, minus secrets such as password, token, card or `format: "password"`, or exactly `flashFields`; a schema with no JSON Schema output declares none, so list `flashFields`), and redirects `303` to the trusted Referer.
|
|
55
55
|
- `protect: { rateLimit?: { max, windowMs, key? }, honeypot?: boolean | string, minTime?: number }` (or top-level `rateLimit`) enforces `rateLimit` (`429` + `Retry-After` / flash+303) before body parsing, then honeypot/`minTime`, then schema validation. It renders a hidden honeypot and an action-URL-bound HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically and refuses bots, fast submits and timestamps older than two hours with `400` and the one message `Submission rejected` before the handler runs. Set `PRUNELLE_FORM_SECRET` or `AUTH_SECRET` in production when using `minTime`, else Prunelle logs a warning when the action is defined (the key is derived from it with HKDF). A `minTime` form an island renders only in the browser has no timestamp and is refused (`prunelle dev` says so): render it on the first render, hidden until needed. The timestamp is signed per request, so a `minTime` form on a page exporting `prerender = true` or `cache` fails `prunelle check` and `prunelle build` (`action/min-time-frozen`), a `--static` export of one fails the build, and `autoPrerender` leaves such a page to render at request time.
|
|
56
56
|
- `prunelle check` and `prunelle build` report unknown form fields with the closest name (a schema taking extra keys through `additionalProperties` or `patternProperties` accepts those), missing required fields, invalid `<select>` enum options, unsupported schema libraries (once per vendor) and unguarded public form actions without `protect`.
|
|
57
57
|
- Island RPC: `const res = await fn(data)` always resolves to `{ ok: true, data }` or `{ ok: false, status, error, fieldErrors?, issues? }`; it accepts `FormData` for files, and redirects navigate the page (to another site only for `ctx.redirect(url, status, { external: true })`; any other cross-site target fails with `Redirect to another site refused`).
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
- HTML escaping: `raw`, `esc`, `escAttr`, `escJson` (JSON text for a `<script>`), `escXml` (text for a feed or sitemap: also drops the control characters XML forbids).
|
|
69
69
|
- HTTP: `getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, `wantsJson`, `safeEqual` (constant-time secret compare), `readStringFields` (a body's string fields, on a null-prototype record), and `safeRedirect(target, fallback = '/')`, which returns the trimmed target only when it is a path on this site, refusing absolute and protocol-relative URLs, backslashes and control characters (`@prunellejs/auth` and the consent endpoint use it).
|
|
70
70
|
- `createRateLimitStore({ maxKeys?, maxHits? })`: a standalone sliding-window store whose `.limiter({ max, windowMs }).hit(key)` returns 0 or the seconds to wait, and `.peek(key)` the same without counting; plugins use `api.rateLimiter()`. A `rateLimit` with no `key` counts the client's network: an IPv4 address without its port or `::ffff:` mapping, or an IPv6 address's /64; `rateLimitAddress(ip)` gives that key to a custom limiter.
|
|
71
|
-
- Standard Schema: `validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`.
|
|
71
|
+
- Standard Schema: `StandardSchemaV1` (including optional `'~standard'.jsonSchema: { input, output? }` Standard JSON Schema extension), `validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`.
|
|
72
72
|
- `declare module 'prunelle/server' { interface PrunelleLocals { ... } }` types `ctx.locals`; `createServer({ root })` runs a built app inside another program.
|
|
73
73
|
- **French web law & Consent (RGPD, CNIL, RGAA, RGESN, LCEN - 0 B client JS)**: `prunelle check` and production `prunelle build` emit actionable warnings (never hard errors):
|
|
74
74
|
- RGAA: `rgaa/img-alt` (`<img>` without `alt`, or `alt={undefined}`/`alt={false}`, unless `role="presentation"` or `aria-hidden`), `rgaa/form-label` (unlabelled `<input>`/`<select>`/`<textarea>`, or a ui `<Select>` with no `Field`, `<label for>` or `ariaLabel`; a `<Label>` component wraps like `<label>`, and `for={ids.name}` matches `id={ids.name}`), `rgaa/accessible-name` (empty or icon-only `<button>`/`<a>`, `<svg role="img">` without `aria-label` or `<title>`), `rgaa/duplicate-id` (duplicate literal `id` in one component, or a static `id` inside `.map()`), `rgaa/positive-tabindex` (`tabindex > 0`).
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
- `prunelle build [dir] [--static] [--compile [out]] [--auto-prerender] [--analyze] [--json] [--max-js <size>]`: `--analyze` lists each route's eager JS, CSS, fonts, first load (brotli), EcoIndex grade/score/inputs for prerendered routes (as `cnumr/ecoindex_python` computes them, every image and third-party request of the page counted), and its islands with why each is one (`--analyze --json` outputs `BundleReport` JSON); `firstLoadUrls`, `distLocator` and `measureFirstLoad` from `prunelle/config` give plugins the same figure, and `await brotliSize(html)` reads the brotli cache. `--max-js 40kb` fails on a route whose gzipped eager JS is over it; `budget: { js?: '40kb', firstLoad?: '500kb' }` in `prunelle.config.ts` (bytes or KB) does the same on every build, `firstLoad` capping the brotli first load, and `--max-js` overrides `budget.js` for one run.
|
|
95
95
|
- `prunelle eco [dir] [--declaration [path]] [--service <name>] [--org <name>] [--contact <email>]`: builds the app and judges the RGESN 2024 criteria prunelle can measure (4.1 autoplay, 4.4 third parties, 6.1 weight cap from `budget.firstLoad`, 6.3 compression, 6.5 unused resources, 6.7 one domain); `--declaration` writes an editable French declaration page (default `src/routes/ecoconception.tsx`) with each prerendered page's EcoIndex, those verdicts and `[à compléter` placeholders for the rest.
|
|
96
96
|
- `prunelle start [dir] [--port 3000] [--host [addr]]`; `prunelle upgrade [dir] [--no-install]` moves a kay v2 app or workspace onto prunelle (kay v1 left untouched, a folder on neither refused, symbolic links never followed; `sqliteAuthStore()` preserves accounts).
|
|
97
|
-
- Plugin commands: `prunelle a11y [--draft [dest]] [--audit-date YYYY-MM-DD --rate <percent>] [--json] [--routes /a,/b]` (via `a11y()` from `prunelle/config`; axe-core tags `RGAAv4` + WCAG 2.1 A/AA, each result mapped to its RGAA criterion, axe's `incomplete` results reported as `toCheck`, to check by hand; the draft's level comes from the manual audit only, "non conforme" without one, and `prunelle check` warns about `[à compléter : ...]` left in any published statement), `prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`, `prunelle pwa-vapid [--json]`. They load from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`.
|
|
97
|
+
- Plugin commands: `prunelle a11y [--draft [dest]] [--force] [--audit-date YYYY-MM-DD --rate <percent>] [--json] [--routes /a,/b]` (via `a11y()` from `prunelle/config`; axe-core tags `RGAAv4` + WCAG 2.1 A/AA, each result mapped to its RGAA criterion, axe's `incomplete` results reported as `toCheck`, to check by hand; `--draft` refuses to overwrite an existing statement unless `--force` is given; the draft's level comes from the manual audit only, "non conforme" without one, and `prunelle check` warns about `[à compléter : ...]` left in any published statement), `prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`, `prunelle pwa-vapid [--json]`. They load from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`.
|
|
98
98
|
- **CLI (dev, editor & agent tooling)**:
|
|
99
99
|
- `prunelle dev [dir] [--port 3000] [--host [addr]]`: binds loopback `127.0.0.1` by default; answers `421` to a `Host` other than `localhost`, `*.localhost`, an IP address, its `--host` and the hosts of `site` and `trustedOrigins` (against DNS rebinding: add a tunnel's origin to `trustedOrigins`); marks rendered elements with `data-pru-src="file:line:col"` in dev only (production output is byte-identical), and Alt-click opens `$PRUNELLE_EDITOR` or `$VISUAL` in VS Code, Cursor, Zed, JetBrains, Sublime, Helix or a `{file}:{line}:{col}` template; records dev build, crash and runtime errors in `.prunelle-dev/last-errors.jsonl`; runs the app in a child process recycled on `prunelle.config.ts` edits or past 2 GB; edits in `public/` reload without rebuilding.
|
|
100
100
|
- `prunelle render <url> [--method|-X <m>] [--body|-d <data>] [--header|-H "K: V"] [--cookie|-b "k=v"] [-i|--include] [--fresh]`: built on `testApp()`, it builds or reuses `.prunelle-cache/render-build` with no port bound and without touching `dist/`, and prints the body (status, headers and body with `-i`); exit `0` for `2xx`/`3xx`, `1` otherwise.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://prunelle.kaynooo.fr",
|
package/src/a11y/declaration.ts
CHANGED
|
@@ -33,6 +33,8 @@ export interface AccessibilityDeclarationOptions {
|
|
|
33
33
|
date?: Date | undefined
|
|
34
34
|
/** Write the generated TSX page to disk (default: `true`). */
|
|
35
35
|
write?: boolean | undefined
|
|
36
|
+
/** Overwrite an existing declaration file at `outPath` (default: `false`). */
|
|
37
|
+
force?: boolean | undefined
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
export interface AccessibilityDeclarationResult {
|
|
@@ -356,6 +358,8 @@ ${contactLine(options.contactEmail?.trim() || undefined)}
|
|
|
356
358
|
`
|
|
357
359
|
|
|
358
360
|
if (options.write !== false) {
|
|
361
|
+
if (existsSync(dest) && options.force !== true)
|
|
362
|
+
throw new Error(`prunelle: ${relativePath} already exists: pass --force to overwrite it.`)
|
|
359
363
|
mkdirSync(dirname(dest), { recursive: true })
|
|
360
364
|
writeFileSync(dest, content)
|
|
361
365
|
}
|
package/src/a11y/index.ts
CHANGED
|
@@ -4,7 +4,9 @@ import type { RouteManifestEntry } from '../build/manifest'
|
|
|
4
4
|
import type { PrunellePlugin } from '../plugins/types'
|
|
5
5
|
import type { BrowserTest, BrowserTestOptions } from '../test/browser'
|
|
6
6
|
import type { RgaaCriterion } from './rgaa-map'
|
|
7
|
+
import { existsSync } from 'node:fs'
|
|
7
8
|
import { resolve } from 'node:path'
|
|
9
|
+
import { relPosix } from '../build/files'
|
|
8
10
|
import { definePlugin } from '../plugins/config'
|
|
9
11
|
import { loadConfig } from '../plugins/load'
|
|
10
12
|
import { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement } from './declaration'
|
|
@@ -381,6 +383,7 @@ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yP
|
|
|
381
383
|
'all-static': { type: 'boolean', description: 'include static non-dynamic HTML routes alongside prerendered routes' },
|
|
382
384
|
'json': { type: 'boolean', description: 'print the audit report as JSON on stdout' },
|
|
383
385
|
'draft': { type: 'string', optional: { bare: '' }, description: 'write an editable RGAA 4.1.2 accessibility declaration page (default: src/routes/accessibilite.tsx)' },
|
|
386
|
+
'force': { type: 'boolean', description: 'overwrite an existing declaration file when used with --draft' },
|
|
384
387
|
'out': { type: 'string', description: 'destination path for --draft (default: src/routes/accessibilite.tsx)' },
|
|
385
388
|
'audit-date': { type: 'string', description: 'day the manual RGAA audit ended (YYYY-MM-DD), written into --draft with --rate' },
|
|
386
389
|
'rate': { type: 'string', description: 'applicable RGAA criteria the manual audit found met, in percent: 100 is totally, 50 or more partially compliant' },
|
|
@@ -412,12 +415,19 @@ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yP
|
|
|
412
415
|
: undefined
|
|
413
416
|
|
|
414
417
|
const wantDraft = values.draft !== undefined
|
|
418
|
+
const force = values.force === true
|
|
415
419
|
const draftDest = values.out
|
|
416
420
|
?? (values.draft !== undefined && values.draft !== '' ? values.draft : undefined)
|
|
417
421
|
?? positionals[0]
|
|
418
422
|
?? pluginOptions.declarationPath
|
|
419
423
|
?? DEFAULT_DECLARATION_PATH
|
|
420
424
|
|
|
425
|
+
if (wantDraft && !force) {
|
|
426
|
+
const dest = resolve(root, draftDest)
|
|
427
|
+
if (existsSync(dest))
|
|
428
|
+
throw new Exit(`${relPosix(root, dest)} already exists: pass --force to overwrite it`, 1)
|
|
429
|
+
}
|
|
430
|
+
|
|
421
431
|
const report = await auditAccessibility({
|
|
422
432
|
root,
|
|
423
433
|
routes: rawRoutes,
|
|
@@ -437,6 +447,7 @@ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yP
|
|
|
437
447
|
contactEmail: values.contact ?? pluginOptions.contactEmail,
|
|
438
448
|
siteUrl: (await loadConfig(root)).site,
|
|
439
449
|
audit: manualAudit,
|
|
450
|
+
force,
|
|
440
451
|
})
|
|
441
452
|
}
|
|
442
453
|
|
package/src/build/bundle.ts
CHANGED
|
@@ -218,7 +218,7 @@ function buildClientSignature(
|
|
|
218
218
|
return ''
|
|
219
219
|
return JSON.stringify({
|
|
220
220
|
minify: env.minify,
|
|
221
|
-
assetPrefix: env.assetPrefix,
|
|
221
|
+
assetPrefix: env.assetPrefix, lang: env.lang,
|
|
222
222
|
isDev: env.isDev,
|
|
223
223
|
nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
|
|
224
224
|
transforms: transformsKey,
|
|
@@ -515,7 +515,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
515
515
|
const serverSignature = cache !== undefined
|
|
516
516
|
? JSON.stringify({
|
|
517
517
|
serverRoot,
|
|
518
|
-
assetPrefix: env.assetPrefix,
|
|
518
|
+
assetPrefix: env.assetPrefix, lang: env.lang,
|
|
519
519
|
isDev: env.isDev,
|
|
520
520
|
transforms: transforms.key,
|
|
521
521
|
entries: [...entries].sort(),
|
package/src/build/files.ts
CHANGED
|
@@ -89,6 +89,12 @@ export function assertSafeOutDir(root: string, outDir: string, routesDir: string
|
|
|
89
89
|
if (dirname(realOut) === realOut || isInside(realOut, realRoot, { orSame: true })) {
|
|
90
90
|
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
|
|
91
91
|
}
|
|
92
|
+
if (existsSync(publicDir)) {
|
|
93
|
+
const realPublic = realpathSync(publicDir)
|
|
94
|
+
if (isInside(realPublic, realOut, { orSame: true })) {
|
|
95
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is inside publicDir ("${realPublic}"), which would publish the server bundle: set outDir outside public/ (e.g. "dist").`)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
92
98
|
}
|
|
93
99
|
catch (err) {
|
|
94
100
|
if (err instanceof Error && err.message.startsWith('prunelle build: refusing unsafe outDir'))
|
|
@@ -107,6 +113,9 @@ export function assertSafeOutDir(root: string, outDir: string, routesDir: string
|
|
|
107
113
|
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
|
|
108
114
|
}
|
|
109
115
|
}
|
|
116
|
+
if (isInside(publicDir, outDir)) {
|
|
117
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it sits inside publicDir ("${publicDir}"), which would publish the server bundle as public files: set outDir outside public/ (e.g. "dist").`)
|
|
118
|
+
}
|
|
110
119
|
// If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
|
|
111
120
|
if (!isInside(root, outDir) && existsSync(outDir)) {
|
|
112
121
|
for (const marker of ['package.json', 'prunelle.config.ts', 'src']) {
|
package/src/build/first-load.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
4
4
|
import { extname, join, posix } from 'node:path'
|
|
5
|
-
import { appBrotliCacheDir, brotliSync } from './precompress'
|
|
5
|
+
import { appBrotliCacheDir, brotliSync, COMPRESSIBLE_EXTS } from './precompress'
|
|
6
6
|
|
|
7
7
|
// A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
|
|
8
8
|
export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
|
|
@@ -22,7 +22,6 @@ const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
|
|
|
22
22
|
const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
|
|
23
23
|
const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
|
|
24
24
|
const FETCHED_RELS = new Set(['stylesheet', 'modulepreload', 'preload'])
|
|
25
|
-
const COMPRESSED_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
|
|
26
25
|
const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf'])
|
|
27
26
|
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico'])
|
|
28
27
|
const SKIPPED_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i
|
|
@@ -159,7 +158,7 @@ function servedSize(file: string): number {
|
|
|
159
158
|
if (existsSync(sidecar))
|
|
160
159
|
return statSync(sidecar).size
|
|
161
160
|
const raw = readFileSync(file)
|
|
162
|
-
if (!
|
|
161
|
+
if (!COMPRESSIBLE_EXTS.has(extname(file).toLowerCase()))
|
|
163
162
|
return raw.byteLength
|
|
164
163
|
const key = `${file}:${raw.byteLength}`
|
|
165
164
|
let packed = brotliCache.get(key)
|
package/src/build/index.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { assertSafeOutDir, fileSize, isHiddenPublicPath, isInNodeModules, relPos
|
|
|
26
26
|
import { isInside } from './is-inside'
|
|
27
27
|
import { ModuleGraph } from './graph'
|
|
28
28
|
import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
|
|
29
|
+
import { formatIslandValueWarnings } from './island-promote'
|
|
29
30
|
import { planIslands } from './islands'
|
|
30
31
|
import { buildActionEntries, buildRouteEntries } from './manifest'
|
|
31
32
|
import { createPluginHost, createPublicFiles } from './plugin-host'
|
|
@@ -238,18 +239,7 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
|
|
|
238
239
|
}
|
|
239
240
|
}
|
|
240
241
|
if (!run.isDev) {
|
|
241
|
-
const projectWarnings = collectProjectComplianceWarnings({
|
|
242
|
-
root: run.root,
|
|
243
|
-
srcDir: join(run.root, 'src'),
|
|
244
|
-
routesDir: run.routesDir,
|
|
245
|
-
routeFiles,
|
|
246
|
-
analyses: graph.analyses,
|
|
247
|
-
compliance: run.compliance,
|
|
248
|
-
consentMaxAge: run.consentMaxAge,
|
|
249
|
-
site: run.site,
|
|
250
|
-
lang: run.lang,
|
|
251
|
-
langFromPlugin: pluginSetsLang(run.plugins),
|
|
252
|
-
})
|
|
242
|
+
const projectWarnings = collectProjectComplianceWarnings({ root: run.root, srcDir: join(run.root, 'src'), routesDir: run.routesDir, publicDir: run.publicDir, routeFiles, analyses: graph.analyses, compliance: run.compliance, consentMaxAge: run.consentMaxAge, site: run.site, lang: run.lang, langFromPlugin: pluginSetsLang(run.plugins) })
|
|
253
243
|
for (const warning of projectWarnings)
|
|
254
244
|
console.warn(warning)
|
|
255
245
|
}
|
|
@@ -432,6 +422,10 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
432
422
|
|
|
433
423
|
const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
|
|
434
424
|
const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
|
|
425
|
+
if (!isDev) {
|
|
426
|
+
for (const warning of formatIslandValueWarnings(islands.valueUses, root, graph, f => graph.source(f), run.compliance))
|
|
427
|
+
console.warn(warning)
|
|
428
|
+
}
|
|
435
429
|
await validateAppForms(run, allRouteFiles, graph)
|
|
436
430
|
|
|
437
431
|
mkdirSync(clientDir, { recursive: true })
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
// Which modules run in the browser: following re-exports to the binding they name, and promoting what reads an interactive import.
|
|
2
2
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
4
|
+
import type { ComplianceConfig } from '../compiler/compliance'
|
|
4
5
|
import type { CompilerWarning } from '../compiler/mistakes'
|
|
5
6
|
import type { IslandIssue } from './islands'
|
|
6
7
|
import type { ModuleGraph } from './graph'
|
|
7
8
|
import { wholeLoadShippedWarning } from '../compiler/analyze'
|
|
9
|
+
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
8
10
|
import { withStateReads } from '../compiler/interactivity'
|
|
9
|
-
import {
|
|
11
|
+
import { walkScoped } from '../compiler/scope'
|
|
12
|
+
import { formatDiagnostic, formatLoc } from '../compiler/shared'
|
|
13
|
+
import { isInNodeModules, isTsFile, relPosix } from './files'
|
|
10
14
|
|
|
11
15
|
export type LoadModule = (file: string) => ModuleAnalysis | undefined
|
|
12
16
|
|
|
@@ -120,15 +124,72 @@ function interactivityChanged(prev: ModuleAnalysis, next: { isInteractive: boole
|
|
|
120
124
|
}
|
|
121
125
|
|
|
122
126
|
/** An imported island a module reads as a value (`const D = Counter`, `{ C: Counter }`, `c={Counter}`), which makes what holds it an island. */
|
|
123
|
-
export interface IslandValueUse { file: string, offset: number, name: string }
|
|
127
|
+
export interface IslandValueUse { file: string, offset: number, offsets?: readonly number[] | undefined, name: string }
|
|
124
128
|
|
|
125
129
|
/** A compiler warning that only applies once a module is promoted to an island across files. */
|
|
126
130
|
export interface PromotedWarning { file: string, warning: CompilerWarning }
|
|
127
131
|
|
|
128
132
|
const COMPONENT_NAME_RE = /^[A-Z]/
|
|
129
133
|
|
|
130
|
-
//
|
|
131
|
-
const
|
|
134
|
+
// Every binding's value read of `local`, in source order.
|
|
135
|
+
const allValueReads = (analysis: ModuleAnalysis, local: string): number[] =>
|
|
136
|
+
analysis.bindings.map(b => b.valueRefs.get(local)).filter((offset): offset is number => offset !== undefined)
|
|
137
|
+
|
|
138
|
+
// All unshadowed non-JSX value reads of `local` in `analysis.program`, used only when a line-ignore hides the first recorded offset.
|
|
139
|
+
function allProgramValueReads(analysis: ModuleAnalysis, local: string): number[] {
|
|
140
|
+
const offsets: number[] = []
|
|
141
|
+
for (const stmt of analysis.program.body) {
|
|
142
|
+
if (stmt.type === 'ImportDeclaration' || stmt.type === 'ExportAllDeclaration')
|
|
143
|
+
continue
|
|
144
|
+
const target = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
|
|
145
|
+
if (target === null)
|
|
146
|
+
continue
|
|
147
|
+
walkScoped(target, {
|
|
148
|
+
onIdentifier(id) {
|
|
149
|
+
if (id.name === local)
|
|
150
|
+
offsets.push(id.start)
|
|
151
|
+
},
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
return offsets
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Formats `[rgesn/island-by-value]` warnings for `prunelle check` and production `prunelle build`, honoring `compliance.ignore` and `prunelle-ignore`. */
|
|
158
|
+
export function formatIslandValueWarnings(
|
|
159
|
+
uses: readonly IslandValueUse[],
|
|
160
|
+
root: string,
|
|
161
|
+
graph: Pick<ModuleGraph, 'analyses'>,
|
|
162
|
+
sourceOf: (file: string) => string,
|
|
163
|
+
compliance: ComplianceConfig | undefined,
|
|
164
|
+
): string[] {
|
|
165
|
+
const rule = 'rgesn/island-by-value'
|
|
166
|
+
if (uses.length === 0 || isRuleIgnored(rule, compliance))
|
|
167
|
+
return []
|
|
168
|
+
const ignoresByFile = new Map<string, ReturnType<typeof parsePrunelleIgnores>>()
|
|
169
|
+
const warnings: string[] = []
|
|
170
|
+
for (const use of uses) {
|
|
171
|
+
const code = sourceOf(use.file)
|
|
172
|
+
let ignores = ignoresByFile.get(use.file)
|
|
173
|
+
if (ignores === undefined) {
|
|
174
|
+
ignores = parsePrunelleIgnores(code)
|
|
175
|
+
ignoresByFile.set(use.file, ignores)
|
|
176
|
+
}
|
|
177
|
+
if (ignores.fileRules.has(rule))
|
|
178
|
+
continue
|
|
179
|
+
const recorded = use.offsets ?? [use.offset]
|
|
180
|
+
let offset = recorded.find(o => !isIgnoredAt(ignores, rule, o))
|
|
181
|
+
if (offset === undefined) {
|
|
182
|
+
const analysis = graph.analyses.get(use.file)
|
|
183
|
+
if (analysis !== undefined)
|
|
184
|
+
offset = allProgramValueReads(analysis, use.name).find(o => !isIgnoredAt(ignores, rule, o))
|
|
185
|
+
}
|
|
186
|
+
if (offset === undefined)
|
|
187
|
+
continue
|
|
188
|
+
const rel = relPosix(root, use.file)
|
|
189
|
+
warnings.push(formatDiagnostic(formatLoc(rel, code, offset), `[${rule}] ${use.name} is an island read as a value, not rendered as <${use.name} />, so what holds it hydrates as an island and ships its code too: render <${use.name} /> itself where it shows, or // prunelle-ignore ${rule} when the whole component should hydrate.`, 'warning'))
|
|
190
|
+
}
|
|
191
|
+
return warnings
|
|
192
|
+
}
|
|
132
193
|
|
|
133
194
|
export function createPromoter(
|
|
134
195
|
graph: ModuleGraph,
|
|
@@ -173,11 +234,11 @@ export function createPromoter(
|
|
|
173
234
|
const recordValueUses = (file: string, analysis: ModuleAnalysis): void => {
|
|
174
235
|
for (const imp of analysis.imports) {
|
|
175
236
|
for (const spec of imp.specifiers) {
|
|
176
|
-
const
|
|
177
|
-
if (
|
|
237
|
+
const offsets = spec.imported === '*' || !COMPONENT_NAME_RE.test(spec.local) ? [] : allValueReads(analysis, spec.local)
|
|
238
|
+
if (offsets.length === 0 || reportedValueUses.has(`${file}#${spec.local}`) || interactiveKind(file, imp.source, spec.imported) !== 'export')
|
|
178
239
|
continue
|
|
179
240
|
reportedValueUses.add(`${file}#${spec.local}`)
|
|
180
|
-
valueUses.push({ file, offset, name: spec.local })
|
|
241
|
+
valueUses.push({ file, offset: offsets[0]!, offsets, name: spec.local })
|
|
181
242
|
}
|
|
182
243
|
}
|
|
183
244
|
}
|
|
@@ -218,7 +279,7 @@ export function createPromoter(
|
|
|
218
279
|
promotedWarnings.push({ file, warning })
|
|
219
280
|
nextWarnings = [...analysis.warnings, warning]
|
|
220
281
|
}
|
|
221
|
-
|
|
282
|
+
Object.assign(analysis, promoted, { warnings: nextWarnings })
|
|
222
283
|
return true
|
|
223
284
|
}
|
|
224
285
|
|
package/src/build/output.ts
CHANGED
|
@@ -7,18 +7,15 @@ import { relPosix } from './files'
|
|
|
7
7
|
/** The file prunelle writes into each folder it builds, so a later build knows the folder is its own to replace. */
|
|
8
8
|
export const OUTPUT_MARKER = '.prunelle-output'
|
|
9
9
|
|
|
10
|
-
const LEADING_SLASH_RE = /^\/+/
|
|
11
|
-
|
|
12
10
|
/** Throws unless `outDir` is missing, empty, or a folder prunelle built: replacing it must never delete someone's files. */
|
|
13
|
-
export function assertOwnOutDir(root: string, outDir: string,
|
|
11
|
+
export function assertOwnOutDir(root: string, outDir: string, _assetPrefix?: string): void {
|
|
14
12
|
if (!existsSync(outDir))
|
|
15
13
|
return
|
|
16
14
|
const names = new Set(readdirSync(outDir))
|
|
17
15
|
if (names.size === 0 || names.has(OUTPUT_MARKER))
|
|
18
16
|
return
|
|
19
|
-
// A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's
|
|
20
|
-
|
|
21
|
-
if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
|
|
17
|
+
// A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's default `_pru/` (or kay v2's `_kay/`) folder.
|
|
18
|
+
if ((names.has('manifest.json') && names.has('server')) || names.has('_pru') || names.has('_kay'))
|
|
22
19
|
return
|
|
23
20
|
throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
|
|
24
21
|
}
|
package/src/build/plugin-host.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '.
|
|
|
5
5
|
import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
|
|
6
6
|
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
7
7
|
import { dirname, join, resolve } from 'node:path'
|
|
8
|
+
import { relPosix } from './files'
|
|
8
9
|
import { isInside } from './is-inside'
|
|
9
10
|
import { precompressFiles } from './precompress'
|
|
10
11
|
|
|
@@ -18,9 +19,10 @@ function cleanRel(relPath: string): string {
|
|
|
18
19
|
/** The clean relative path of a file a plugin writes under `base`, or a throw naming the plugin when it climbs out of `base`. */
|
|
19
20
|
function confinedRel(plugin: string, what: string, base: string, relPath: string): string {
|
|
20
21
|
const clean = cleanRel(relPath)
|
|
21
|
-
|
|
22
|
+
const target = resolve(base, clean)
|
|
23
|
+
if (!isInside(base, target))
|
|
22
24
|
throw new Error(`prunelle build: plugin "${plugin}" ${what}("${relPath}") leaves the output folder: use a relative path without "..".`)
|
|
23
|
-
return
|
|
25
|
+
return relPosix(base, target)
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
export interface PublicFiles {
|
package/src/build/precompress.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { getAppContext } from '../plugins/context'
|
|
|
10
10
|
/** Brotli quality of the sidecars: written once per build, downloaded by every visitor, so the smallest the encoder makes. */
|
|
11
11
|
export const BROTLI_QUALITY = 11
|
|
12
12
|
|
|
13
|
-
const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm', '.ttf', '.otf', '.ico'])
|
|
13
|
+
export const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm', '.ttf', '.otf', '.ico'])
|
|
14
14
|
const STALE_MS = 7 * 86_400_000
|
|
15
15
|
|
|
16
16
|
const compress = promisify(brotliCompress)
|
package/src/build/prerender.ts
CHANGED
|
@@ -160,8 +160,9 @@ async function planRoutes(options: PrerenderOptions, modules: Record<string, unk
|
|
|
160
160
|
const mod = modules?.[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
|
|
161
161
|
if (typeof mod.paths === 'function') {
|
|
162
162
|
hasPathsFn = true
|
|
163
|
-
const
|
|
164
|
-
|
|
163
|
+
const source = routeSource(options, route)
|
|
164
|
+
const returned: unknown = await namedPathsError(route, source, mod.paths)
|
|
165
|
+
assertPathUrls(returned, source)
|
|
165
166
|
urls = returned
|
|
166
167
|
}
|
|
167
168
|
else {
|
|
@@ -222,8 +223,10 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
222
223
|
throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
|
|
223
224
|
}
|
|
224
225
|
// A page prunelle chose to prerender by itself falls back to request time quietly; one the app asked for is told.
|
|
225
|
-
if (task.route.autoPrerender !== true)
|
|
226
|
-
|
|
226
|
+
if (task.route.autoPrerender !== true) {
|
|
227
|
+
const isStaticRoute = !task.route.path.includes(':') && !task.route.path.includes('*')
|
|
228
|
+
console.warn(`prunelle build: prerender route "${u}" (${routeSource(options, task.route)}) answered HTTP ${res.status}, ${isStaticRoute ? 'so it renders at request time instead: drop `prerender = true`' : 'so it is not prerendered and answers 404 in production: leave it out of paths()'}, or have it answer 200.`)
|
|
229
|
+
}
|
|
227
230
|
continue
|
|
228
231
|
}
|
|
229
232
|
const ct = res.headers.get('content-type')
|
package/src/build/reach.ts
CHANGED
|
@@ -2,11 +2,45 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
4
|
import type { ModuleGraph } from './graph'
|
|
5
|
-
import type { IslandPlan } from './islands'
|
|
5
|
+
import type { IslandPlan, IslandTarget } from './islands'
|
|
6
6
|
import { islandKey } from './islands'
|
|
7
7
|
|
|
8
8
|
const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
|
|
9
9
|
|
|
10
|
+
interface ModuleEdge {
|
|
11
|
+
source: string
|
|
12
|
+
specifiers?: readonly { local: string, imported: string }[] | undefined
|
|
13
|
+
start: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function orderedEdges(analysis: ModuleAnalysis): readonly ModuleEdge[] {
|
|
17
|
+
const reexports = analysis.reexports
|
|
18
|
+
if (reexports === undefined || reexports.length === 0)
|
|
19
|
+
return analysis.imports
|
|
20
|
+
return [...analysis.imports, ...reexports].sort((a, b) => a.start - b.start)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function edgeBindings(edge: ModuleEdge, bindings: ReadonlyMap<string, IslandTarget> | undefined): IslandTarget[] {
|
|
24
|
+
if (bindings === undefined || edge.specifiers === undefined)
|
|
25
|
+
return []
|
|
26
|
+
const matched: IslandTarget[] = []
|
|
27
|
+
for (const spec of edge.specifiers) {
|
|
28
|
+
if (spec.imported === '*') {
|
|
29
|
+
const prefix = `${spec.local}.`
|
|
30
|
+
for (const [tag, target] of bindings) {
|
|
31
|
+
if (tag.startsWith(prefix))
|
|
32
|
+
matched.push(target)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
const target = bindings.get(spec.local)
|
|
37
|
+
if (target !== undefined)
|
|
38
|
+
matched.push(target)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return matched
|
|
42
|
+
}
|
|
43
|
+
|
|
10
44
|
export interface FileReach {
|
|
11
45
|
/** Island chunks reachable from the file, and the subset loaded eagerly. */
|
|
12
46
|
chunks: Set<string>
|
|
@@ -39,13 +73,15 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
|
|
|
39
73
|
}
|
|
40
74
|
|
|
41
75
|
/** Adds the island chunks of a file reached at level 0; true when its imports ship inside the island and the level stops there. */
|
|
42
|
-
function addIslandChunks(file: string, analysis: ModuleAnalysis, reach: FileReach): boolean {
|
|
76
|
+
function addIslandChunks(file: string, isRoot: boolean, analysis: ModuleAnalysis, reach: FileReach): boolean {
|
|
43
77
|
if (analysis.isInteractive) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
78
|
+
if (isRoot) {
|
|
79
|
+
const chunk = islandChunks.get(`${file}#default`)
|
|
80
|
+
if (chunk !== undefined) {
|
|
81
|
+
reach.chunks.add(chunk)
|
|
82
|
+
if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
|
|
83
|
+
reach.eager.add(chunk)
|
|
84
|
+
}
|
|
49
85
|
}
|
|
50
86
|
// Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
|
|
51
87
|
if (analysis.staticJsxTags.size === 0)
|
|
@@ -88,35 +124,63 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
|
|
|
88
124
|
|
|
89
125
|
let pruned = false
|
|
90
126
|
if (atIslands)
|
|
91
|
-
pruned = addIslandChunks(file, analysis, reach)
|
|
127
|
+
pruned = addIslandChunks(file, file === root, analysis, reach)
|
|
92
128
|
if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
|
|
93
129
|
reach.usesRenderContext = true
|
|
94
130
|
if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
|
|
95
131
|
reach.usesRegion = true
|
|
96
132
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
133
|
+
// The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
|
|
134
|
+
const next = atIslands ? (pruned ? IMPORTS : ISLANDS) : atImports ? IMPORTS : RENDERED
|
|
135
|
+
const deps = depsOf(file)
|
|
136
|
+
if (!atRendered) {
|
|
137
|
+
for (const dep of deps)
|
|
138
|
+
visit(dep, next)
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const depSet = new Set(deps)
|
|
143
|
+
const visitedDeps = new Set<string>()
|
|
144
|
+
const bindings = islands.pageBindings.get(file)
|
|
145
|
+
const visitedBindings = new Set<IslandTarget>()
|
|
146
|
+
const addTargetStyle = (target: IslandTarget): void => {
|
|
147
|
+
if (visitedBindings.has(target))
|
|
148
|
+
return
|
|
149
|
+
visitedBindings.add(target)
|
|
150
|
+
visit(target.file, RENDERED)
|
|
151
|
+
const islCss = islandCssUrl.get(islandKey(target))
|
|
152
|
+
if (islCss !== undefined)
|
|
153
|
+
reach.styles.add(islCss)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Walk imports and re-exports in source order so dependency CSS lands before the importer's CSS (#159).
|
|
157
|
+
for (const edge of orderedEdges(analysis)) {
|
|
158
|
+
const resolved = graph.resolve(file, edge.source)
|
|
159
|
+
if (resolved === undefined)
|
|
160
|
+
continue
|
|
161
|
+
const cssUrl = srcCssToUrl.get(resolved)
|
|
162
|
+
if (cssUrl !== undefined) {
|
|
163
|
+
reach.styles.add(cssUrl)
|
|
164
|
+
continue
|
|
108
165
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
reach.styles.add(cssUrl)
|
|
166
|
+
if (depSet.has(resolved)) {
|
|
167
|
+
visitedDeps.add(resolved)
|
|
168
|
+
visit(resolved, next)
|
|
113
169
|
}
|
|
170
|
+
for (const target of edgeBindings(edge, bindings))
|
|
171
|
+
addTargetStyle(target)
|
|
172
|
+
}
|
|
173
|
+
for (const dep of deps) {
|
|
174
|
+
if (!visitedDeps.has(dep))
|
|
175
|
+
visit(dep, next)
|
|
176
|
+
}
|
|
177
|
+
for (const target of bindings?.values() ?? [])
|
|
178
|
+
addTargetStyle(target)
|
|
179
|
+
if (file === root && analysis.isInteractive) {
|
|
180
|
+
const islCss = islandCssUrl.get(`${file}#default`)
|
|
181
|
+
if (islCss !== undefined)
|
|
182
|
+
reach.styles.add(islCss)
|
|
114
183
|
}
|
|
115
|
-
|
|
116
|
-
// The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
|
|
117
|
-
const next = atIslands ? (pruned ? IMPORTS : ISLANDS) : atImports ? IMPORTS : RENDERED
|
|
118
|
-
for (const dep of depsOf(file))
|
|
119
|
-
visit(dep, next)
|
|
120
184
|
}
|
|
121
185
|
|
|
122
186
|
visit(root, ISLANDS)
|