Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/guide/api-environment-instances.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ class DevEnvironment {
*/
async warmupRequest(url: string): Promise<void>

/**
* Register a resolved module ID as safe to load in this environment, even
* outside server.fs.allow. server.fs.deny still applies.
* Call from the plugin's transform hook when it adds a reference to the module.
*/
addSafeModule(id: string): void

/**
* Called by the module runner to retrieve information about the specified
* module. Internally calls `transformRequest` and wraps the result in the
Expand Down
29 changes: 29 additions & 0 deletions docs/guide/api-environment-plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,35 @@ A plugin could use the `environment` instance to change how a module is processe
}
```

## Registering Safe Modules

During dev, plugins can call `this.environment.addSafeModule(id)` to allow a resolved module ID to be loaded outside [`server.fs.allow`](/config/server-options#server-fs-allow).

For filesystem modules, pass a normalized absolute path, optionally with a query. Use Vite's `normalizePath` utility to normalize filesystem paths. The method registers both the full ID and the path with its query and hash removed. Other query variants must be registered separately.

When a plugin adds a reference that Vite cannot discover through import analysis, register the referenced ID in the same `transform` hook. This allows the referenced module to pass the access check when it is requested later.

```ts
import type { Plugin } from 'vite'

// runtimeId is a normalized absolute path, optionally with a query.
// runtimeUrl is the URL to insert into the transformed code.
function runtimePlugin(runtimeId: string, runtimeUrl: string): Plugin {
return {
name: 'plugin-runtime',
transform: {
filter: { code: '__RUNTIME_URL__' },
handler(code) {
if (this.environment.mode === 'dev') {
this.environment.addSafeModule(runtimeId)
}
return code.replaceAll('__RUNTIME_URL__', JSON.stringify(runtimeUrl))
},
},
}
}
```

## Registering New Environments Using Hooks

Plugins can add new environments in the `config` hook. For example, [RSC support](/plugins/#vitejs-plugin-rsc) uses an additional environment to have a separate module graph with the `react-server` condition:
Expand Down
62 changes: 61 additions & 1 deletion packages/vite/src/node/__tests__/dev.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,74 @@ describe('the dev server', () => {
isFileLoadingAllowed(environment.config, outsideFile),
environment.name,
).toBe(false)
environment.safeModulePaths.addId(deniedFile)
environment.addSafeModule(deniedFile)
expect(
isFileLoadingAllowed(environment.config, deniedFile),
environment.name,
).toBe(false)
}
})

test('registers a safe module in the current environment when a transform adds its reference', async () => {
const root = path.join(import.meta.dirname, 'fixtures', 'input-option')
const runtimeFile = normalizePath(path.join(root, 'plugin-runtime.js'))
const runtimeId = runtimeFile + '?custom'
const runtimeUrl = path.posix.join('/@custom/', runtimeId)
const callInLoad = vi.fn()

const server = await createTestServer({
configFile: false,
root,
logLevel: 'silent',
optimizeDeps: { noDiscovery: true },
server: {
fs: { strict: 'extended', allow: [] },
middlewareMode: true,
ws: false,
},
plugins: [
{
name: 'plugin-runtime',
resolveId(source) {
if (source === 'virtual:entry') return '\0entry'
if (source === runtimeUrl) return runtimeId
},
load(id) {
callInLoad()
if (id === '\0entry') return ''
if (id === runtimeId) return 'export default 42'
},
transform(_code, id) {
if (id !== '\0entry') return
if (this.environment.mode === 'dev') {
this.environment.addSafeModule(runtimeId)
}
return `export const runtimeUrl = ${JSON.stringify(runtimeUrl)}`
},
},
],
})

const { client, ssr } = server.environments
await ssr.pluginContainer.resolveId(runtimeUrl)
expect(isFileLoadingAllowed(ssr.config, runtimeId)).toBe(false)
expect((await ssr.transformRequest('virtual:entry'))?.code).toContain(
runtimeUrl,
)
expect(isFileLoadingAllowed(ssr.config, runtimeId)).toBe(true)
expect(isFileLoadingAllowed(ssr.config, runtimeFile)).toBe(true)
expect(isFileLoadingAllowed(ssr.config, runtimeFile + '?other')).toBe(false)
expect(isFileLoadingAllowed(client.config, runtimeId)).toBe(false)
expect(isFileLoadingAllowed(client.config, runtimeFile)).toBe(false)
expect(await ssr.transformRequest(runtimeUrl)).not.toBeNull()

callInLoad.mockClear()
await expect(client.transformRequest(runtimeUrl)).rejects.toMatchObject({
code: 'ERR_DENIED_ID',
})
expect(callInLoad).not.toHaveBeenCalled()
})

test('resolves environment inputs into separate safe module paths', async () => {
const root = path.join(import.meta.dirname, 'fixtures', 'input-option')
const entries: Record<string, string> = {
Expand Down
10 changes: 10 additions & 0 deletions packages/vite/src/node/server/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,16 @@ export class DevEnvironment extends BaseEnvironment {
warmupFiles(server, this)
}

/**
* Register a resolved module ID as safe to load in this environment, even
* outside `server.fs.allow`. Filesystem IDs must be normalized absolute paths
* and may include a query. `server.fs.deny` still applies.
* Call from the plugin's `transform` hook when it adds a reference to the module.
*/
addSafeModule(id: string): void {
this.safeModulePaths.addId(id)
}

/**
* Called by the module runner to retrieve information about the specified
* module. Internally calls `transformRequest` and wraps the result in the
Expand Down
11 changes: 6 additions & 5 deletions playground/optimize-missing-deps/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ export async function createServer(root = process.cwd(), hmrPort) {

const app = express()

const { createServer: createViteServer, normalizePath } = await import('vite')
/**
* @type {import('vite').ViteDevServer}
*/
const vite = await (
await import('vite')
).createServer({
const vite = await createViteServer({
root,
logLevel: isTest ? 'error' : 'info',
server: {
Expand All @@ -24,12 +23,12 @@ export async function createServer(root = process.cwd(), hmrPort) {
port: hmrPort,
},
fs: {
// TODO: expose `environment.safeModulePaths.add` and use it
allow: [resolve('main.js')],
allow: [],
},
},
appType: 'custom',
})
const mainFile = normalizePath(resolve('main.js'))
app.use(vite.middlewares)

app.use('*all', async (req, res) => {
Expand All @@ -39,9 +38,11 @@ export async function createServer(root = process.cwd(), hmrPort) {

// `main.js` imports dependencies that are yet to be discovered and optimized, aka "missing" deps.
// Loading `main.js` in SSR should not trigger optimizing the "missing" deps
vite.environments.ssr.addSafeModule(mainFile)
const { name } = await vite.ssrLoadModule('./main.js')

// Loading `main.js` in the client should trigger optimizing the "missing" deps
vite.environments.client.addSafeModule(mainFile)
const appHtml = `<div id="app">${name}</div>
<script type='module'>
import { name } from './main.js'
Expand Down
Loading