-
-
Notifications
You must be signed in to change notification settings - Fork 241
feat(plugin-rsc): add import.meta.viteRsc.importAsset API
#1069
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hi-ogawa
wants to merge
6
commits into
main
Choose a base branch
from
feat/import-asset-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c15c99c
feat(plugin-rsc): add `import.meta.viteRsc.importAsset` API
hi-ogawa 08e88f3
refactor: consolidate importAssets into existing AssetsManifest
hi-ogawa 8b951af
fix: add ensureAssetImportsClientEntry for client rollupOptions.input
hi-ogawa 96e0391
test: add e2e test for importAsset API
hi-ogawa 29562fb
wip
hi-ogawa bef2c8f
chore: example
hi-ogawa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| import assert from 'node:assert' | ||
| import path from 'node:path' | ||
| import MagicString from 'magic-string' | ||
| import { stripLiteral } from 'strip-literal' | ||
| import { normalizePath, type Plugin } from 'vite' | ||
| import type { RscPluginManager } from '../plugin' | ||
| import { evalValue } from './vite-utils' | ||
|
|
||
| // Virtual module prefix for entry asset wrappers in dev mode | ||
| const ASSET_ENTRY_VIRTUAL_PREFIX = 'virtual:vite-rsc/asset-entry/' | ||
|
|
||
| export type AssetImportMeta = { | ||
| resolvedId: string | ||
| sourceEnv: string | ||
| specifier: string | ||
| isEntry: boolean | ||
| } | ||
|
|
||
| export function vitePluginImportAsset(manager: RscPluginManager): Plugin[] { | ||
| return [ | ||
| { | ||
| name: 'rsc:import-asset', | ||
| resolveId(source) { | ||
| // Handle virtual asset entry modules | ||
| if (source.startsWith(ASSET_ENTRY_VIRTUAL_PREFIX)) { | ||
| return '\0' + source | ||
| } | ||
| }, | ||
| async load(id) { | ||
| // Handle virtual asset entry modules in dev mode | ||
| if (id.startsWith('\0' + ASSET_ENTRY_VIRTUAL_PREFIX)) { | ||
| assert(this.environment.mode === 'dev') | ||
| const resolvedId = id.slice( | ||
| ('\0' + ASSET_ENTRY_VIRTUAL_PREFIX).length, | ||
| ) | ||
|
|
||
| let code = '' | ||
| // Enable HMR only when react plugin is available | ||
| const resolved = await this.resolve('/@react-refresh') | ||
| if (resolved) { | ||
| code += ` | ||
| import RefreshRuntime from "/@react-refresh"; | ||
| RefreshRuntime.injectIntoGlobalHook(window); | ||
| window.$RefreshReg$ = () => {}; | ||
| window.$RefreshSig$ = () => (type) => type; | ||
| window.__vite_plugin_react_preamble_installed__ = true; | ||
| ` | ||
| } | ||
| code += `await import(${JSON.stringify(resolvedId)});` | ||
| // Server CSS cleanup on HMR | ||
| code += /* js */ ` | ||
| const ssrCss = document.querySelectorAll("link[rel='stylesheet']"); | ||
| import.meta.hot.on("vite:beforeUpdate", () => { | ||
| ssrCss.forEach(node => { | ||
| if (node.dataset.precedence?.startsWith("vite-rsc/client-references")) { | ||
| node.remove(); | ||
| } | ||
| }); | ||
| }); | ||
| ` | ||
| // Close error overlay after syntax error is fixed | ||
| code += ` | ||
| import.meta.hot.on("rsc:update", () => { | ||
| document.querySelectorAll("vite-error-overlay").forEach((n) => n.close()) | ||
| }); | ||
| ` | ||
| return code | ||
| } | ||
| }, | ||
| buildStart() { | ||
| // Emit discovered entries during build | ||
| if (this.environment.mode !== 'build') return | ||
| if (this.environment.name !== 'client') return | ||
|
|
||
| // Collect unique entries targeting client environment | ||
| const emitted = new Set<string>() | ||
| for (const metas of Object.values(manager.assetImportMetaMap)) { | ||
| for (const meta of Object.values(metas)) { | ||
| if (meta.isEntry && !emitted.has(meta.resolvedId)) { | ||
| emitted.add(meta.resolvedId) | ||
| this.emitFile({ | ||
| type: 'chunk', | ||
| id: meta.resolvedId, | ||
| }) | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| transform: { | ||
| async handler(code, id) { | ||
| if (!code.includes('import.meta.viteRsc.importAsset')) return | ||
|
|
||
| const { server, config } = manager | ||
| const s = new MagicString(code) | ||
|
|
||
| for (const match of stripLiteral(code).matchAll( | ||
| /import\.meta\.viteRsc\.importAsset\s*\(([\s\S]*?)\)/dg, | ||
| )) { | ||
| const [argStart, argEnd] = match.indices![1]! | ||
| const argCode = code.slice(argStart, argEnd).trim() | ||
|
|
||
| // Parse: ('./entry.browser.tsx', { entry: true }) | ||
| const [specifier, options]: [string, { entry?: boolean }?] = | ||
| evalValue(`[${argCode}]`) | ||
| const isEntry = options?.entry ?? false | ||
|
|
||
| // Resolve specifier relative to importer against client environment | ||
| let resolvedId: string | ||
| if (this.environment.mode === 'dev') { | ||
| const clientEnv = server.environments.client | ||
| assert(clientEnv, `[vite-rsc] client environment not found`) | ||
| const resolved = await clientEnv.pluginContainer.resolveId( | ||
| specifier, | ||
| id, | ||
| ) | ||
| assert( | ||
| resolved, | ||
| `[vite-rsc] failed to resolve '${specifier}' for client environment`, | ||
| ) | ||
| resolvedId = resolved.id | ||
| } else { | ||
| // Build mode: resolve in client environment config | ||
| const clientEnvConfig = config.environments.client | ||
| assert(clientEnvConfig, `[vite-rsc] client environment not found`) | ||
| // Use this environment's resolver for now | ||
| const resolved = await this.resolve(specifier, id) | ||
| assert( | ||
| resolved, | ||
| `[vite-rsc] failed to resolve '${specifier}' for client environment`, | ||
| ) | ||
| resolvedId = resolved.id | ||
| } | ||
|
|
||
| // Track discovered asset, keyed by [sourceEnv][resolvedId] | ||
| const sourceEnv = this.environment.name | ||
| manager.assetImportMetaMap[sourceEnv] ??= {} | ||
| manager.assetImportMetaMap[sourceEnv]![resolvedId] = { | ||
| resolvedId, | ||
| sourceEnv, | ||
| specifier, | ||
| isEntry, | ||
| } | ||
|
|
||
| let replacement: string | ||
| if (this.environment.mode === 'dev') { | ||
| if (isEntry) { | ||
| // Dev + entry: use virtual wrapper with HMR support | ||
| const virtualId = ASSET_ENTRY_VIRTUAL_PREFIX + resolvedId | ||
| const url = config.base + '@id/__x00__' + virtualId | ||
| replacement = `Promise.resolve({ url: ${JSON.stringify(url)} })` | ||
| } else { | ||
| // Dev + non-entry: compute URL directly | ||
| const relativePath = normalizePath( | ||
| path.relative(config.root, resolvedId), | ||
| ) | ||
| const url = config.base + relativePath | ||
| replacement = `Promise.resolve({ url: ${JSON.stringify(url)} })` | ||
| } | ||
| } else { | ||
| // Build: use existing assets manifest | ||
| // Use relative ID for stable builds across different machines | ||
| const relativeId = manager.toRelativeId(resolvedId) | ||
| replacement = `(async () => (await import("virtual:vite-rsc/assets-manifest")).default.importAssets[${JSON.stringify(relativeId)}])()` | ||
| } | ||
|
|
||
| const [start, end] = match.indices![0]! | ||
| s.overwrite(start, end, replacement) | ||
| } | ||
|
|
||
| if (s.hasChanged()) { | ||
| return { | ||
| code: s.toString(), | ||
| map: s.generateMap({ hires: 'boundary' }), | ||
| } | ||
| } | ||
| }, | ||
| }, | ||
| }, | ||
| ] | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check warning
Code scanning / CodeQL
Improper code sanitization Medium
Copilot Autofix
AI 3 months ago
In general, whenever user-influenced strings are embedded into dynamically constructed JavaScript source, you must escape additional “unsafe” characters beyond what
JSON.stringifyhandles for HTML/script contexts, particularly<,>,/, backslash, control characters, and U+2028/U+2029. The referenced pattern uses a small helper (escapeUnsafeChars) applied afterJSON.stringifyto ensure the resulting string literal is safe even when inlined into<script>.The best targeted fix here is to introduce a small local escape helper in
packages/plugin-rsc/src/plugins/import-asset.tsand apply it toJSON.stringify(relativeId)in the build-modereplacementexpression. We will: (1) define acharMapandescapeUnsafeCharsfunction near the top of this file, using the same mapping as in the background, and (2) change line 188 so that it usesescapeUnsafeChars(JSON.stringify(relativeId)). This preserves all existing behavior (the manifest still uses the same key value fromrelativeId) while ensuring the generated virtual module source cannot contain problematic raw characters in that location.No new external imports are needed; we can implement the helper with
String.prototype.replace. All edits stay withinpackages/plugin-rsc/src/plugins/import-asset.tsin the provided regions.