histoire
Version:
A fast story book powered by Vite
211 lines (210 loc) • 10.9 kB
JavaScript
import { dirname } from 'pathe';
import { APP_PATH, getHistoireStyleFiles } from '../alias.js';
import { tailwindRuntimeDirectory } from '../builtin-plugins/tailwind/template.js';
import { getContextRegistry } from '../runtime/registry.js';
import { installUiHttpRouter } from '../server/ui-channel/http.js';
import { notifyStoryChange } from '../stories.js';
import { resolveAccessibilityRuntime } from '../util/resolve-accessibility-runtime.js';
import { resolveHistoireAppBundledDir } from '../util/resolve-histoire-app.js';
import { createOptimizerCacheIgnore } from '../util/story-ignore.js';
import { getCollectionCacheFile } from '../util/temp-paths.js';
import { createEmbedMiddleware } from '../virtual/embed/middleware.js';
import { resolveVisualConfig } from '../visual/config.js';
import { retireVisualSource } from '../visual/source.js';
import { createAppHtmlMiddleware, createSandboxHtmlMiddleware } from './dev-html.js';
import { createMcpPreviewHtmlMiddleware } from './mcp-preview-html.js';
import { createMswWorkerMiddleware } from './msw-worker.js';
import { getStoryOptimizerEntries, getViteCacheDir } from './optimizer-cache.js';
import { histoireSharedPath, resolveSupportPluginAllowPaths, resolveWorkbenchPluginAllowPaths, tryResolveDependency, withPackageDirs } from './resolve-paths.js';
import { createWorkbenchVueResolver } from './workbench-vue.js';
/**
* Builds the main Histoire Vite plugin: base aliases, dep optimizer setup, dev
* server file permissions, story hot updates and the dev HTML documents.
* @param ctx The histoire context.
* @param options Plugin options (see {@link HistoireVitePluginOptions}).
*/
export function createHistoireVitePlugin(ctx, options) {
const { isServer, browserRuntime, browserRuntimePaths } = options;
const supportPluginAllowPaths = resolveSupportPluginAllowPaths(ctx);
const controlsEntry = tryResolveDependency(ctx.root, '@histoire/controls/package.json');
// Peer CSS retains font URLs after package publishing, so Vite must serve its assets.
const controlsAllowPaths = controlsEntry ? [dirname(controlsEntry)] : [];
const { tempDir } = getContextRegistry(ctx);
const visual = resolveVisualConfig(ctx.config.visual);
const accessibilityRuntime = resolveAccessibilityRuntime(ctx.root, ctx.config.inspection);
return {
name: 'histoire-vite-plugin',
// Workbench plugin client graphs share the workbench's vendored Vue.
resolveId: createWorkbenchVueResolver(),
config(_, { command }) {
const optimizeEntries = browserRuntime
? []
: [
`${APP_PATH}/bundle-main.js`,
`${APP_PATH}/bundle-sandbox.js`,
...getStoryOptimizerEntries(ctx),
];
const optimizeInclude = browserRuntime
? []
: [
...withPackageDirs([
'shiki',
]),
// Imported by Histoire's Vitest browser runtime, past the scan:
// discovered when the first document loads them, they reload it.
...browserRuntimePaths.mswBrowser ? ['msw/browser'] : [],
...browserRuntimePaths.mswCoreHttp ? ['msw/core/http'] : [],
...browserRuntimePaths.mswHttpFallback ? ['msw/http'] : [],
// The virtual v5 story shim imports Vitest after the initial scan.
...browserRuntimePaths.vitestHasBundledExpect ? ['vitest'] : [],
];
return {
resolve: {
dedupe: [
'vue',
],
alias: [
{
find: 'histoire-style',
replacement: getHistoireStyleFiles().style,
},
{
find: 'histoire-bundled-style',
replacement: getHistoireStyleFiles().bundledStyle,
},
{
find: /^@histoire\/shared$/,
replacement: histoireSharedPath,
},
...(browserRuntimePaths.mswBrowser
? [{
find: /^msw\/browser$/,
replacement: browserRuntimePaths.mswBrowser,
}]
: []),
...(browserRuntimePaths.mswCoreHttp
? [{
find: /^msw\/core\/http$/,
replacement: browserRuntimePaths.mswCoreHttp,
}]
: []),
...(browserRuntimePaths.mswHttpFallback
? [{
find: /^msw\/http$/,
replacement: browserRuntimePaths.mswHttpFallback,
}]
: []),
],
...(isServer
? {
// Force resolving deps like Node.JS resolution algorithm (in case some modules are not loaded with ssr: true e.g. .vue files)
conditions: ['node'],
}
: {}),
},
optimizeDeps: {
entries: optimizeEntries,
include: optimizeInclude,
noDiscovery: browserRuntime,
exclude: [
'histoire',
'@histoire/vendors',
...browserRuntime && !browserRuntimePaths.vitestHasBundledExpect
? ['vitest']
: [],
],
},
server: {
fs: {
allow: [
APP_PATH,
tailwindRuntimeDirectory,
resolveHistoireAppBundledDir(),
tempDir,
ctx.resolvedViteConfig.root,
ctx.root,
...supportPluginAllowPaths,
...resolveWorkbenchPluginAllowPaths(ctx),
...controlsAllowPaths,
...browserRuntimePaths.allowPaths,
...browserRuntimePaths.mswAllowPaths,
...accessibilityRuntime ? [dirname(accessibilityRuntime.scannerId)] : [],
...process.env.HISTOIRE_DEV
? [
'../../packages/histoire-vendors',
]
: [],
],
},
watch: {
// Every run owns its optimizer cache, but older caches can remain
// beside it. Watch plugin sources while pruning all cache folders.
ignored: [`!**/node_modules/.histoire/**`, '**/vite.config.*', createOptimizerCacheIgnore(ctx),
// Offline reports must never reload the reviewing browser. Baseline
// approvals and saved cells refresh through their owned UI channel.
`${ctx.root}/.histoire/visual/**`, ...visual ? [`${ctx.root}/${visual.baselineDir}/**`] : []],
},
hmr: command === 'build' ? false : !isServer,
},
define: {
// We need to force this to be able to use `devtoolsRawSetupState`
'__VUE_PROD_DEVTOOLS__': 'true',
// Disable warnings
'process.env.NODE_ENV': JSON.stringify(isServer ? 'production' : process.env.NODE_ENV ?? 'development'),
...!isServer
? {
// Collect flag
'process.env.HST_COLLECT': 'false',
}
: {},
'__HST_COLLECT__': isServer,
},
cacheDir: getViteCacheDir(ctx, browserRuntime
? (isServer ? 'browser-server' : 'browser-client')
: (isServer ? 'server' : 'client')),
};
},
/**
* Vitest runs once and creates its servers with `server.watch: null`, but
* the dev watch options returned above re-enable chokidar. A run cancelled
* while warmup transforms are in flight then re-adds files to the closed
* watcher (chokidar reopens on `add`), and those live `fs.watch` handles
* keep the isolated test worker from exiting after teardown.
* @param config The resolved Vite config, mutated before servers read it.
*/
configResolved(config) {
if (browserRuntime)
config.server.watch = null;
},
options() {
this.meta.histoire = {
isCollecting: isServer,
};
},
handleHotUpdate(updateContext) {
// Revalidation writes this internal cache after a ready source is exposed;
// it is not a story dependency or a change to the rendered document.
if (visual && !isServer && !browserRuntime && updateContext.file !== getCollectionCacheFile(ctx.root))
retireVisualSource(updateContext.server);
const story = ctx.storyFiles.find(file => file.path === updateContext.file);
if (story) {
notifyStoryChange(ctx, story);
}
},
configureServer(server) {
// Catalog belongs to filesystem/explicit collection owners. Browser
// mounts and reconnects only read it; recollecting here retires ready
// runtimes on every visit and amplifies optimizer reloads into full scans.
server.middlewares.use(createEmbedMiddleware(server, ctx));
server.middlewares.use(createMcpPreviewHtmlMiddleware(server));
if (!isServer && !browserRuntime)
installUiHttpRouter(server);
server.middlewares.use(createSandboxHtmlMiddleware(server));
server.middlewares.use(createMswWorkerMiddleware(server, ctx.root));
// serve our index.html after vite history fallback
return () => {
server.middlewares.use(createAppHtmlMiddleware(server, ctx));
};
},
};
}