diff --git a/packages/vite/rolldown.config.ts b/packages/vite/rolldown.config.ts index c60cdd517cf247..e01413c9c6cdd1 100644 --- a/packages/vite/rolldown.config.ts +++ b/packages/vite/rolldown.config.ts @@ -154,7 +154,7 @@ const moduleRunnerConfig = defineConfig({ /^rolldown\//, ...Object.keys(pkg.dependencies), ], - plugins: [bundleSizeLimit(56), enableSourceMapsInWatchModePlugin()], + plugins: [bundleSizeLimit(71), enableSourceMapsInWatchModePlugin()], output: { ...(sharedNodeOptions.output as OutputOptions), minify: { diff --git a/packages/vite/src/client/bundledDevClient.ts b/packages/vite/src/client/bundledDevClient.ts index 7dd2436355e22b..94763901be5133 100644 --- a/packages/vite/src/client/bundledDevClient.ts +++ b/packages/vite/src/client/bundledDevClient.ts @@ -3,7 +3,7 @@ import { DevRuntime } from 'rolldown/experimental/runtime' import { BundledDevHMRClient, BundledDevHMRContext, -} from './bundledDevHmrClient' +} from '../shared/bundledDevHmr' import { base, clearOverlayOrReloadOnFirstUpdate, @@ -62,7 +62,7 @@ if (typeof DevRuntime !== 'undefined') { transport, runtime, { - base, + loadPatch: (url) => import(/* @vite-ignore */ base + url), partialAccept: __HMR_PARTIAL_ACCEPT__, beforeApply: clearOverlayOrReloadOnFirstUpdate, }, diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index fcc0c7b0d43a90..17fe70a1933247 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -1,5 +1,6 @@ import type { ErrorPayload, HotPayload } from '#types/hmrPayload' import type { ViteHotContext } from '#types/hot' +import type { BundledDevHMRClient } from '../shared/bundledDevHmr' import { setupForwardConsoleHandler } from '../shared/forwardConsole' import { HMRClient, HMRContext } from '../shared/hmr' import { createHMRHandler } from '../shared/hmrHandler' @@ -8,7 +9,6 @@ import { normalizeModuleRunnerTransport, } from '../shared/moduleRunnerTransport' import { moduleUrlToBrowserUrl } from '../shared/utils' -import type { BundledDevHMRClient } from './bundledDevHmrClient' import { ErrorOverlay, cspNonce, overlayId } from './overlay' // @ts-expect-error internal virtual module import '@vite/env' diff --git a/packages/vite/src/module-runner/constants.ts b/packages/vite/src/module-runner/constants.ts index b850d69ac4b680..008df55f3aab58 100644 --- a/packages/vite/src/module-runner/constants.ts +++ b/packages/vite/src/module-runner/constants.ts @@ -5,3 +5,5 @@ export const ssrDynamicImportKey = `__vite_ssr_dynamic_import__` export const ssrExportAllKey = `__vite_ssr_exportAll__` export const ssrExportNameKey = `__vite_ssr_exportName__` export const ssrImportMetaKey = `__vite_ssr_import_meta__` + +export const ssrRolldownRuntimeKey = `__rolldown_runtime__` diff --git a/packages/vite/src/module-runner/esmEvaluator.ts b/packages/vite/src/module-runner/esmEvaluator.ts index 003ba64f8077a3..cd991792f61f7d 100644 --- a/packages/vite/src/module-runner/esmEvaluator.ts +++ b/packages/vite/src/module-runner/esmEvaluator.ts @@ -9,6 +9,7 @@ import { ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey, + ssrRolldownRuntimeKey, } from './constants' import type { ModuleEvaluator, ModuleRunnerContext } from './types' @@ -29,6 +30,7 @@ export class ESModulesEvaluator implements ModuleEvaluator { ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, + ssrRolldownRuntimeKey, // source map should already be inlined by Vite. // Place "use strict" on its own line to avoid shifting the column numbers '"use strict";\n' + code, @@ -41,6 +43,7 @@ export class ESModulesEvaluator implements ModuleEvaluator { context[ssrDynamicImportKey], context[ssrExportAllKey], context[ssrExportNameKey], + context[ssrRolldownRuntimeKey], ) Object.seal(context[ssrModuleExportsKey]) diff --git a/packages/vite/src/module-runner/evaluatedModules.ts b/packages/vite/src/module-runner/evaluatedModules.ts index d999a389f898e6..ed149c05f5b27b 100644 --- a/packages/vite/src/module-runner/evaluatedModules.ts +++ b/packages/vite/src/module-runner/evaluatedModules.ts @@ -29,6 +29,7 @@ export class EvaluatedModules { public readonly fileToModulesMap: Map> = new Map() public readonly urlToIdModuleMap: Map = new Map() + private readonly retainedSourceMaps = new Map() /** * Returns the module node by the resolved module ID. Usually, module ID is @@ -74,6 +75,7 @@ export class EvaluatedModules { this.urlToIdModuleMap.set(url, moduleNode) return moduleNode } + this.retainedSourceMaps.delete(id) const moduleNode = new EvaluatedModuleNode(id, url) this.idToModuleMap.set(id, moduleNode) this.urlToIdModuleMap.set(url, moduleNode) @@ -85,6 +87,7 @@ export class EvaluatedModules { } public invalidateModule(node: EvaluatedModuleNode): void { + this.retainedSourceMaps.delete(node.id) node.evaluated = false node.meta = undefined node.map = undefined @@ -97,6 +100,21 @@ export class EvaluatedModules { node.imports.clear() } + public removeModule( + node: EvaluatedModuleNode, + options?: { retainSourceMap?: boolean }, + ): void { + if (options?.retainSourceMap) { + const map = this.getModuleSourceMapById(node.id) + if (map) this.retainedSourceMaps.set(node.id, map) + } else { + this.retainedSourceMaps.delete(node.id) + } + this.fileToModulesMap.delete(node.file) + this.idToModuleMap.delete(node.id) + this.urlToIdModuleMap.delete(node.url) + } + /** * Extracts the inlined source map from the module code and returns the decoded * source map. If the source map is not inlined, it will return null. @@ -104,7 +122,7 @@ export class EvaluatedModules { */ getModuleSourceMapById(id: string): DecodedMap | null { const mod = this.getModuleById(id) - if (!mod) return null + if (!mod) return this.retainedSourceMaps.get(id) ?? null if (mod.map) return mod.map if (!mod.meta || !('code' in mod.meta)) return null @@ -118,6 +136,7 @@ export class EvaluatedModules { this.idToModuleMap.clear() this.fileToModulesMap.clear() this.urlToIdModuleMap.clear() + this.retainedSourceMaps.clear() } } diff --git a/packages/vite/src/module-runner/hmrHandler.ts b/packages/vite/src/module-runner/hmrHandler.ts index 8ec3821974a961..5e9c1019f42c20 100644 --- a/packages/vite/src/module-runner/hmrHandler.ts +++ b/packages/vite/src/module-runner/hmrHandler.ts @@ -44,21 +44,7 @@ export function createHMRHandlerForRunner( hmrClient.logger.debug(`program reload`) await hmrClient.notifyListeners('vite:beforeFullReload', payload) - runner.evaluatedModules.clear() - - for (const url of clearEntrypointUrls) { - if (runner.isClosed()) break - try { - await runner.import(url) - } catch (err) { - if (runner.isClosed()) break - if (err.code !== ERR_OUTDATED_OPTIMIZED_DEP) { - hmrClient.logger.error( - `An error happened during full reload\n${err.message}\n${err.stack}`, - ) - } - } - } + await reimportEntrypoints(runner, clearEntrypointUrls) break } case 'prune': @@ -75,7 +61,8 @@ export function createHMRHandlerForRunner( } case 'ping': // noop break - case 'bundled-dev-update': // todo + case 'bundled-dev-update': + runner._bundledDevHmrClient?.handlePush(payload) break default: { const check: never = payload @@ -85,6 +72,39 @@ export function createHMRHandlerForRunner( }) } +/** + * The module runner equivalent of a browser page reload: drop every evaluated + * module and run the entrypoints again. + */ +export function reloadEntrypoints(runner: ModuleRunner): Promise { + return reimportEntrypoints(runner, findAllEntrypoints(runner)) +} + +async function reimportEntrypoints( + runner: ModuleRunner, + entrypointUrls: Set, +): Promise { + if (runner._bundledDevHmrClient) { + await runner._resetBundledDevRuntime() + } else { + runner.evaluatedModules.clear() + } + + for (const url of entrypointUrls) { + if (runner.isClosed()) break + try { + await runner.import(url) + } catch (err) { + if (runner.isClosed()) break + if (err.code !== ERR_OUTDATED_OPTIMIZED_DEP) { + runner.hmrClient?.logger.error( + `An error happened during full reload\n${err.message}\n${err.stack}`, + ) + } + } + } +} + function getModulesByFile(runner: ModuleRunner, file: string): string[] { const nodes = runner.evaluatedModules.getModulesByFile(file) if (!nodes) { diff --git a/packages/vite/src/module-runner/index.ts b/packages/vite/src/module-runner/index.ts index e23db77dde3a86..537e28bce9815a 100644 --- a/packages/vite/src/module-runner/index.ts +++ b/packages/vite/src/module-runner/index.ts @@ -37,5 +37,6 @@ export { ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey, + ssrRolldownRuntimeKey, } from './constants' export type { InterceptorOptions } from './sourcemap/interceptor' diff --git a/packages/vite/src/module-runner/runner.ts b/packages/vite/src/module-runner/runner.ts index 1ff49a6fc3a35a..6721d6a73fac97 100644 --- a/packages/vite/src/module-runner/runner.ts +++ b/packages/vite/src/module-runner/runner.ts @@ -1,5 +1,12 @@ -import type { ViteHotContext } from '#types/hot' +import { nanoid } from 'nanoid/non-secure' +import { DevRuntime } from 'rolldown/experimental/runtime' +import type { Update } from '#types/hmrPayload' +import type { ModuleNamespace } from '#types/hot' import { createIsBuiltin } from '../shared/builtin' +import { + BundledDevHMRClient, + BundledDevHMRContext, +} from '../shared/bundledDevHmr' import { HMRClient, HMRContext, type HMRLogger } from '../shared/hmr' import { type NormalizedModuleRunnerTransport, @@ -14,6 +21,7 @@ import { ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey, + ssrRolldownRuntimeKey, } from './constants' import { createDefaultImportMeta } from './createImportMeta' import { ESModulesEvaluator } from './esmEvaluator' @@ -29,7 +37,7 @@ import type { ResolvedResult, SSRImportMetadata, } from './types' -import { posixDirname, posixPathToFileHref, posixResolve } from './utils' +import { posixDirname, posixJoin } from './utils' interface ModuleRunnerDebugger { (formatter: unknown, ...args: unknown[]): void @@ -38,6 +46,11 @@ interface ModuleRunnerDebugger { export class ModuleRunner { public evaluatedModules: EvaluatedModules public hmrClient?: HMRClient + /** + * Set instead of a plain `hmrClient` when `rolldownRuntime` is enabled. + * @internal + */ + public _bundledDevHmrClient?: BundledDevHMRClient private readonly transport: NormalizedModuleRunnerTransport private readonly resetSourceMapSupport?: () => void @@ -47,6 +60,11 @@ export class ModuleRunner { >() private isBuiltin?: (id: string) => boolean private builtinsPromise?: Promise + // Owned by the runner rather than bootstrapped from the bundle: the modules + // receive it as the `__rolldown_runtime__` argument, so it has to exist + // before the first one runs. It is per-runner on purpose — `ssrLoadModule` + // has its own compat runner, and a global would collide. + private rolldownDevRuntime?: DevRuntime private closed = false @@ -57,6 +75,12 @@ export class ModuleRunner { ) { this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules() this.transport = normalizeModuleRunnerTransport(options.transport) + // independent of HMR: the bundle needs `__rolldown_runtime__` to execute + // at all, so the runtime exists even when HMR is disabled + let runtime: DevRuntime | undefined + if (options.rolldownRuntime) { + runtime = this.rolldownDevRuntime = this.createRolldownDevRuntime() + } if (options.hmr !== false) { const optionsHmr = options.hmr ?? true const resolvedHmrLogger: HMRLogger = @@ -65,11 +89,35 @@ export class ModuleRunner { : optionsHmr.logger === false ? silentConsole : optionsHmr.logger - this.hmrClient = new HMRClient( - resolvedHmrLogger, - this.transport, - ({ acceptedPath }) => this.import(acceptedPath), - ) + const importUpdatedModule = ({ acceptedPath }: Update) => + this.import(acceptedPath) + if (runtime) { + this.hmrClient = this._bundledDevHmrClient = new BundledDevHMRClient( + resolvedHmrLogger, + this.transport, + runtime, + { + partialAccept: + optionsHmr !== true && optionsHmr.partialAccept === true, + loadPatch: async (url) => { + await this.import(url) + // don't leave the HMR patch in memory + const patchModule = this.evaluatedModules.getModuleByUrl(url) + if (patchModule) { + this.evaluatedModules.removeModule(patchModule) + } + }, + beforeApply: () => 'continue', + importUpdatedModule, + }, + ) + } else { + this.hmrClient = new HMRClient( + resolvedHmrLogger, + this.transport, + importUpdatedModule, + ) + } if (!this.transport.connect) { throw new Error( 'HMR is not supported by this runner transport, but `hmr` option was set to true', @@ -79,6 +127,14 @@ export class ModuleRunner { } else { this.transport.connect?.() } + if (runtime) { + // registers this runner with the dev engine so it gets its own ship map + this.transport.send({ + type: 'custom', + event: 'vite:client-connected', + data: { clientId: runtime.clientId }, + }) + } if (options.sourcemapInterceptor !== false) { this.resetSourceMapSupport = enableSourceMapSupport(this) } @@ -89,7 +145,24 @@ export class ModuleRunner { */ public async import(url: string): Promise { const fetchedModule = await this.cachedModule(url) - return await this.cachedRequest(url, fetchedModule) + const exportsObject = await this.cachedRequest( + fetchedModule.url, + fetchedModule, + ) + if ( + this.rolldownDevRuntime && + fetchedModule.meta && + 'rolldownModuleId' in fetchedModule.meta && + fetchedModule.meta.rolldownModuleId && + this.rolldownDevRuntime.isExecuted(fetchedModule.meta.rolldownModuleId) + ) { + const loadedExports = this.rolldownDevRuntime.loadExports( + fetchedModule.meta.rolldownModuleId, + ) + fetchedModule.exports = loadedExports + return loadedExports + } + return exportsObject } /** @@ -100,6 +173,21 @@ export class ModuleRunner { this.hmrClient?.clear() } + /** @internal */ + public async _resetBundledDevRuntime(): Promise { + this.evaluatedModules.clear() + this.moduleHotContexts.clear() + + const oldClientId = this.rolldownDevRuntime!.clientId + const runtime = this.createRolldownDevRuntime() + await this._bundledDevHmrClient!.resetForFullReload(runtime) + this.rolldownDevRuntime = runtime + await this.transport.invoke('resetBundledDevClient', [ + oldClientId, + runtime.clientId, + ]) + } + /** * Clears all caches, removes all HMR listeners, and resets source map support. * This method doesn't stop the HMR connection. @@ -108,6 +196,7 @@ export class ModuleRunner { this.resetSourceMapSupport?.() this.clearCache() this.hmrClient = undefined + this._bundledDevHmrClient = undefined this.closed = true await this.transport.disconnect?.() } @@ -311,12 +400,18 @@ export class ModuleRunner { if ('invalidate' in fetchedModule && fetchedModule.invalidate) { this.evaluatedModules.invalidateModule(module) + this.moduleHotContexts.delete(module.url) } fetchedModule.url = moduleUrl fetchedModule.id = moduleId module.meta = fetchedModule + // Do not keep lazy "patches" in memory, but keep the sourcemap + if (module.url.startsWith('/@vite/lazy?')) { + this.evaluatedModules.removeModule(module, { retainSourceMap: true }) + } + return module } @@ -343,7 +438,7 @@ export class ModuleRunner { // it's possible to provide an object with toString() method inside import() dep = String(dep) if (dep[0] === '.') { - dep = posixResolve(posixDirname(url), dep) + dep = posixJoin(posixDirname(url), dep) } return request(dep, { isDynamicImport: true }) } @@ -353,6 +448,7 @@ export class ModuleRunner { this.debug?.('[module runner] externalizing', externalize) const exports = await this.evaluator.runExternalModule(externalize) mod.exports = exports + this.rolldownDevRuntime?.registerModule(externalize, { exports }) return exports } @@ -372,7 +468,6 @@ export class ModuleRunner { const modulePath = cleanUrl(file || moduleId) // disambiguate the `:/` on windows: see nodejs/node#31710 - const href = posixPathToFileHref(modulePath) const meta = await createImportMeta(modulePath) const exports = Object.create(null) Object.defineProperty(exports, Symbol.toStringTag, { @@ -383,20 +478,14 @@ export class ModuleRunner { mod.exports = exports - let hotContext: ViteHotContext | undefined if (this.hmrClient) { Object.defineProperty(meta, 'hot', { enumerable: true, get: () => { - if (!this.hmrClient) { - throw new Error(`[module runner] HMR client was closed.`) - } - this.debug?.('[module runner] creating hmr context for', mod.url) - hotContext ||= new HMRContext(this.hmrClient, mod.url) - return hotContext + return this.ensureModuleHotContext(mod.url) }, set: (value) => { - hotContext = value + this.moduleHotContexts.set(mod.url, value) }, }) } @@ -413,14 +502,64 @@ export class ModuleRunner { get: getter, }), [ssrImportMetaKey]: meta, + [ssrRolldownRuntimeKey]: this.rolldownDevRuntime, } - this.debug?.('[module runner] executing', href) + this.debug?.('[module runner] executing', meta.href) await this.evaluator.runInlinedModule(context, code, mod) return exports } + + private moduleHotContexts = new Map() + + private createRolldownDevRuntime(): DevRuntime { + class ViteDevRuntime extends DevRuntime { + constructor(private readonly runner: ModuleRunner) { + super(nanoid()) + } + + payloadDelivered(filename: string): void { + this.runner.transport.send({ + type: 'custom', + event: 'vite:bundled-dev:payload-delivered', + data: { filename }, + }) + } + + // Rolldown's runtime uses `import` that will not be rewritten by the module runner transform + override loadLazyChunk(proxyModuleId: string): Promise { + return this.runner.import( + `/@vite/lazy?id=${encodeURIComponent(proxyModuleId)}&clientId=${this.clientId}`, + ) + } + + override hooks: DevRuntime['hooks'] = { + createModuleHotContext: (id) => this.runner.ensureModuleHotContext(id), + onModuleCacheRemoval: (id) => + this.runner._bundledDevHmrClient?.handleModuleCacheRemoval(id), + } + } + return new ViteDevRuntime(this) + } + + private ensureModuleHotContext(url: string) { + if (!this.hmrClient) { + return + } + + if (!this.moduleHotContexts.has(url)) { + this.debug?.('[module runner] creating hmr context for', url) + // in full-bundle mode `invalidate()` is resolved locally against the + // rolldown runtime graph instead of being sent to the server + const hotContext = this._bundledDevHmrClient + ? new BundledDevHMRContext(this._bundledDevHmrClient, url) + : new HMRContext(this.hmrClient, url) + this.moduleHotContexts.set(url, hotContext) + } + return this.moduleHotContexts.get(url) + } } function exportAll(exports: any, sourceModule: any) { diff --git a/packages/vite/src/module-runner/types.ts b/packages/vite/src/module-runner/types.ts index 676d06cfc734fe..b77bd5ebf953aa 100644 --- a/packages/vite/src/module-runner/types.ts +++ b/packages/vite/src/module-runner/types.ts @@ -1,3 +1,4 @@ +import type { DevRuntime } from 'rolldown/experimental/runtime-types' import type { ViteHotContext } from '#types/hot' import type { HMRLogger } from '../shared/hmr' import type { @@ -18,6 +19,7 @@ import type { ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey, + ssrRolldownRuntimeKey, } from './constants' import type { EvaluatedModuleNode, EvaluatedModules } from './evaluatedModules' import type { InterceptorOptions } from './sourcemap/interceptor' @@ -45,6 +47,10 @@ export interface ModuleRunnerContext { [ssrExportAllKey]: (obj: any) => void [ssrExportNameKey]: (name: string, getter: () => unknown) => void [ssrImportMetaKey]: ModuleRunnerImportMeta + /** + * @internal + */ + [ssrRolldownRuntimeKey]: DevRuntime | undefined } export interface ModuleEvaluator { @@ -86,6 +92,11 @@ export interface ModuleRunnerHmr { * Configure HMR logger. */ logger?: false | HMRLogger + /** + * Enable partial acceptance of exports in bundled mode. + * @default false + */ + partialAccept?: boolean } export interface ModuleRunnerOptions { @@ -121,6 +132,14 @@ export interface ModuleRunnerOptions { * Custom module cache. If not provided, creates a separate module cache for each ModuleRunner instance. */ evaluatedModules?: EvaluatedModules + /** + * The modules are served as a rolldown bundle that ships its own dev runtime, + * instead of one module at a time. HMR is then driven by the runtime's module + * graph rather than by the server's. + * + * @default false + */ + rolldownRuntime?: boolean } export interface ImportMetaEnv { diff --git a/packages/vite/src/module-runner/utils.ts b/packages/vite/src/module-runner/utils.ts index 1fbfa95e992954..3fa04958159ac5 100644 --- a/packages/vite/src/module-runner/utils.ts +++ b/packages/vite/src/module-runner/utils.ts @@ -42,6 +42,7 @@ function encodePathChars(filepath: string) { export const posixDirname: (path: string) => string = pathe.dirname export const posixResolve: (...paths: string[]) => string = pathe.resolve +export const posixJoin: (...paths: string[]) => string = pathe.join export function posixPathToFileHref(posixPath: string): string { let resolved = posixResolve(posixPath) diff --git a/packages/vite/src/node/server/bundledDev.ts b/packages/vite/src/node/server/bundledDev.ts index 00fa6b5f140b7e..76e3e1f3b89928 100644 --- a/packages/vite/src/node/server/bundledDev.ts +++ b/packages/vite/src/node/server/bundledDev.ts @@ -1,7 +1,12 @@ import { setTimeout } from 'node:timers/promises' import getEtag from 'etag' import colors from 'picocolors' -import type { RolldownOutput } from 'rolldown' +import type { + OutputOptions, + Plugin, + RolldownOptions, + RolldownOutput, +} from 'rolldown' import { type BindingClientHmrUpdate, type DevEngine, @@ -33,6 +38,7 @@ type HmrOutput = BindingClientHmrUpdate['update'] type MemoryFile = { source: string | Uint8Array + sourcemapPath?: string etag?: string contentType?: string } @@ -101,14 +107,10 @@ export class BundledDev { private lastBuildError: Error | null = null memoryFiles: MemoryFiles = new MemoryFiles() + facadeToChunk: Map = new Map() + private entryResolver?: (id: string) => Promise - constructor(private environment: DevEnvironment) { - if (environment.name !== 'client') { - throw new Error( - 'currently full bundle mode is only available for client environment', - ) - } - } + constructor(private environment: DevEnvironment) {} private get devEngine(): DevEngine { if (!this._devEngine) { @@ -123,11 +125,21 @@ export class BundledDev { return this.memoryFiles.size > this.staticFiles.size } + async resolveEntryFacade(id: string): Promise { + return this.entryResolver?.(id) + } + async listen(): Promise { this._closed = false debug?.('INITIAL: setup bundle options') const rolldownOptions = await this.getRolldownOptions() - await this.storeStaticFiles() + if (isEmptyInput(rolldownOptions.input)) { + debug?.('INITIAL: no entry points, skipping the build') + return + } + if (this.environment.config.consumer !== 'server') { + await this.storeStaticFiles() + } // NOTE: only single outputOptions is supported here if ( Array.isArray(rolldownOptions.output) && @@ -145,7 +157,7 @@ export class BundledDev { 'vite:client-connected', async (payload, client) => { this.clients.setupIfNeeded(client, payload.clientId) - this.devEngine.registerClient(payload.clientId) + await this.devEngine.registerClient(payload.clientId) }, ) this.environment.hot.on('vite:bundled-dev:payload-delivered', (payload) => { @@ -286,6 +298,21 @@ export class BundledDev { }) } + /** + * @internal + */ + public async _waitForInitialBuildSuccess(): Promise { + // the build is skipped when there are no entry points + if (!this._devEngine) return + await this.devEngine.ensureCurrentBuildFinish() + const bundleState = await this.devEngine.getBundleState() + if (bundleState.lastBuildErrored) { + throw new Error( + `The last full bundle mode build has failed. See logs for more information.`, + ) + } + } + private async waitForInitialBuildFinish(): Promise { if (this._closed) return await this.devEngine.ensureCurrentBuildFinish() @@ -343,7 +370,10 @@ export class BundledDev { async triggerLazyBundling( moduleId: string | null, clientId: string | null, - ): Promise<{ code: string; filename: string } | undefined> { + ): Promise< + | { code: string; filename: string; sourcemap: string | undefined } + | undefined + > { if (!moduleId || !clientId) { return } @@ -364,9 +394,21 @@ export class BundledDev { return { filename: result.filename, code: result.code + payloadDeliveredAck(result.filename), + sourcemap: result.sourcemap, } } + async resetClient(oldClientId: string, newClientId: string): Promise { + const client = this.clients.get(oldClientId) + if (!client) { + throw new Error(`bundled dev client ${oldClientId} is not registered`) + } + this.clients.replace(client, newClientId) + this.reloadNeededClientIds.delete(oldClientId) + await this.devEngine.removeClient(oldClientId) + await this.devEngine.registerClient(newClientId) + } + /** * Called when the client reports that it evaluated a payload (the line appended * by `payloadDeliveredAck`). Only then is the payload recorded on the server's @@ -384,8 +426,12 @@ export class BundledDev { async close(): Promise { this._closed = true this.memoryFiles.clear() - await this._devEngine?.close() - this.initialBuildCompleted = false + try { + await this._devEngine?.close() + } finally { + this.entryResolver = undefined + this.initialBuildCompleted = false + } } private async storeStaticFiles(): Promise { @@ -414,23 +460,51 @@ export class BundledDev { private storeOutputFiles(output: RolldownOutput['output'][number][]): void { // NOTE: don't clear memoryFiles here as incremental build reuses the files for (const outputFile of output) { + if ( + outputFile.type === 'chunk' && + outputFile.isEntry && + outputFile.facadeModuleId + ) { + this.facadeToChunk.set( + outputFile.facadeModuleId, + normalizePath(outputFile.fileName), + ) + } this.memoryFiles.set(normalizePath(outputFile.fileName), () => { const source = outputFile.type === 'chunk' ? outputFile.code : outputFile.source return { source, + sourcemapPath: + outputFile.type === 'chunk' && outputFile.sourcemapFileName + ? normalizePath(outputFile.sourcemapFileName) + : undefined, etag: getEtag(Buffer.from(source), { weak: true }), } }) } } - private async getRolldownOptions() { + protected async getRolldownOptions(): Promise { const chunkMetadataMap = new ChunkMetadataMap() const rolldownOptions = resolveRolldownOptions( this.environment, chunkMetadataMap, ) + const setEntryResolver = ( + resolver: (id: string) => Promise, + ) => { + this.entryResolver = resolver + } + const resolveEntriesPlugin: Plugin = { + name: 'vite:bundled-dev-resolve-entries', + buildStart() { + setEntryResolver(async (id) => { + return (await this.resolve(id, undefined, { isEntry: true }))?.id + }) + }, + } + rolldownOptions.plugins = [rolldownOptions.plugins, resolveEntriesPlugin] rolldownOptions.experimental ??= {} rolldownOptions.experimental.devMode = { lazy: true, @@ -449,24 +523,26 @@ export class BundledDev { // set filenames to make output paths predictable so that `renderChunk` hook does not need to be used if (Array.isArray(rolldownOptions.output)) { for (const output of rolldownOptions.output) { - output.entryFileNames = 'assets/[name].js' - output.chunkFileNames = 'assets/[name]-[hash].js' - output.assetFileNames = 'assets/[name]-[hash][extname]' - output.minify = false - output.sourcemap = true + Object.assign(output, this.getOutputOptions()) } } else { rolldownOptions.output ??= {} - rolldownOptions.output.entryFileNames = 'assets/[name].js' - rolldownOptions.output.chunkFileNames = 'assets/[name]-[hash].js' - rolldownOptions.output.assetFileNames = 'assets/[name]-[hash][extname]' - rolldownOptions.output.minify = false - rolldownOptions.output.sourcemap = true + Object.assign(rolldownOptions.output, this.getOutputOptions()) } return rolldownOptions } + protected getOutputOptions(): OutputOptions { + return { + entryFileNames: 'assets/[name].js', + chunkFileNames: 'assets/[name]-[hash].js', + assetFileNames: 'assets/[name]-[hash][extname]', + minify: false, + sourcemap: true, + } + } + private handleHmrOutput( client: NormalizedHotChannelClient, files: string[], @@ -510,6 +586,9 @@ export class BundledDev { hmrOutput.code + payloadDeliveredAck(hmrOutput.filename) + '\n; export {}', + sourcemapPath: hmrOutput.sourcemapFilename + ? normalizePath(hmrOutput.sourcemapFilename) + : undefined, }) if (hmrOutput.sourcemapFilename && hmrOutput.sourcemap) { this.memoryFiles.set(hmrOutput.sourcemapFilename, { @@ -551,6 +630,13 @@ class Clients { this.idToClient.set(clientId, client) } + replace(client: NormalizedHotChannelClient, clientId: string): void { + const previousClientId = this.clientToId.get(client) + if (previousClientId) this.idToClient.delete(previousClientId) + this.clientToId.set(client, clientId) + this.idToClient.set(clientId, client) + } + get(id: string): NormalizedHotChannelClient | undefined { return this.idToClient.get(id) } @@ -593,3 +679,11 @@ function debounce(time: number, cb: () => void) { function payloadDeliveredAck(filename: string): string { return `\n;__rolldown_runtime__.payloadDelivered(${JSON.stringify(filename)});` } + +function isEmptyInput(input: RolldownOptions['input']): boolean { + if (Array.isArray(input)) return input.length === 0 + if (typeof input === 'object' && input != null) { + return Object.keys(input).length === 0 + } + return false +} diff --git a/packages/vite/src/node/server/environment.ts b/packages/vite/src/node/server/environment.ts index 4e29fa5e8411a5..56cd157150a294 100644 --- a/packages/vite/src/node/server/environment.ts +++ b/packages/vite/src/node/server/environment.ts @@ -173,6 +173,12 @@ export class DevEnvironment extends BaseEnvironment { : { type: 'RegExp', source: builtin.source, flags: builtin.flags }, ) }, + resetBundledDevClient: (oldClientId, newClientId) => { + if (!this.bundledDev) { + throw new Error('bundled dev is not enabled in this environment') + } + return this.bundledDev.resetClient(oldClientId, newClientId) + }, }) this.hot.on( diff --git a/packages/vite/src/node/ssr/fetchModule.ts b/packages/vite/src/node/ssr/fetchModule.ts index 0158c009620e3d..a839cfe3fdde7f 100644 --- a/packages/vite/src/node/ssr/fetchModule.ts +++ b/packages/vite/src/node/ssr/fetchModule.ts @@ -1,15 +1,24 @@ -import { pathToFileURL } from 'node:url' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' import type { FetchResult } from 'vite/module-runner' -import type { EnvironmentModuleNode, TransformResult } from '..' +import type { TransformResult } from '..' import { MODULE_RUNNER_SOURCEMAPPING_SOURCE, SOURCEMAPPING_URL, } from '../../shared/constants' -import { encodeSourceURL, unwrapId } from '../../shared/utils' +import type { ViteFetchResult } from '../../shared/invokeMethods' +import { cleanUrl, encodeSourceURL, unwrapId } from '../../shared/utils' import { tryNodeResolve } from '../plugins/resolve' +import type { BundledDev } from '../server/bundledDev' import type { DevEnvironment } from '../server/environment' import { genSourceMapUrl } from '../server/sourcemap' -import { isBuiltin, isExternalUrl, isFilePathESM } from '../utils' +import { + isBuiltin, + isExternalUrl, + isFilePathESM, + normalizePath, +} from '../utils' +import { ssrTransform } from './ssrTransform' export interface FetchModuleOptions { cached?: boolean @@ -43,7 +52,13 @@ export async function fetchModule( // if there is no importer, the file is an entry point // entry points are always internalized - if (!isFileUrl && importer && url[0] !== '.' && url[0] !== '/') { + if ( + !isFileUrl && + importer && + url[0] !== '.' && + url[0] !== '/' && + !isBundledChunkUrl(environment, url) + ) { const { isProduction, root } = environment.config const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve @@ -80,6 +95,12 @@ export async function fetchModule( url = unwrapId(url) + const bundledDev = environment.bundledDev + + if (bundledDev) { + return fetchBundledModule(environment, bundledDev, url, importer, options) + } + const mod = await environment.moduleGraph.ensureEntryFromUrl(url) const cached = !!mod.transformResult @@ -99,7 +120,7 @@ export async function fetchModule( } if (options.inlineSourceMap !== false) { - result = inlineSourceMap(mod, result, options.startOffset) + result = inlineSourceMap(mod.id!, result, options.startOffset) } // remove shebang @@ -115,13 +136,153 @@ export async function fetchModule( } } +async function fetchBundledModule( + environment: DevEnvironment, + bundledDev: BundledDev, + url: string, + importer: string | undefined, + options: FetchModuleOptions, +) { + await bundledDev._waitForInitialBuildSuccess() + + if (url.startsWith('/@vite/lazy?')) { + const { searchParams } = new URL(url, 'http://localhost') + const moduleId = searchParams.get('id')! + const clientId = searchParams.get('clientId')! + const lazyResult = await bundledDev.triggerLazyBundling(moduleId, clientId) + if (lazyResult == null) { + throw new Error(`unknown request: ${url}`) + } + // This module is invalidated immediately, so url/id do not matter + const result: ViteFetchResult = { + code: lazyResult.code, + url, + id: moduleId!, + file: cleanUrl(moduleId!), + invalidate: false, + } + + // See https://github.com/rolldown/rolldown/issues/8376 + const ssrResult = await ssrTransform( + result.code, + lazyResult.sourcemap ? JSON.parse(lazyResult.sourcemap) : null, + url, + result.code, + ) + if (!ssrResult) { + throw new Error(`[vite] cannot apply ssr transform to '${url}'.`) + } + result.code = ssrResult.code + if (options.inlineSourceMap !== false) { + result.code = inlineSourceMap( + result.id, + ssrResult, + options.startOffset, + ).code + } + return result + } + + const outDir = normalizePath( + path.resolve(environment.config.root, environment.config.build.outDir), + ) + + let fileName: string + let facadeId: string | undefined + + // Assume this is an entry point that was specified in rolldownOptions.input + if (!importer) { + const resolvedEntry = await resolveBundledEntryFilename( + bundledDev, + environment.config.root, + url, + ) + if (!resolvedEntry) { + const entrypoints = [...bundledDev.facadeToChunk.keys()] + throw new Error( + `[vite] Entrypoint '${url}' was not defined in the config. ` + + (entrypoints.length + ? `Available entry points: \n- ${[...bundledDev.facadeToChunk.keys()].join('\n- ')}` + : `The build did not produce any chunks. Did it finish successfully? See the logs for more information.`), + ) + } + ;[facadeId, fileName] = resolvedEntry + } else if (url[0] === '.') { + // Importer is reported as a full path on the file system. + // This happens because we provide the `file` attribute. + if (importer.startsWith(outDir)) { + importer = importer.slice(outDir.length + 1) + } + fileName = path.posix.join(path.posix.dirname(importer), url) + } else { + fileName = url + } + + const memoryFile = bundledDev.memoryFiles.get(fileName) + const code = memoryFile?.source + if (code == null) { + throw new Error( + `[vite] the module '${url}' (chunk '${fileName}') ${ + importer ? ` imported from '${importer}'` : '' + } was not bundled. Is server established?`, + ) + } + const map = memoryFile?.sourcemapPath + ? bundledDev.memoryFiles.get(memoryFile.sourcemapPath)?.source.toString() + : undefined + const result: ViteFetchResult = { + code: code.toString(), + // To make sure dynamic imports resolve assets correctly. + // (Dynamic import resolves relative urls with importer url) + url: fileName, + id: fileName, + // The potential position on the file system. + // We don't actually keep it there, it's virtual. + file: normalizePath(path.resolve(outDir, fileName)), + // chunks cannot be invalidated manually + invalidate: false, + // TODO: seems like rolldown uses `process.cwd()` instead of `config.root` + // We need this because __rolldown_runtime__ keeps modules internally + // And after HMR there is no other way to receive the updated exports + rolldownModuleId: facadeId + ? normalizePath(path.relative(process.cwd(), facadeId)) + : undefined, + } + // TODO: this should be done in rolldown, there is already a function for it + // output.format = 'module-runner' + // See https://github.com/rolldown/rolldown/issues/8376 + const ssrResult = await ssrTransform( + result.code, + map ? JSON.parse(map) : null, + result.file!, + result.code, + ) + if (!ssrResult) { + throw new Error(`[vite] cannot apply ssr transform to '${url}'.`) + } + result.code = ssrResult.code + if (options.inlineSourceMap !== false) { + result.code = inlineSourceMap( + result.id, + ssrResult, + options.startOffset, + ).code + } + + // remove shebang + if (result.code[0] === '#') + result.code = result.code.replace(/^#!.*/, (s) => ' '.repeat(s.length)) + + return result +} + const OTHER_SOURCE_MAP_REGEXP = new RegExp( `//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, 'gm', ) function inlineSourceMap( - mod: EnvironmentModuleNode, + id: string, result: TransformResult, startOffset: number | undefined, ) { @@ -147,8 +308,49 @@ function inlineSourceMap( } : map result.code = `${code.trimEnd()}\n//# sourceURL=${encodeSourceURL( - mod.id!, + id, )}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n` return result } + +function isBundledChunkUrl(environment: DevEnvironment, url: string) { + return environment.bundledDev?.memoryFiles.has(url) +} + +async function resolveBundledEntryFilename( + environment: BundledDev, + root: string, + url: string, +): Promise<[facadeId: string | undefined, chunkName: string] | undefined> { + if (environment.memoryFiles.has(url)) { + return [undefined, url] + } + // Already resolved by the user to be a url + if (environment.facadeToChunk.has(url)) { + return [url, environment.facadeToChunk.get(url)!] + } + const facadeId = await environment.resolveEntryFacade(url) + if (facadeId && environment.facadeToChunk.has(facadeId)) { + return [facadeId, environment.facadeToChunk.get(facadeId)!] + } + const moduleId = normalizePath( + url.startsWith('file://') + ? // new URL(path) + fileURLToPath(url) + : // ./index.js + // NOTE: we don't try to find it if extension is not passed + // It will throw an error instead + path.resolve(root, url), + ) + if (environment.facadeToChunk.get(moduleId)) { + return [moduleId, environment.facadeToChunk.get(moduleId)!] + } + if (url[0] === '/') { + const tryAbsoluteUrl = path.posix.join(root, url) + const absoluteChunk = environment.facadeToChunk.get(tryAbsoluteUrl) + if (absoluteChunk) { + return [tryAbsoluteUrl, absoluteChunk] + } + } +} diff --git a/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import-source-map.js b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import-source-map.js new file mode 100644 index 00000000000000..167fbce64626bb --- /dev/null +++ b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import-source-map.js @@ -0,0 +1 @@ +export const load = () => import('./has-error-deep.ts') diff --git a/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import.js b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import.js index aad961772410fb..c3624dfafb81f7 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import.js +++ b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/dynamic-import.js @@ -2,7 +2,14 @@ import path from 'node:path' import { pathToFileURL } from 'node:url' import * as staticModule from './simple' -export const initialize = async () => { +export const initialize = async (isFullBundle) => { + if (isFullBundle) { + return { + dynamicProcessed: await import('./simple'), + static: staticModule, + } + } + const nameRelative = './simple' const nameAbsolute = '/fixtures/simple' const nameAbsoluteExtension = '/fixtures/simple.js' diff --git a/packages/vite/src/node/ssr/runtime/__tests__/fixtures/full-reload.js b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/full-reload.js new file mode 100644 index 00000000000000..651591a9aff242 --- /dev/null +++ b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/full-reload.js @@ -0,0 +1 @@ +export const value = 'initial' diff --git a/packages/vite/src/node/ssr/runtime/__tests__/fixtures/simple-hmr.js b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/simple-hmr.js new file mode 100644 index 00000000000000..b7cb5ad928b589 --- /dev/null +++ b/packages/vite/src/node/ssr/runtime/__tests__/fixtures/simple-hmr.js @@ -0,0 +1,11 @@ +export const test = 'I am initialized' + +let _resolve +const deferredPromise = new Promise((resolve) => { + _resolve = resolve +}) +deferredPromise.resolve = _resolve + +globalThis.__HMR_PROMISE__ ??= deferredPromise + +import.meta.hot?.accept() diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts index 5f527eee8830c6..6e01472e34ca6f 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts @@ -1,14 +1,17 @@ +import fs from 'node:fs' +import { resolve } from 'node:path' import { assert, describe, expect, onTestFinished, vi } from 'vitest' import { promiseWithResolvers } from '../../../../shared/utils' -import { createModuleRunnerTester } from './utils' +import { runnerTest as it } from './utils' describe( 'module runner hmr works as expected', () => { - const it = createModuleRunnerTester({ + it.override('config', { server: { // override watch options because it's disabled by default watch: {}, + hmr: true, }, }) @@ -206,6 +209,104 @@ describe( expect(sharedResult.value).toBe('ready') expect(evaluatedResult.sharedValue).toBe('ready') }) + + describe('full bundle mode', () => { + it.override('fullBundle', ['./fixtures/simple-hmr.js']) + it.override('config', { + server: { + hmr: true, + watch: { usePolling: true, interval: 10 }, + }, + }) + + it('the exports object is updated', async ({ runner }) => { + const exports1 = await runner.import('/fixtures/simple-hmr.js') + + expect(exports1).toHaveProperty('test', 'I am initialized') + expect(exports1).not.toHaveProperty('hmr') + + const hmrCode = `\nexport const hmr = true;globalThis.__HMR_PROMISE__.resolve()` + + editFile('./fixtures/simple-hmr.js', (code) => code + hmrCode) + onTestFinished(() => { + ;(globalThis as any).__HMR_PROMISE__ = undefined + editFile('./fixtures/simple-hmr.js', (code) => + code.replace(hmrCode, ''), + ) + }) + + await (globalThis as any).__HMR_PROMISE__ + + const exports2 = await runner.import('/fixtures/simple-hmr.js') + expect(exports2).toMatchObject({ + test: 'I am initialized', + hmr: true, + }) + }) + }) }, process.env.CI ? 50_00 : 5_000, ) + +function editFile(file: string, callback: (content: string) => string) { + const filepath = resolve(import.meta.dirname, file) + const content = fs.readFileSync(filepath, 'utf-8') + fs.writeFileSync(filepath, callback(content), 'utf-8') +} + +describe.each([false, true])( + 'full bundle partial acceptance (%s)', + (partialAccept) => { + it.override('fullBundle', ['virtual:partial-accept-entry']) + it.override('config', { + experimental: { hmrPartialAccept: partialAccept }, + server: { hmr: true }, + plugins: [ + { + name: 'partial-accept-fixture', + resolveId(id) { + if (id.startsWith('virtual:partial-accept-')) return id + }, + load(id) { + if (id === 'virtual:partial-accept-entry') { + return ` + import { accepted } from 'virtual:partial-accept-dep' + export const value = () => accepted + ` + } + if (id === 'virtual:partial-accept-dep') { + return ` + export const accepted = 1 + export const other = 2 + import.meta.hot.acceptExports(['accepted']) + ` + } + }, + }, + ], + }) + + it('respects the configured partial acceptance during propagation', async ({ + runner, + }) => { + const mod = await runner.import('virtual:partial-accept-entry') + expect(mod.value()).toBe(1) + const update = runner._bundledDevHmrClient!.computeHmrUpdate([ + 'virtual:partial-accept-dep', + ]) + expect(update).toStrictEqual({ + type: 'update', + boundaries: [ + { + boundary: 'virtual:partial-accept-dep', + acceptedVia: 'virtual:partial-accept-dep', + isWithinCircularImport: false, + }, + ], + updateSet: partialAccept + ? ['virtual:partial-accept-dep'] + : ['virtual:partial-accept-dep', 'virtual:partial-accept-entry'], + }) + }) + }, +) diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-no-hmr.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-no-hmr.spec.ts index 021726e915aa96..fac5adc98fe72c 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-no-hmr.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-no-hmr.spec.ts @@ -1,8 +1,8 @@ import { describe, expect } from 'vitest' -import { createModuleRunnerTester } from './utils' +import { runnerTest as it } from './utils' describe('module runner hmr works as expected', () => { - const it = createModuleRunnerTester({ + it.override('config', { server: { // override watch options because it's disabled by default watch: {}, diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts index d5e41a9c6c9011..54c5778c770aff 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts @@ -2,21 +2,64 @@ import { existsSync, readdirSync } from 'node:fs' import { posix, resolve, win32 } from 'node:path' import { setTimeout } from 'node:timers/promises' import { fileURLToPath } from 'node:url' -import { describe, expect, it, vi } from 'vitest' -import type { HMRLogger } from '../../../../../dist/node/module-runner' +import { describe, expect, vi } from 'vitest' +import type { HMRLogger } from '../../../../module-runner' import type { ExternalFetchResult } from '../../../../shared/invokeMethods' -import { isWindows } from '../../../../shared/utils' +import { isWindows, slash } from '../../../../shared/utils' import { createServer } from '../../../server' import { createRunnableDevEnvironment, isRunnableDevEnvironment, } from '../../../server/environments/runnableEnvironment' -import { createModuleRunnerTester } from './utils' +import { createFixtureEditor, runnerTest as it } from './utils' const _URL = URL -describe('module runner initialization', () => { - const it = createModuleRunnerTester({ +describe.for([ + { + fullBundle: [ + './fixtures/dynamic-import.js', + './fixtures/simple.js', + './fixtures/test.css', + './fixtures/test.module.css', + './fixtures/assets.js', + './fixtures/top-level-object.js', + './fixtures/cyclic2/test9/index.js', + './fixtures/live-binding/test4/index.js', + './fixtures/live-binding/test3/index.js', + './fixtures/live-binding/test2/index.js', + './fixtures/live-binding/test1/index.js', + './fixtures/execution-order-re-export/index.js', + './fixtures/cyclic2/test7/Ion.js', + './fixtures/cyclic2/test6/index.js', + './fixtures/cyclic2/test5/index.js', + './fixtures/cyclic2/test4/index.js', + './fixtures/cyclic2/test3/index.js', + './fixtures/cyclic2/test2/index.js', + './fixtures/cyclic2/test1/index.js', + './fixtures/no-this/importer.js', + './fixtures/native.js', + './fixtures/installed.js', + './fixtures/virtual.js', + './fixtures/cyclic/entry.js', + './fixtures/tla-circular/index.js', + './fixtures/has-error.js', + './fixtures/basic.js', + './fixtures/simple.js?raw', + './fixtures/simple.js?url', + './fixtures/test.css?inline', + './fixtures/oxc-runtime-helper.ts', + + // TODO: this fails during bundle, not at runtime + // './fixtures/esm-external-non-existing.js', + // './fixtures/cjs-external-non-existing.js', + ], + title: 'full bundle mode', + }, + { fullBundle: [], title: 'dev mode' }, +])('module runner initialization ($title)', ({ fullBundle }) => { + it.override('fullBundle', fullBundle) + it.override('config', { resolve: { external: ['tinyglobby'], noExternal: ['@oxc-project/runtime'], @@ -24,7 +67,7 @@ describe('module runner initialization', () => { }) it('correctly runs ssr code', async ({ runner }) => { - const mod = await runner.import('/fixtures/simple.js') + const mod = await runner.import('./fixtures/simple.js') expect(mod.test).toBe('I am initialized') // loads the same module if id is a file url @@ -38,43 +81,6 @@ describe('module runner initialization', () => { expect(mod).toBe(mod3) }) - it('can load virtual modules as an entry point', async ({ runner }) => { - const mod = await runner.import('virtual:test') - expect(mod.msg).toBe('virtual') - - // already resolved id works similar to `transformRequest` - expect(await runner.import(`\0virtual:normal`)).toMatchInlineSnapshot(` - { - "default": "ok", - } - `) - - // escaped virtual module id works - expect(await runner.import(`/@id/__x00__virtual:normal`)) - .toMatchInlineSnapshot(` - { - "default": "ok", - } - `) - - // timestamp query works - expect(await runner.import(`virtual:normal?t=${Date.now()}`)) - .toMatchInlineSnapshot(` - { - "default": "ok", - } - `) - - // other arbitrary queries don't work - await expect(() => - runner.import('virtual:normal?abcd=1234'), - ).rejects.toMatchObject({ - message: expect.stringContaining( - 'Failed to load url virtual:normal?abcd=1234', - ), - }) - }) - it('css is loaded correctly', async ({ runner }) => { const css = await runner.import('/fixtures/test.css') expect(css.default).toBeUndefined() @@ -87,17 +93,29 @@ describe('module runner initialization', () => { }) }) - it('assets are loaded correctly', async ({ runner }) => { + it('assets are loaded correctly', async ({ runner, fullBundle }) => { const assets = await runner.import('/fixtures/assets.js') - expect(assets).toMatchObject({ - mov: '/fixtures/assets/placeholder.mov', - txt: '/fixtures/assets/placeholder.txt', - png: '/fixtures/assets/placeholder.png', - webp: '/fixtures/assets/placeholder.webp', - }) + if (fullBundle.length) { + expect(assets).toMatchObject({ + mov: 'data:video/quicktime;base64,', + txt: 'data:text/plain;base64,', + png: 'data:image/png;base64,', + webp: 'data:image/webp;base64,', + }) + } else { + expect(assets).toMatchObject({ + mov: '/fixtures/assets/placeholder.mov', + txt: '/fixtures/assets/placeholder.txt', + png: '/fixtures/assets/placeholder.png', + webp: '/fixtures/assets/placeholder.webp', + }) + } }) - it('ids with Vite queries are loaded correctly', async ({ runner }) => { + it('ids with Vite queries are loaded correctly', async ({ + runner, + fullBundle, + }) => { const raw = await runner.import('/fixtures/simple.js?raw') expect(raw.default).toMatchInlineSnapshot(` "export const test = 'I am initialized' @@ -106,7 +124,11 @@ describe('module runner initialization', () => { " `) const url = await runner.import('/fixtures/simple.js?url') - expect(url.default).toMatchInlineSnapshot(`"/fixtures/simple.js"`) + if (fullBundle.length) { + expect(url.default).toMatch('/assets') + } else { + expect(url.default).toMatchInlineSnapshot(`"/fixtures/simple.js"`) + } const inline = await runner.import('/fixtures/test.css?inline') expect(inline.default).toMatchInlineSnapshot(` ".test { @@ -118,14 +140,20 @@ describe('module runner initialization', () => { it('modules with query strings are treated as different modules', async ({ runner, + fullBundle, + skip, }) => { + skip(!!fullBundle.length) const modSimple = await runner.import('/fixtures/simple.js') const modUrl = await runner.import('/fixtures/simple.js?url') expect(modSimple).not.toBe(modUrl) expect(modUrl.default).toBe('/fixtures/simple.js') }) - it('exports is not modifiable', async ({ runner }) => { + it('exports is not modifiable', async ({ runner, skip, fullBundle }) => { + // TODO: fix in rolldown https://github.com/rolldown/rolldown/issues/7722 + skip(!!fullBundle.length, "rolldown's module is not sealed") + const mod = await runner.import('/fixtures/simple.js') expect(Object.isSealed(mod)).toBe(true) expect(() => { @@ -155,7 +183,7 @@ describe('module runner initialization', () => { const s = Symbol() try { await runner.import('/fixtures/has-error.js') - } catch (e) { + } catch (e: any) { expect(e[s]).toBeUndefined() e[s] = true expect(e[s]).toBe(true) @@ -163,56 +191,11 @@ describe('module runner initialization', () => { try { await runner.import('/fixtures/has-error.js') - } catch (e) { + } catch (e: any) { expect(e[s]).toBe(true) } }) - it('importing external cjs library checks exports', async ({ runner }) => { - await expect(() => runner.import('/fixtures/cjs-external-non-existing.js')) - .rejects.toThrowErrorMatchingInlineSnapshot(` - [SyntaxError: [vite] Named export 'nonExisting' not found. The requested module '@vitejs/cjs-external' is a CommonJS module, which may not support all module.exports as named exports. - CommonJS modules can always be imported via the default export, for example using: - - import pkg from '@vitejs/cjs-external'; - const {nonExisting} = pkg; - ] - `) - // subsequent imports of the same external package should not throw if imports are correct - await expect( - runner.import('/fixtures/cjs-external-existing.js'), - ).resolves.toMatchObject({ - result: 'world', - }) - }) - - it('importing external esm library checks exports', async ({ runner }) => { - await expect(() => - runner.import('/fixtures/esm-external-non-existing.js'), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `[SyntaxError: [vite] The requested module '@vitejs/esm-external' does not provide an export named 'nonExisting']`, - ) - // subsequent imports of the same external package should not throw if imports are correct - await expect( - runner.import('/fixtures/esm-external-existing.js'), - ).resolves.toMatchObject({ - result: 'world', - }) - }) - - it("dynamic import doesn't produce duplicates", async ({ runner }) => { - const mod = await runner.import('/fixtures/dynamic-import.js') - const modules = await mod.initialize() - // toBe checks that objects are actually the same, not just structurally - // using toEqual here would be a mistake because it check the structural difference - expect(modules.static).toBe(modules.dynamicProcessed) - expect(modules.static).toBe(modules.dynamicRelative) - expect(modules.static).toBe(modules.dynamicAbsolute) - expect(modules.static).toBe(modules.dynamicAbsoluteExtension) - expect(modules.static).toBe(modules.dynamicAbsoluteFull) - expect(modules.static).toBe(modules.dynamicFileUrl) - }) - it('correctly imports a virtual module', async ({ runner }) => { const mod = await runner.import('/fixtures/virtual.js') expect(mod.msg0).toBe('virtual0') @@ -234,44 +217,6 @@ describe('module runner initialization', () => { expect(mod.existsSync).toBe(existsSync) }) - it('correctly resolves module url', async ({ runner, server }) => { - const { meta } = await runner.import('/fixtures/basic') - const basicUrl = new _URL('./fixtures/basic.js', import.meta.url).toString() - expect(meta.url).toBe(basicUrl) - - const filename = meta.filename! - const dirname = meta.dirname! - - if (isWindows) { - const cwd = process.cwd() - const drive = `${cwd[0].toUpperCase()}:\\` - const root = server.config.root.replace(/\\/g, '/') - - expect(filename.startsWith(drive)).toBe(true) - expect(dirname.startsWith(drive)).toBe(true) - - expect(filename).toBe(win32.join(root, '.\\fixtures\\basic.js')) - expect(dirname).toBe(win32.join(root, '.\\fixtures')) - } else { - const root = server.config.root - - expect(posix.join(root, './fixtures/basic.js')).toBe(filename) - expect(posix.join(root, './fixtures')).toBe(dirname) - } - }) - - it(`no maximum call stack error ModuleRunner.isCircularImport`, async ({ - runner, - }) => { - // entry.js ⇔ entry-cyclic.js - // ⇓ - // action.js - const mod = await runner.import('/fixtures/cyclic/entry') - await mod.setupCyclic() - const action = await mod.importAction('/fixtures/cyclic/action') - expect(action).toBeDefined() - }) - it('resolves circular imports between modules with top-level await', async ({ runner, }) => { @@ -318,19 +263,6 @@ describe('module runner initialization', () => { ) }) - it(`cyclic invalid 2`, async ({ runner }) => { - // It should be an error but currently `undefined` fallback. - expect( - await runner.import('/fixtures/cyclic2/test6/index.js'), - ).toMatchInlineSnapshot( - ` - { - "dep1": "dep1: dep2: undefined", - } - `, - ) - }) - it(`cyclic with mixed import and re-export`, async ({ runner }) => { const mod = await runner.import('/fixtures/cyclic2/test7/Ion.js') expect(mod).toMatchInlineSnapshot(` @@ -432,10 +364,158 @@ describe('module runner initialization', () => { } `) }) + + it('dynamic imports in FBM', async ({ runner }) => { + const mod = await runner.import('./fixtures/dynamic-import.js') + const modules = await mod.initialize(true) + + expect(modules.static).toBe(modules.dynamicProcessed) + expect(modules.dynamicProcessed.test).toBeTypeOf('string') + expect(modules.dynamicProcessed.test).toBe(modules.static.test) + }) +}) + +describe('not supported by bundle mode', () => { + // if bundle throws an error, we should stopn waiting + it('importing external cjs library checks exports', async ({ runner }) => { + await expect(() => runner.import('/fixtures/cjs-external-non-existing.js')) + .rejects.toThrowErrorMatchingInlineSnapshot(` + [SyntaxError: [vite] Named export 'nonExisting' not found. The requested module '@vitejs/cjs-external' is a CommonJS module, which may not support all module.exports as named exports. + CommonJS modules can always be imported via the default export, for example using: + + import pkg from '@vitejs/cjs-external'; + const {nonExisting} = pkg; + ] + `) + // subsequent imports of the same external package should not throw if imports are correct + await expect( + runner.import('/fixtures/cjs-external-existing.js'), + ).resolves.toMatchObject({ + result: 'world', + }) + }) + + it('importing external esm library checks exports', async ({ runner }) => { + await expect(() => + runner.import('/fixtures/esm-external-non-existing.js'), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `[SyntaxError: [vite] The requested module '@vitejs/esm-external' does not provide an export named 'nonExisting']`, + ) + // subsequent imports of the same external package should not throw if imports are correct + await expect( + runner.import('/fixtures/esm-external-existing.js'), + ).resolves.toMatchObject({ + result: 'world', + }) + }) + + it("dynamic import doesn't produce duplicates", async ({ runner }) => { + const mod = await runner.import('/fixtures/dynamic-import.js') + const modules = await mod.initialize() + // toBe checks that objects are actually the same, not just structurally + // using toEqual here would be a mistake because it check the structural difference + expect(modules.static).toBe(modules.dynamicProcessed) + expect(modules.static).toBe(modules.dynamicRelative) + expect(modules.static).toBe(modules.dynamicAbsolute) + expect(modules.static).toBe(modules.dynamicAbsoluteExtension) + expect(modules.static).toBe(modules.dynamicAbsoluteFull) + expect(modules.static).toBe(modules.dynamicFileUrl) + }) + + it('can load virtual modules as an entry point', async ({ runner }) => { + const mod = await runner.import('virtual:test') + expect(mod.msg).toBe('virtual') + + // already resolved id works similar to `transformRequest` + expect(await runner.import(`\0virtual:normal`)).toMatchInlineSnapshot(` + { + "default": "ok", + } + `) + + // escaped virtual module id works + expect(await runner.import(`/@id/__x00__virtual:normal`)) + .toMatchInlineSnapshot(` + { + "default": "ok", + } + `) + + // timestamp query works + expect(await runner.import(`virtual:normal?t=${Date.now()}`)) + .toMatchInlineSnapshot(` + { + "default": "ok", + } + `) + + // other arbitrary queries don't work + await expect(() => + runner.import('virtual:normal?abcd=1234'), + ).rejects.toMatchObject({ + message: expect.stringContaining( + 'Failed to load url virtual:normal?abcd=1234', + ), + }) + }) + + // files are virtual, so url is not defined + it('correctly resolves module url', async ({ runner, server }) => { + const { meta } = await runner.import('/fixtures/basic.js') + const basicUrl = new _URL('./fixtures/basic.js', import.meta.url).toString() + expect(meta.url).toBe(basicUrl) + + const filename = meta.filename! + const dirname = meta.dirname! + + if (isWindows) { + const cwd = process.cwd() + const drive = `${cwd[0].toUpperCase()}:\\` + const root = server.config.root.replace(/\\/g, '/') + + expect(filename.startsWith(drive)).toBe(true) + expect(dirname.startsWith(drive)).toBe(true) + + expect(filename).toBe(win32.join(root, '.\\fixtures\\basic.js')) + expect(dirname).toBe(win32.join(root, '.\\fixtures')) + } else { + const root = server.config.root + + expect(posix.join(root, './fixtures/basic.js')).toBe(filename) + expect(posix.join(root, './fixtures')).toBe(dirname) + } + }) + + it(`no maximum call stack error ModuleRunner.isCircularImport`, async ({ + runner, + }) => { + // entry.js ⇔ entry-cyclic.js + // ⇓ + // action.js + const mod = await runner.import('./fixtures/cyclic/entry.js') + await mod.setupCyclic() + const action = await mod.importAction('/fixtures/cyclic/action') + expect(action).toBeDefined() + }) + + // rolldown doesn't support this + // - Cannot access 'dep1' before initialization + it(`cyclic invalid 2`, async ({ runner }) => { + // It should be an error but currently `undefined` fallback. + expect( + await runner.import('/fixtures/cyclic2/test6/index.js'), + ).toMatchInlineSnapshot( + ` + { + "dep1": "dep1: dep2: undefined", + } + `, + ) + }) }) describe('optimize-deps', () => { - const it = createModuleRunnerTester({ + it.override('config', { cacheDir: 'node_modules/.vite-test', ssr: { noExternal: true, @@ -452,15 +532,16 @@ describe('optimize-deps', () => { }) describe('resolveId absolute path entry', () => { - const it = createModuleRunnerTester({ + it.override('config', { plugins: [ { name: 'test-resolevId', enforce: 'pre', resolveId(source) { if ( + source === 'virtual:basic-alias' || source === - posix.join(this.environment.config.root, 'fixtures/basic.js') + posix.join(this.environment.config.root, 'fixtures/basic.js') ) { return '\0virtual:basic' } @@ -487,12 +568,27 @@ describe('resolveId absolute path entry', () => { ) expect(mod.name).toMatchInlineSnapshot(`"virtual:basic"`) }) + + describe('in full bundle mode', () => { + const entry = posix.join(slash(import.meta.dirname), 'fixtures/basic.js') + it.override('fullBundle', [entry]) + + it('accepts any ID that resolves to an entry facade', async ({ + runner, + }) => { + const mod = await runner.import('virtual:basic-alias') + expect(mod.name).toMatchInlineSnapshot(`"virtual:basic"`) + }) + }) }) describe('virtual module hmr', () => { let state = 'init' - const it = createModuleRunnerTester({ + it.override('config', { + server: { + hmr: true, + }, plugins: [ { name: 'test-resolevId', @@ -511,12 +607,12 @@ describe('virtual module hmr', () => { ], }) - it('full reload', async ({ server, runner }) => { + it('full reload', async ({ environment, runner }) => { const mod = await runner.import('virtual:test') expect(mod.default).toBe('init') state = 'reloaded' - server.environments.ssr.moduleGraph.invalidateAll() - server.environments.ssr.hot.send({ type: 'full-reload' }) + environment.moduleGraph.invalidateAll() + environment.hot.send({ type: 'full-reload' }) await vi.waitFor(() => { const mod = runner.evaluatedModules.getModuleById('\0virtual:test') expect(mod?.exports.default).toBe('reloaded') @@ -544,8 +640,67 @@ describe('virtual module hmr', () => { }) }) +describe('full reload in full bundle mode', () => { + const hmrLogs: string[] = [] + it.override('fullBundle', ['./fixtures/full-reload.js']) + it.override('runnerOptions', { + hmr: { + logger: { + debug: (...messages) => hmrLogs.push(messages.join(' ')), + error: (error) => hmrLogs.push(String(error)), + }, + }, + }) + it.override('config', { + server: { + hmr: true, + watch: { usePolling: true, interval: 10 }, + }, + }) + + it('continues HMR after re-importing the entrypoint', async ({ runner }) => { + const filename = resolve(import.meta.dirname, './fixtures/full-reload.js') + const { editFile } = createFixtureEditor() + + expect(await runner.import('/fixtures/full-reload.js')).toHaveProperty( + 'value', + 'initial', + ) + + editFile( + filename, + (code) => + code.replace('initial', 'updated') + '\nimport.meta.hot?.accept()\n', + ) + await vi.waitFor( + () => { + expect( + [...runner.evaluatedModules.idToModuleMap.values()].find( + (module) => module.exports?.value === 'updated', + )?.exports, + ).toHaveProperty('value', 'updated') + }, + { timeout: 3_000 }, + ) + + editFile(filename, (code) => code.replace('updated', 'updated-again')) + await vi.waitFor( + () => { + expect( + hmrLogs.some((log) => /hot updated: .*full-reload\.js/.test(log)), + ).toBe(true) + }, + { timeout: 3_000 }, + ) + expect(await runner.import('/fixtures/full-reload.js')).toHaveProperty( + 'value', + 'updated-again', + ) + }) +}) + describe('invalid package', () => { - const it = createModuleRunnerTester({ + it.override('config', { environments: { ssr: { resolve: { @@ -638,7 +793,7 @@ describe('full-reload during close', () => { }) describe('server.fs check', () => { - const it = createModuleRunnerTester({ + it.override('config', { server: { fs: { allow: [resolve(import.meta.dirname, './fixtures/circular')], diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts index 140680c91e917e..144e971873b445 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts @@ -1,29 +1,24 @@ import { resolve } from 'node:path' import { runInThisContext } from 'node:vm' -import { describe, expect } from 'vitest' +import { describe, expect, vi } from 'vitest' import type { ViteDevServer } from '../../..' import type { ModuleRunnerContext } from '../../../../module-runner' import { ESModulesEvaluator } from '../../../../module-runner' import { SOURCEMAPPING_URL } from '../../../../shared/constants' -import { - createFixtureEditor, - createModuleRunnerTester, - resolvePath, -} from './utils' +import { createFixtureEditor, runnerTest as it, resolvePath } from './utils' describe('module runner initialization', () => { - const it = createModuleRunnerTester( - {}, - { + it.override({ + runnerOptions: { sourcemapInterceptor: 'prepareStackTrace', }, - ) + }) const getError = async (cb: () => void): Promise => { try { await cb() expect.unreachable() - } catch (err) { + } catch (err: any) { return err } } @@ -139,6 +134,37 @@ describe('module runner initialization', () => { ]) }) + describe('bundled lazy imports', () => { + it.override('fullBundle', ['./fixtures/dynamic-import-source-map.js']) + + it('maps lazy module stack traces to the original source', async ({ + runner, + server, + environment, + onTestFinished, + }) => { + const fetchModule = vi.spyOn(environment, 'fetchModule') + onTestFinished(() => fetchModule.mockRestore()) + + const entry = await runner.import( + '/fixtures/dynamic-import-source-map.js', + ) + const mod = await entry.load() + + expect(fetchModule).toHaveBeenCalledWith( + expect.stringContaining('/@vite/lazy?'), + undefined, + expect.any(Object), + ) + + const error = await getError(() => mod.main()) + expect(serializeStackDeep(server, error).slice(1, 3)).toStrictEqual([ + expect.stringContaining('/fixtures/has-error-deep.ts:2:9'), + expect.stringContaining('/fixtures/has-error-deep.ts:6:3'), + ]) + }) + }) + it('preserves async stack frame formatting', async ({ runner, server }) => { const error = await getError(async () => { const mod = await runner.import('/fixtures/has-error-async.ts') @@ -291,13 +317,12 @@ describe('module runner with node:vm executor', () => { } } - const it = createModuleRunnerTester( - {}, - { + it.override({ + runnerOptions: { sourcemapInterceptor: 'prepareStackTrace', evaluator: new Evaluator(), }, - ) + }) it('should not crash when error stacktrace contains negative column', async ({ runner, @@ -339,9 +364,8 @@ describe('module runner interceptor with inline data: source map', () => { } } - const it = createModuleRunnerTester( - {}, - { + it.override({ + runnerOptions: { sourcemapInterceptor: { // Serves a file that is not part of the runner module graph and // carries an inline base64 source map, so mapping goes through @@ -354,7 +378,7 @@ describe('module runner interceptor with inline data: source map', () => { }, evaluator: new Evaluator(), }, - ) + }) it('should not crash when decoding an inline source map while globalThis.Buffer is absent', async ({ runner, diff --git a/packages/vite/src/node/ssr/runtime/__tests__/utils.ts b/packages/vite/src/node/ssr/runtime/__tests__/utils.ts index 9fd3faca7907dc..1ade3e966bf43a 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/utils.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/utils.ts @@ -1,101 +1,109 @@ import fs from 'node:fs' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { onTestFinished, test } from 'vitest' +import { test as base, onTestFinished } from 'vitest' import type { InlineConfig } from '../../../config' import type { ViteDevServer } from '../../../server' import { createServer } from '../../../server' -import type { ServerModuleRunnerOptions } from '../serverModuleRunner' -import { createServerModuleRunner } from '../serverModuleRunner' +import type { RunnableDevEnvironment } from '../../../server/environments/runnableEnvironment' +import { + type ServerModuleRunnerOptions, + createServerModuleRunner, +} from '../serverModuleRunner' -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -- infer the fixture context from the builder -export function createModuleRunnerTester( - config: InlineConfig = {}, - runnerConfig: ServerModuleRunnerOptions = {}, -) { - function waitForWatcher(server: ViteDevServer) { - return new Promise((resolve) => { - if ((server.watcher as any)._readyEmitted) { - resolve() - } else { - server.watcher.once('ready', () => resolve()) - } - }) - } - - return ( - test - // eslint-disable-next-line no-empty-pattern - .extend('server', async ({}, { onCleanup }) => { - // @ts-ignore - globalThis.__HMR__ = {} - - const server = await createServer({ - root: import.meta.dirname, - logLevel: 'error', - server: { - middlewareMode: true, - watch: null, - ws: false, - }, - ssr: { - external: ['@vitejs/cjs-external', '@vitejs/esm-external'], - }, - optimizeDeps: { - disabled: true, - noDiscovery: true, - include: [], +export const runnerTest = base + .extend('fullBundle', [] as string[]) + .extend('runnerOptions', undefined as ServerModuleRunnerOptions | undefined) + .extend('config', {} as InlineConfig) + .extend('server', async ({ config, fullBundle }, { onCleanup }) => { + const server = await createServer({ + configFile: false, + root: import.meta.dirname, + logLevel: 'error', + ssr: { + external: ['@vitejs/cjs-external', '@vitejs/esm-external'], + }, + environments: { + ssr: { + isBundled: fullBundle.length > 0, + }, + }, + build: { + rolldownOptions: { + input: fullBundle, + ...config.build?.rolldownOptions, + }, + ...config.build, + }, + optimizeDeps: { + disabled: true, + noDiscovery: true, + include: [], + }, + plugins: [ + { + name: 'vite-plugin-virtual', + resolveId(id) { + if (id === 'virtual0:test') { + return `\0virtual:test` + } + if (id === 'virtual:test') { + return 'virtual:test' + } + if (id === 'virtual:normal') { + return '\0' + id + } }, - plugins: [ - { - name: 'vite-plugin-virtual', - resolveId(id) { - if (id === 'virtual0:test') { - return `\0virtual:test` - } - if (id === 'virtual:test') { - return 'virtual:test' - } - if (id === 'virtual:normal') { - return '\0' + id - } - }, - load(id) { - if (id === `\0virtual:test`) { - return `export const msg = 'virtual0'` - } - if (id === `virtual:test`) { - return `export const msg = 'virtual'` - } - if (id === '\0virtual:normal') { - return 'export default "ok"' - } - }, - }, - ...(config.plugins ?? []), - ], - ...config, - }) - onCleanup(() => server.close()) - return server - }) - .extend('environment', ({ server }) => server.environments.ssr) - .extend('runner', async ({ server, environment }, { onCleanup }) => { - const runner = createServerModuleRunner(environment, { - hmr: { - logger: false, + load(id) { + if (id === `\0virtual:test`) { + return `export const msg = 'virtual0'` + } + if (id === `virtual:test`) { + return `export const msg = 'virtual'` + } + if (id === '\0virtual:normal') { + return 'export default "ok"' + } }, - // don't override by default so Vitest source maps are correct - sourcemapInterceptor: false, - ...runnerConfig, - }) - onCleanup(() => runner.close()) - if (config.server?.watch) { - await waitForWatcher(server) - } - return runner - }) + }, + ...(config.plugins ?? []), + ], + ...config, + server: { + middlewareMode: true, + watch: null, + ws: false, + hmr: false, + ...config.server, + }, + }) + onCleanup(() => server.close()) + if (config.server?.watch) { + await waitForWatcher(server) + } + return server + }) + .extend( + 'environment', + ({ server }) => server.environments.ssr as RunnableDevEnvironment, ) + .extend('runner', ({ environment, runnerOptions }, { onCleanup }) => { + if (runnerOptions) { + const runner = createServerModuleRunner(environment, runnerOptions) + onCleanup(() => runner.close()) + return runner + } + return environment.runner + }) + +function waitForWatcher(server: ViteDevServer) { + return new Promise((resolve) => { + if ((server.watcher as any)._readyEmitted) { + resolve() + } else { + server.watcher.once('ready', () => resolve()) + } + }) } type FixtureEditor = { diff --git a/packages/vite/src/node/ssr/runtime/serverModuleRunner.ts b/packages/vite/src/node/ssr/runtime/serverModuleRunner.ts index 2400ec357a0c2b..64488646744364 100644 --- a/packages/vite/src/node/ssr/runtime/serverModuleRunner.ts +++ b/packages/vite/src/node/ssr/runtime/serverModuleRunner.ts @@ -57,6 +57,7 @@ function createHMROptions( return { logger: options.hmr?.logger ?? defaultLogger, + partialAccept: environment.config.experimental.hmrPartialAccept, } } @@ -89,9 +90,14 @@ export const createServerModuleRunnerTransport = (options: { }): ModuleRunnerTransport => { const hmrClient: HotChannelClient = { send: (payload: HotPayload) => { - if (payload.type !== 'custom') { + if ( + payload.type !== 'custom' && + payload.type !== 'update' && + payload.type !== 'bundled-dev-update' && + payload.type !== 'full-reload' + ) { throw new Error( - 'Cannot send non-custom events from the client to the server.', + `Cannot send events of type '${payload.type}' from the client to the server.`, ) } options.channel.send(payload) @@ -147,6 +153,7 @@ export function createServerModuleRunner( const hmr = createHMROptions(environment, options) return new ModuleRunner( { + rolldownRuntime: environment.config.isBundled, ...options, transport: createServerModuleRunnerTransport({ channel: environment.hot as NormalizedServerHotChannel, @@ -158,3 +165,8 @@ export function createServerModuleRunner( options.evaluator, ) } + +export interface ServerModuleRunnerFactoryOptions { + runner?: (environment: E, options?: ServerModuleRunnerOptions) => ModuleRunner + runnerOptions?: ServerModuleRunnerOptions +} diff --git a/packages/vite/src/client/bundledDevHmrClient.ts b/packages/vite/src/shared/bundledDevHmr.ts similarity index 92% rename from packages/vite/src/client/bundledDevHmrClient.ts rename to packages/vite/src/shared/bundledDevHmr.ts index 2452f059034068..2f5ddf0db9e395 100644 --- a/packages/vite/src/client/bundledDevHmrClient.ts +++ b/packages/vite/src/shared/bundledDevHmr.ts @@ -3,8 +3,9 @@ import type { Update, UpdatePayload, } from '#types/hmrPayload' -import { HMRClient, HMRContext, type HMRLogger } from '../shared/hmr' -import type { NormalizedModuleRunnerTransport } from '../shared/moduleRunnerTransport' +import type { ModuleNamespace } from '#types/hot' +import { HMRClient, HMRContext, type HMRLogger } from './hmr' +import type { NormalizedModuleRunnerTransport } from './moduleRunnerTransport' /** the subset of `__rolldown_runtime__` the HMR client uses */ export interface RolldownRuntimeLike { @@ -34,10 +35,20 @@ type HmrUpdate = } export interface BundledDevHMRClientOptions { - base: string + /** + * Loads and executes the HMR patch chunk served at `url`. The browser imports + * it, the module runner fetches it through its own transport. + */ + loadPatch: (url: string) => Promise partialAccept: boolean /** returning `'reload'` aborts the apply — the hook reloads the page itself */ beforeApply: () => 'reload' | 'continue' + /** + * Only used for the plain `update` payloads this client inherits from + * `HMRClient`. Full-bundle updates never go through it, but the module runner + * uses the same client for both modes, so it needs a working implementation. + */ + importUpdatedModule?: (update: Update) => Promise } export class BundledDevHMRClient extends HMRClient { @@ -51,11 +62,27 @@ export class BundledDevHMRClient extends HMRClient { private runtime: RolldownRuntimeLike, private options: BundledDevHMRClientOptions, ) { - super(logger, transport, async () => { - throw new Error( - 'unreachable: full-bundle mode applies patches through its own queue', - ) + super( + logger, + transport, + options.importUpdatedModule ?? + (async () => { + throw new Error( + 'unreachable: full-bundle mode applies patches through its own queue', + ) + }), + ) + } + + resetForFullReload(runtime: RolldownRuntimeLike): Promise { + this.applyQueue = this.applyQueue.then(() => { + this.runtime = runtime + this.lastSeq = 0 + this.reloadPending = false + this.currentFirstInvalidatedBy = undefined + this.clear() }) + return this.applyQueue } isSelfAccepted(id: string): boolean { @@ -326,7 +353,7 @@ export class BundledDevHMRClient extends HMRClient { if (this.options.beforeApply() === 'reload') return try { - await import(/* @vite-ignore */ this.options.base + url) + await this.options.loadPatch(url) } catch { this.requestFullReload(`failed to import hmr patch ${url}`) return diff --git a/packages/vite/src/shared/invokeMethods.ts b/packages/vite/src/shared/invokeMethods.ts index 57b1993060105f..8ca6a5d0ddcb96 100644 --- a/packages/vite/src/shared/invokeMethods.ts +++ b/packages/vite/src/shared/invokeMethods.ts @@ -54,6 +54,12 @@ export interface ViteFetchResult { * Invalidate module on the client side. */ invalidate: boolean + /** + * Original entry module ID in Rolldown's runtime. + * Used to retrieve updated exports after HMR. + * @experimental + */ + rolldownModuleId?: string } export type InvokeSendData< @@ -89,4 +95,9 @@ export type InvokeMethods = { | { type: 'RegExp'; source: string; flags: string } > > + + resetBundledDevClient: ( + oldClientId: string, + newClientId: string, + ) => Promise } diff --git a/playground/ssr-bundled-dev/__tests__/serve.ts b/playground/ssr-bundled-dev/__tests__/serve.ts new file mode 100644 index 00000000000000..389e923ebefc63 --- /dev/null +++ b/playground/ssr-bundled-dev/__tests__/serve.ts @@ -0,0 +1,41 @@ +// this is automatically detected by playground/vitestSetup.ts and will replace +// the default e2e test serve behavior + +import path from 'node:path' +import kill from 'kill-port' +import { createInMemoryLogger, hmrPorts, ports, rootDir } from '~utils' + +export const port = ports['ssr-bundled-dev'] + +export const serverLogs = [] + +export async function serve(): Promise<{ close(): Promise }> { + await kill(port) + + const { createServer } = await import(path.resolve(rootDir, 'server.js')) + const { app, vite } = await createServer( + rootDir, + hmrPorts['ssr-bundled-dev'], + createInMemoryLogger(serverLogs), + ) + + return new Promise((resolve, reject) => { + try { + const server = app.listen(port, () => { + resolve({ + // for test teardown + async close() { + await new Promise((resolve) => { + server.close(resolve) + }) + if (vite) { + await vite.close() + } + }, + }) + }) + } catch (e) { + reject(e) + } + }) +} diff --git a/playground/ssr-bundled-dev/__tests__/ssr.spec.ts b/playground/ssr-bundled-dev/__tests__/ssr.spec.ts new file mode 100644 index 00000000000000..76dbf84c8b5a33 --- /dev/null +++ b/playground/ssr-bundled-dev/__tests__/ssr.spec.ts @@ -0,0 +1,80 @@ +import { expect, test } from 'vitest' +import { browserLogs, editFile, isServe, page } from '~utils' +import { port, serverLogs } from './serve' + +const url = `http://localhost:${port}` + +test(`circular dependencies modules doesn't throw`, async () => { + await page.goto(`${url}/circular-dep`) + + expect(await page.textContent('.circ-dep-init')).toMatch( + 'circ-dep-init-a circ-dep-init-b', + ) +}) + +test(`circular import doesn't throw (1)`, async () => { + await page.goto(`${url}/circular-import`) + + expect(await page.textContent('.circ-import')).toMatchInlineSnapshot( + '"A is: __A__"', + ) +}) + +test(`circular import doesn't throw (2)`, async () => { + await page.goto(`${url}/circular-import2`) + + expect(await page.textContent('.circ-import')).toMatchInlineSnapshot( + '"A is: __A__"', + ) +}) + +test(`deadlock doesn't happen for static imports`, async () => { + await page.goto(`${url}/forked-deadlock-static-imports`) + + expect(await page.textContent('.forked-deadlock-static-imports')).toMatch( + 'rendered', + ) +}) + +test(`deadlock doesn't happen for dynamic imports`, async () => { + await page.goto(`${url}/forked-deadlock-dynamic-imports`) + + expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch( + 'rendered', + ) +}) + +test(`import.meta.resolve is supported`, async () => { + await page.goto(`${url}/import-meta`) + + const metaUrl = await page.textContent('.import-meta-url') + expect(metaUrl).not.toBe('') + expect(await page.textContent('.import-meta-resolve')).toBe(metaUrl) +}) + +test(`import.meta.main is supported`, async () => { + await page.goto(`${url}/import-meta`) + + expect(await page.textContent('.import-meta-main')).toBe('false') +}) + +test.runIf(isServe)('html proxy is encoded', async () => { + await page.goto( + `${url}?%22%3E%3C/script%3E%3Cscript%3Econsole.log(%27html%20proxy%20is%20not%20encoded%27)%3C/script%3E`, + ) + + expect(browserLogs).not.toContain('html proxy is not encoded') +}) + +// run this at the end to reduce flakiness +test.runIf(isServe)('should restart ssr', async () => { + editFile('./vite.config.ts', (content) => content + '\n') + await expect + .poll(() => { + expect(serverLogs).toContainEqual( + expect.stringMatching('server restarted'), + ) + expect(serverLogs).not.toContainEqual(expect.stringMatching('error')) + }) + .toSatisfy(() => true) +}) diff --git a/playground/ssr-bundled-dev/index.html b/playground/ssr-bundled-dev/index.html new file mode 100644 index 00000000000000..1b901ee15cf153 --- /dev/null +++ b/playground/ssr-bundled-dev/index.html @@ -0,0 +1,16 @@ + + + + + + SSR + + + +

SSR

+
+ + diff --git a/playground/ssr-bundled-dev/package.json b/playground/ssr-bundled-dev/package.json new file mode 100644 index 00000000000000..232de8fe81bf28 --- /dev/null +++ b/playground/ssr-bundled-dev/package.json @@ -0,0 +1,15 @@ +{ + "name": "@vitejs/test-ssr", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "node server", + "serve": "NODE_ENV=production node server", + "debug": "node --inspect-brk server" + }, + "dependencies": {}, + "devDependencies": { + "express": "^5.2.1" + } +} diff --git a/playground/ssr-bundled-dev/server.js b/playground/ssr-bundled-dev/server.js new file mode 100644 index 00000000000000..0b7fd29f58d2a6 --- /dev/null +++ b/playground/ssr-bundled-dev/server.js @@ -0,0 +1,79 @@ +import fs from 'node:fs' +import path from 'node:path' +import express from 'express' +import { isRunnableDevEnvironment } from 'vite' + +const isTest = process.env.VITEST + +export async function createServer( + root = process.cwd(), + hmrPort, + customLogger, +) { + const resolve = (p) => path.resolve(import.meta.dirname, p) + + const app = express() + + /** + * @type {import('vite').ViteDevServer} + */ + const vite = await ( + await import('vite') + ).createServer({ + root, + logLevel: isTest ? 'error' : 'info', + server: { + middlewareMode: true, + watch: { + // During tests we edit the files too fast and sometimes chokidar + // misses change events, so enforce polling for consistency + usePolling: true, + interval: 100, + }, + hmr: { + port: hmrPort, + }, + }, + appType: 'custom', + customLogger, + }) + // use vite's connect instance as middleware + app.use(vite.middlewares) + + app.use('*all', async (req, res, next) => { + if (!isRunnableDevEnvironment(vite.environments.ssr)) { + res.status(500) + return + } + + try { + const url = req.originalUrl + + let template + template = fs.readFileSync(resolve('index.html'), 'utf-8') + template = await vite.transformIndexHtml(url, template) + const render = (await vite.environments.ssr.runner.import('/src/app.js')) + .render + + const appHtml = await render(url, import.meta.dirname) + + const html = template.replace(``, appHtml) + + res.status(200).set({ 'Content-Type': 'text/html' }).end(html) + } catch (e) { + if (isTest) throw e + console.log(e.stack) + res.status(500).end(e.stack) + } + }) + + return { app, vite } +} + +if (!isTest) { + createServer().then(({ app }) => + app.listen(5173, () => { + console.log('http://localhost:5173') + }), + ) +} diff --git a/playground/ssr-bundled-dev/src/app.js b/playground/ssr-bundled-dev/src/app.js new file mode 100644 index 00000000000000..972ba427f9e050 --- /dev/null +++ b/playground/ssr-bundled-dev/src/app.js @@ -0,0 +1,73 @@ +import { escapeHtml } from './utils' + +const pathRenderers = { + '/': renderRoot, + '/circular-dep': renderCircularDep, + '/circular-import': renderCircularImport, + '/circular-import2': renderCircularImport2, + '/forked-deadlock-static-imports': renderForkedDeadlockStaticImports, + '/forked-deadlock-dynamic-imports': renderForkedDeadlockDynamicImports, + '/import-meta': renderImportMeta, +} + +export async function render(url, rootDir) { + const pathname = url.replace(/#[^#]*$/, '').replace(/\?[^?]*$/, '') + const renderer = pathRenderers[pathname] + if (renderer) { + return await renderer(rootDir) + } + return '404' +} + +async function renderRoot(rootDir) { + const paths = Object.keys(pathRenderers).filter((key) => key !== '/') + return ` + + ` +} + +async function renderCircularDep(rootDir) { + const { getValueAB } = await import('./circular-dep-init/circular-dep-init') + return `
${escapeHtml(getValueAB())}
` +} + +async function renderCircularImport(rootDir) { + const { logA } = await import('./circular-import/index.js') + return `
${escapeHtml(logA())}
` +} + +async function renderCircularImport2(rootDir) { + const { logA } = await import('./circular-import2/index.js') + return `
${escapeHtml(logA())}
` +} + +async function renderForkedDeadlockStaticImports(rootDir) { + const { commonModuleExport } = await import('./forked-deadlock/common-module') + commonModuleExport() + return `
rendered
` +} + +async function renderForkedDeadlockDynamicImports(rootDir) { + const { commonModuleExport } = + await import('./forked-deadlock/dynamic-imports/common-module') + await commonModuleExport() + return `
rendered
` +} + +async function renderImportMeta(rootDir) { + const metaUrl = import.meta.url + const resolveResult = import.meta.resolve('./app.js') + const metaMain = import.meta.main + return ( + `
${escapeHtml(metaUrl)}
` + + `
${escapeHtml(resolveResult)}
` + + `
${escapeHtml(String(metaMain))}
` + ) +} diff --git a/playground/ssr-bundled-dev/src/circular-dep-init/README.md b/playground/ssr-bundled-dev/src/circular-dep-init/README.md new file mode 100644 index 00000000000000..864d16ae8c495b --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-dep-init/README.md @@ -0,0 +1 @@ +This test aim to find out wherever the modules with circular dependencies are correctly initialized diff --git a/playground/ssr-bundled-dev/src/circular-dep-init/circular-dep-init.js b/playground/ssr-bundled-dev/src/circular-dep-init/circular-dep-init.js new file mode 100644 index 00000000000000..8867d64ec45091 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-dep-init/circular-dep-init.js @@ -0,0 +1,2 @@ +export * from './module-a' +export { getValueAB } from './module-b' diff --git a/playground/ssr-bundled-dev/src/circular-dep-init/module-a.js b/playground/ssr-bundled-dev/src/circular-dep-init/module-a.js new file mode 100644 index 00000000000000..335b3ac26ab3b5 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-dep-init/module-a.js @@ -0,0 +1 @@ +export const valueA = 'circ-dep-init-a' diff --git a/playground/ssr-bundled-dev/src/circular-dep-init/module-b.js b/playground/ssr-bundled-dev/src/circular-dep-init/module-b.js new file mode 100644 index 00000000000000..cb16d7e9be4a30 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-dep-init/module-b.js @@ -0,0 +1,8 @@ +import { valueA } from './circular-dep-init' + +export const valueB = 'circ-dep-init-b' +export const valueAB = valueA.concat(` ${valueB}`) + +export function getValueAB() { + return valueAB +} diff --git a/playground/ssr-bundled-dev/src/circular-import/a.js b/playground/ssr-bundled-dev/src/circular-import/a.js new file mode 100644 index 00000000000000..00c8645fd78b12 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import/a.js @@ -0,0 +1,5 @@ +import { getB } from './b' + +export const A = '__A__' + +export const B = getB() diff --git a/playground/ssr-bundled-dev/src/circular-import/b.js b/playground/ssr-bundled-dev/src/circular-import/b.js new file mode 100644 index 00000000000000..c0e732b29e2035 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import/b.js @@ -0,0 +1,5 @@ +export function getB() { + return '__B__' +} + +export { A } from './a' diff --git a/playground/ssr-bundled-dev/src/circular-import/index.js b/playground/ssr-bundled-dev/src/circular-import/index.js new file mode 100644 index 00000000000000..c9ec0fc50238b4 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import/index.js @@ -0,0 +1,5 @@ +import { A } from './b' + +export function logA() { + return `A is: ${A}` +} diff --git a/playground/ssr-bundled-dev/src/circular-import2/a.js b/playground/ssr-bundled-dev/src/circular-import2/a.js new file mode 100644 index 00000000000000..00c8645fd78b12 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import2/a.js @@ -0,0 +1,5 @@ +import { getB } from './b' + +export const A = '__A__' + +export const B = getB() diff --git a/playground/ssr-bundled-dev/src/circular-import2/b.js b/playground/ssr-bundled-dev/src/circular-import2/b.js new file mode 100644 index 00000000000000..772e68833f300b --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import2/b.js @@ -0,0 +1,5 @@ +export { A } from './a' + +export function getB() { + return '__B__' +} diff --git a/playground/ssr-bundled-dev/src/circular-import2/index.js b/playground/ssr-bundled-dev/src/circular-import2/index.js new file mode 100644 index 00000000000000..c9ec0fc50238b4 --- /dev/null +++ b/playground/ssr-bundled-dev/src/circular-import2/index.js @@ -0,0 +1,5 @@ +import { A } from './b' + +export function logA() { + return `A is: ${A}` +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/README.md b/playground/ssr-bundled-dev/src/forked-deadlock/README.md new file mode 100644 index 00000000000000..2ef77cfc927565 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/README.md @@ -0,0 +1,51 @@ +This test aims to check for a particular type of circular dependency that causes tricky deadlocks, **deadlocks with forked imports stack** + +``` +A -> B means: B is imported by A and B has A in its stack +A ... B means: A is waiting for B to ssrLoadModule() + +H -> X ... Y +H -> X -> Y ... B +H -> A ... B +H -> A -> B ... X +``` + +### Forked deadlock description: + +``` +[X] is waiting for [Y] to resolve + ↑ ↳ is waiting for [A] to resolve + │ ↳ is waiting for [B] to resolve + │ ↳ is waiting for [X] to resolve + └────────────────────────────────────────────────────────────────────────┘ +``` + +This may seems a traditional deadlock, but the thing that makes this special is the import stack of each module: + +``` +[X] stack: + [H] +``` + +``` +[Y] stack: + [X] + [H] +``` + +``` +[A] stack: + [H] +``` + +``` +[B] stack: + [A] + [H] +``` + +Even if `[X]` is imported by `[B]`, `[B]` is not in `[X]`'s stack because it's imported by `[H]` in first place then it's stack is only composed by `[H]`. `[H]` **forks** the imports **stack** and this makes it hard to be found. + +### Fix description + +Vite, when imports `[X]`, should check whether `[X]` is already pending and if it is, it must check that, when it was imported in first place, the stack of `[X]` doesn't have any module in common with the current module; in this case `[B]` has the module `[H]` is common with `[X]` and i can assume that a deadlock is going to happen. diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/common-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/common-module.js new file mode 100644 index 00000000000000..eaad0a3dbfa78c --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/common-module.js @@ -0,0 +1,10 @@ +import { deadlockfuseModuleExport } from './deadlock-fuse-module' +import { stuckModuleExport } from './stuck-module' + +/** + * module H + */ +export function commonModuleExport() { + stuckModuleExport() + deadlockfuseModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/deadlock-fuse-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/deadlock-fuse-module.js new file mode 100644 index 00000000000000..4f31763ba2343f --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/deadlock-fuse-module.js @@ -0,0 +1,8 @@ +import { fuseStuckBridgeModuleExport } from './fuse-stuck-bridge-module' + +/** + * module A + */ +export function deadlockfuseModuleExport() { + fuseStuckBridgeModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/common-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/common-module.js new file mode 100644 index 00000000000000..045383548daec8 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/common-module.js @@ -0,0 +1,13 @@ +/** + * module H + */ +export async function commonModuleExport() { + const [{ stuckModuleExport }, { deadlockfuseModuleExport }] = + await Promise.all([ + import('./stuck-module'), + import('./deadlock-fuse-module'), + ]) + + stuckModuleExport() + deadlockfuseModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/deadlock-fuse-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/deadlock-fuse-module.js new file mode 100644 index 00000000000000..4f31763ba2343f --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/deadlock-fuse-module.js @@ -0,0 +1,8 @@ +import { fuseStuckBridgeModuleExport } from './fuse-stuck-bridge-module' + +/** + * module A + */ +export function deadlockfuseModuleExport() { + fuseStuckBridgeModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/fuse-stuck-bridge-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/fuse-stuck-bridge-module.js new file mode 100644 index 00000000000000..211ad7c3bc9f92 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/fuse-stuck-bridge-module.js @@ -0,0 +1,8 @@ +import { stuckModuleExport } from './stuck-module' + +/** + * module C + */ +export function fuseStuckBridgeModuleExport() { + stuckModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/middle-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/middle-module.js new file mode 100644 index 00000000000000..0632eedeabd7a5 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/middle-module.js @@ -0,0 +1,8 @@ +import { deadlockfuseModuleExport } from './deadlock-fuse-module' + +/** + * module Y + */ +export function middleModuleExport() { + void deadlockfuseModuleExport +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/stuck-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/stuck-module.js new file mode 100644 index 00000000000000..50b4d28063dc70 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/dynamic-imports/stuck-module.js @@ -0,0 +1,8 @@ +import { middleModuleExport } from './middle-module' + +/** + * module X + */ +export function stuckModuleExport() { + middleModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/fuse-stuck-bridge-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/fuse-stuck-bridge-module.js new file mode 100644 index 00000000000000..211ad7c3bc9f92 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/fuse-stuck-bridge-module.js @@ -0,0 +1,8 @@ +import { stuckModuleExport } from './stuck-module' + +/** + * module C + */ +export function fuseStuckBridgeModuleExport() { + stuckModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/middle-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/middle-module.js new file mode 100644 index 00000000000000..0632eedeabd7a5 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/middle-module.js @@ -0,0 +1,8 @@ +import { deadlockfuseModuleExport } from './deadlock-fuse-module' + +/** + * module Y + */ +export function middleModuleExport() { + void deadlockfuseModuleExport +} diff --git a/playground/ssr-bundled-dev/src/forked-deadlock/stuck-module.js b/playground/ssr-bundled-dev/src/forked-deadlock/stuck-module.js new file mode 100644 index 00000000000000..50b4d28063dc70 --- /dev/null +++ b/playground/ssr-bundled-dev/src/forked-deadlock/stuck-module.js @@ -0,0 +1,8 @@ +import { middleModuleExport } from './middle-module' + +/** + * module X + */ +export function stuckModuleExport() { + middleModuleExport() +} diff --git a/playground/ssr-bundled-dev/src/utils.js b/playground/ssr-bundled-dev/src/utils.js new file mode 100644 index 00000000000000..cffcfe5f7cec22 --- /dev/null +++ b/playground/ssr-bundled-dev/src/utils.js @@ -0,0 +1,16 @@ +const escapeHtmlReplaceMap = { + '&': '&', + "'": ''', + '`': '`', + '"': '"', + '<': '<', + '>': '>', +} + +/** + * @param {string} string + * @returns {string} + */ +export function escapeHtml(string) { + return string.replace(/[&'`"<>]/g, (match) => escapeHtmlReplaceMap[match]) +} diff --git a/playground/ssr-bundled-dev/vite.config.ts b/playground/ssr-bundled-dev/vite.config.ts new file mode 100644 index 00000000000000..17cf90ec44a4d4 --- /dev/null +++ b/playground/ssr-bundled-dev/vite.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from 'vite' + +export default defineConfig({ + build: { + rolldownOptions: { + input: ['./src/app.js'], + }, + }, + environments: { + client: { + isBundled: true, + }, + ssr: { + isBundled: true, + }, + }, +}) diff --git a/playground/test-utils.ts b/playground/test-utils.ts index cfe208fefd6991..46ae8f2e225016 100644 --- a/playground/test-utils.ts +++ b/playground/test-utils.ts @@ -55,6 +55,7 @@ export const ports = { 'proxy-hmr': 9616, // not imported but used in `proxy-hmr/vite.config.js` 'proxy-hmr/other-app': 9617, // not imported but used in `proxy-hmr/other-app/vite.config.js` 'ssr-conditions': 9620, + 'ssr-bundled-dev': 9621, 'css/postcss-caching': 5005, 'css/postcss-plugins-different-dir': 5006, 'css/dynamic-import': 5007, @@ -77,6 +78,7 @@ export const hmrPorts = { 'ssr-conditions': 24688, 'client-reload/hmr-port': 24689, 'client-reload/cross-origin': 24690, + 'ssr-bundled-dev': 24692, } const hexToNameMap: Record = {} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 61c165ebb41be6..26c3c5b9cface6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1782,6 +1782,12 @@ importers: playground/ssr-alias/alias-original: {} + playground/ssr-bundled-dev: + devDependencies: + express: + specifier: ^5.2.1 + version: 5.3.0(ms@2.1.3) + playground/ssr-conditions: dependencies: '@vitejs/test-ssr-conditions-external': diff --git a/vitest.config.ts b/vitest.config.ts index 86bcf66669dba5..33570f425f9b37 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,6 +6,7 @@ const _dirname = path.dirname(url.fileURLToPath(import.meta.url)) export default defineConfig({ test: { + includeTaskLocation: true, include: ['**/__tests__/**/*.spec.[tj]s'], exclude: [ '**/node_modules/**',