@storybook/builder-vite 7.0.0-beta.25 → 7.0.0-beta.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +808 -19
  2. package/dist/index.mjs +774 -19
  3. package/package.json +11 -11
package/dist/index.mjs CHANGED
@@ -1,12 +1,199 @@
1
- var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x+'" is not supported')});import*as fs2 from"fs-extra";import express from"express";import{dirname,join as join2,parse as parse2}from"path";import{normalizeStories}from"@storybook/core-common";async function transformIframeHtml(html,options){let{configType,features,presets,serverChannelUrl,title}=options,frameworkOptions=await presets.apply("frameworkOptions"),headHtmlSnippet=await presets.apply("previewHead"),bodyHtmlSnippet=await presets.apply("previewBody"),logLevel=await presets.apply("logLevel",void 0),docsOptions=await presets.apply("docs"),coreOptions=await presets.apply("core"),stories=normalizeStories(await options.presets.apply("stories",[],options),{configDir:options.configDir,workingDir:process.cwd()}).map(specifier=>({...specifier,importPathMatcher:specifier.importPathMatcher.source}));return html.replace("<!-- [TITLE HERE] -->",title||"Storybook").replace("[CONFIG_TYPE HERE]",configType||"").replace("[LOGLEVEL HERE]",logLevel||"").replace("'[FRAMEWORK_OPTIONS HERE]'",JSON.stringify(frameworkOptions)).replace("'[CHANNEL_OPTIONS HERE]'",JSON.stringify(coreOptions&&coreOptions.channelOptions?coreOptions.channelOptions:{})).replace("'[FEATURES HERE]'",JSON.stringify(features||{})).replace("'[STORIES HERE]'",JSON.stringify(stories||{})).replace("'[DOCS_OPTIONS HERE]'",JSON.stringify(docsOptions||{})).replace("'[SERVER_CHANNEL_URL HERE]'",JSON.stringify(serverChannelUrl)).replace("<!-- [HEAD HTML SNIPPET HERE] -->",headHtmlSnippet||"").replace("<!-- [BODY HTML SNIPPET HERE] -->",bodyHtmlSnippet||"")}import{createServer}from"vite";import*as path4 from"path";import{loadConfigFromFile,mergeConfig as mergeConfig2}from"vite";import externalGlobals from"rollup-plugin-external-globals";import{isPreservingSymlinks,getFrameworkName as getFrameworkName2}from"@storybook/core-common";import{globals}from"@storybook/preview/globals";import{parse}from"es-module-lexer";import MagicString from"magic-string";import{createFilter}from"vite";var include=[/\.stories\.([tj])sx?$/,/(stories|story).mdx$/],filter=createFilter(include),injectExportOrderPlugin={name:"storybook:inject-export-order-plugin",enforce:"post",async transform(code,id){if(!filter(id))return;let[,exports]=await parse(code);if(exports.includes("__namedExportsOrder"))return;let s=new MagicString(code),orderedExports=exports.filter(e=>e!=="default");return s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`),{code:s.toString(),map:s.generateMap({hires:!0,source:id})}}};import{createFilter as createFilter2}from"vite";var isStorybookMdx=id=>id.endsWith("stories.mdx")||id.endsWith("story.mdx");async function mdxPlugin(options){let filter2=createFilter2(/\.mdx?$/),docsOptions=(await options.presets.apply("addons",[])).find(a=>[a,a.name].includes("@storybook/addon-docs"))?.options??{};return{name:"storybook:mdx-plugin",enforce:"pre",async transform(src,id){if(!filter2(id))return;let{compile}=await import("@storybook/mdx2-csf"),mdxLoaderOptions=await options.presets.apply("mdxLoaderOptions",{mdxCompileOptions:{providerImportSource:"@storybook/addon-docs/mdx-react-shim"},jsxOptions:docsOptions.jsxOptions});return{code:String(await compile(src,{skipCsf:!isStorybookMdx(id),...mdxLoaderOptions})),map:null}}}}import{createFilter as createFilter3}from"vite";import MagicString2 from"magic-string";function stripStoryHMRBoundary(){let filter2=createFilter3(/\.stories\.([tj])sx?$/);return{name:"storybook:strip-hmr-boundary-plugin",enforce:"post",async transform(src,id){if(!filter2(id))return;let s=new MagicString2(src);return s.replace(/import\.meta\.hot\.accept\(\);/,""),{code:s.toString(),map:s.generateMap({hires:!0,source:id})}}}}import*as fs from"fs";import{mergeConfig}from"vite";import{getRendererName}from"@storybook/core-common";var virtualFileId="/virtual:/@storybook/builder-vite/vite-app.js",virtualStoriesFile="/virtual:/@storybook/builder-vite/storybook-stories.js",virtualPreviewFile="/virtual:/@storybook/builder-vite/preview-entry.js",virtualAddonSetupFile="/virtual:/@storybook/builder-vite/setup-addons.js";import{resolve}from"path";import slash from"slash";import path from"path";import{normalizePath}from"vite";function transformAbsPath(absPath){let splits=absPath.split(`node_modules${path.sep}`);return normalizePath(splits[splits.length-1])}function processPreviewAnnotation(path6){if(typeof path6=="object")return path6.bare;if(path6?.startsWith("./")||path6?.startsWith("../"))return slash(resolve(path6));if(!path6)throw new Error("Could not determine path for previewAnnotation");return path6.includes("node_modules")?transformAbsPath(path6):slash(path6)}async function generateIframeScriptCode(options){let{presets}=options,rendererName=await getRendererName(options),configEntries=[...await presets.apply("previewAnnotations",[],options)].filter(Boolean).map(processPreviewAnnotation),filesToImport=(files,name)=>files.map((el,i)=>`import ${name?`* as ${name}_${i} from `:""}'${el}'`).join(`
2
- `),importArray=(name,length)=>new Array(length).fill(0).map((_,i)=>`${name}_${i}`);return`
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/index.ts
10
+ import * as fs2 from "fs-extra";
11
+ import express from "express";
12
+ import { dirname, join as join2, parse as parse2 } from "path";
13
+
14
+ // src/transform-iframe-html.ts
15
+ import { normalizeStories } from "@storybook/core-common";
16
+ async function transformIframeHtml(html, options) {
17
+ const { configType, features, presets, serverChannelUrl, title } = options;
18
+ const frameworkOptions = await presets.apply("frameworkOptions");
19
+ const headHtmlSnippet = await presets.apply("previewHead");
20
+ const bodyHtmlSnippet = await presets.apply("previewBody");
21
+ const logLevel = await presets.apply("logLevel", void 0);
22
+ const docsOptions = await presets.apply("docs");
23
+ const coreOptions = await presets.apply("core");
24
+ const stories = normalizeStories(await options.presets.apply("stories", [], options), {
25
+ configDir: options.configDir,
26
+ workingDir: process.cwd()
27
+ }).map((specifier) => ({
28
+ ...specifier,
29
+ importPathMatcher: specifier.importPathMatcher.source
30
+ }));
31
+ return html.replace("<!-- [TITLE HERE] -->", title || "Storybook").replace("[CONFIG_TYPE HERE]", configType || "").replace("[LOGLEVEL HERE]", logLevel || "").replace(`'[FRAMEWORK_OPTIONS HERE]'`, JSON.stringify(frameworkOptions)).replace(
32
+ `'[CHANNEL_OPTIONS HERE]'`,
33
+ JSON.stringify(coreOptions && coreOptions.channelOptions ? coreOptions.channelOptions : {})
34
+ ).replace(`'[FEATURES HERE]'`, JSON.stringify(features || {})).replace(`'[STORIES HERE]'`, JSON.stringify(stories || {})).replace(`'[DOCS_OPTIONS HERE]'`, JSON.stringify(docsOptions || {})).replace(`'[SERVER_CHANNEL_URL HERE]'`, JSON.stringify(serverChannelUrl)).replace("<!-- [HEAD HTML SNIPPET HERE] -->", headHtmlSnippet || "").replace("<!-- [BODY HTML SNIPPET HERE] -->", bodyHtmlSnippet || "");
35
+ }
36
+
37
+ // src/vite-server.ts
38
+ import { createServer } from "vite";
39
+
40
+ // src/vite-config.ts
41
+ import * as path4 from "path";
42
+ import { loadConfigFromFile, mergeConfig as mergeConfig2 } from "vite";
43
+ import { viteExternalsPlugin } from "vite-plugin-externals";
44
+ import { isPreservingSymlinks, getFrameworkName as getFrameworkName2 } from "@storybook/core-common";
45
+ import { globals } from "@storybook/preview/globals";
46
+
47
+ // src/plugins/inject-export-order-plugin.ts
48
+ import { parse } from "es-module-lexer";
49
+ import MagicString from "magic-string";
50
+ import { createFilter } from "vite";
51
+ var include = [/\.stories\.([tj])sx?$/, /(stories|story).mdx$/];
52
+ var filter = createFilter(include);
53
+ var injectExportOrderPlugin = {
54
+ name: "storybook:inject-export-order-plugin",
55
+ // This should only run after the typescript has been transpiled
56
+ enforce: "post",
57
+ async transform(code, id) {
58
+ if (!filter(id))
59
+ return void 0;
60
+ const [, exports] = await parse(code);
61
+ if (exports.includes("__namedExportsOrder")) {
62
+ return void 0;
63
+ }
64
+ const s = new MagicString(code);
65
+ const orderedExports = exports.filter((e) => e !== "default");
66
+ s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`);
67
+ return {
68
+ code: s.toString(),
69
+ map: s.generateMap({ hires: true, source: id })
70
+ };
71
+ }
72
+ };
73
+
74
+ // src/plugins/mdx-plugin.ts
75
+ import { createFilter as createFilter2 } from "vite";
76
+ var isStorybookMdx = (id) => id.endsWith("stories.mdx") || id.endsWith("story.mdx");
77
+ async function mdxPlugin(options) {
78
+ const include2 = /\.mdx?$/;
79
+ const filter2 = createFilter2(include2);
80
+ const addons = await options.presets.apply("addons", []);
81
+ const docsOptions = (
82
+ // @ts-expect-error - not sure what type to use here
83
+ addons.find((a) => [a, a.name].includes("@storybook/addon-docs"))?.options ?? {}
84
+ );
85
+ return {
86
+ name: "storybook:mdx-plugin",
87
+ enforce: "pre",
88
+ async transform(src, id) {
89
+ if (!filter2(id))
90
+ return void 0;
91
+ const { compile } = await import("@storybook/mdx2-csf");
92
+ const mdxLoaderOptions = await options.presets.apply("mdxLoaderOptions", {
93
+ mdxCompileOptions: {
94
+ providerImportSource: "@storybook/addon-docs/mdx-react-shim"
95
+ },
96
+ jsxOptions: docsOptions.jsxOptions
97
+ });
98
+ const code = String(
99
+ await compile(src, {
100
+ skipCsf: !isStorybookMdx(id),
101
+ ...mdxLoaderOptions
102
+ })
103
+ );
104
+ return {
105
+ code,
106
+ map: null
107
+ // TODO: update mdx2-csf to return the map
108
+ };
109
+ }
110
+ };
111
+ }
112
+
113
+ // src/plugins/strip-story-hmr-boundaries.ts
114
+ import { createFilter as createFilter3 } from "vite";
115
+ import MagicString2 from "magic-string";
116
+ function stripStoryHMRBoundary() {
117
+ const filter2 = createFilter3(/\.stories\.([tj])sx?$/);
118
+ return {
119
+ name: "storybook:strip-hmr-boundary-plugin",
120
+ enforce: "post",
121
+ async transform(src, id) {
122
+ if (!filter2(id))
123
+ return void 0;
124
+ const s = new MagicString2(src);
125
+ s.replace(/import\.meta\.hot\.accept\(\);/, "");
126
+ return {
127
+ code: s.toString(),
128
+ map: s.generateMap({ hires: true, source: id })
129
+ };
130
+ }
131
+ };
132
+ }
133
+
134
+ // src/plugins/code-generator-plugin.ts
135
+ import * as fs from "fs";
136
+ import { mergeConfig } from "vite";
137
+
138
+ // src/codegen-iframe-script.ts
139
+ import { getRendererName } from "@storybook/core-common";
140
+
141
+ // src/virtual-file-names.ts
142
+ var virtualFileId = "/virtual:/@storybook/builder-vite/vite-app.js";
143
+ var virtualStoriesFile = "/virtual:/@storybook/builder-vite/storybook-stories.js";
144
+ var virtualPreviewFile = "/virtual:/@storybook/builder-vite/preview-entry.js";
145
+ var virtualAddonSetupFile = "/virtual:/@storybook/builder-vite/setup-addons.js";
146
+
147
+ // src/utils/process-preview-annotation.ts
148
+ import { resolve } from "path";
149
+ import slash from "slash";
150
+
151
+ // src/utils/transform-abs-path.ts
152
+ import path from "path";
153
+ import { normalizePath } from "vite";
154
+ function transformAbsPath(absPath) {
155
+ const splits = absPath.split(`node_modules${path.sep}`);
156
+ const module = normalizePath(splits[splits.length - 1]);
157
+ return module;
158
+ }
159
+
160
+ // src/utils/process-preview-annotation.ts
161
+ function processPreviewAnnotation(path6) {
162
+ if (typeof path6 === "object") {
163
+ return path6.bare;
164
+ }
165
+ if (path6?.startsWith("./") || path6?.startsWith("../")) {
166
+ return slash(resolve(path6));
167
+ }
168
+ if (!path6) {
169
+ throw new Error("Could not determine path for previewAnnotation");
170
+ }
171
+ if (path6.includes("node_modules")) {
172
+ return transformAbsPath(path6);
173
+ }
174
+ return slash(path6);
175
+ }
176
+
177
+ // src/codegen-iframe-script.ts
178
+ async function generateIframeScriptCode(options) {
179
+ const { presets } = options;
180
+ const rendererName = await getRendererName(options);
181
+ const previewAnnotations = await presets.apply(
182
+ "previewAnnotations",
183
+ [],
184
+ options
185
+ );
186
+ const configEntries = [...previewAnnotations].filter(Boolean).map(processPreviewAnnotation);
187
+ const filesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ""}'${el}'`).join("\n");
188
+ const importArray = (name, length) => new Array(length).fill(0).map((_, i) => `${name}_${i}`);
189
+ const code = `
3
190
  // Ensure that the client API is initialized by the framework before any other iframe code
4
191
  // is loaded. That way our client-apis can assume the existence of the API+store
5
192
  import { configure } from '${rendererName}';
6
193
 
7
194
  import { logger } from '@storybook/client-logger';
8
195
  import * as previewApi from "@storybook/preview-api";
9
- ${filesToImport(configEntries,"config")}
196
+ ${filesToImport(configEntries, "config")}
10
197
 
11
198
  import * as preview from '${virtualPreviewFile}';
12
199
  import { configStories } from '${virtualStoriesFile}';
@@ -23,7 +210,7 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
23
210
  setGlobalRender,
24
211
  } = previewApi;
25
212
 
26
- const configs = [${importArray("config",configEntries.length).concat("preview.default").join(",")}].filter(Boolean)
213
+ const configs = [${importArray("config", configEntries.length).concat("preview.default").join(",")}].filter(Boolean)
27
214
 
28
215
  configs.forEach(config => {
29
216
  Object.keys(config).forEach((key) => {
@@ -83,30 +270,53 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
83
270
  */
84
271
 
85
272
  configStories(configure);
86
- `.trim()}import{loadPreviewOrConfigFile,getFrameworkName}from"@storybook/core-common";async function generateModernIframeScriptCode(options){let{presets,configDir}=options,frameworkName=await getFrameworkName(options),previewOrConfigFile=loadPreviewOrConfigFile({configDir}),relativePreviewAnnotations=[...await presets.apply("previewAnnotations",[],options),previewOrConfigFile].filter(Boolean).map(processPreviewAnnotation),generateHMRHandler=frameworkName2=>frameworkName2==="@storybook/web-components-vite"?`
273
+ `.trim();
274
+ return code;
275
+ }
276
+
277
+ // src/codegen-modern-iframe-script.ts
278
+ import { loadPreviewOrConfigFile, getFrameworkName } from "@storybook/core-common";
279
+ async function generateModernIframeScriptCode(options) {
280
+ const { presets, configDir } = options;
281
+ const frameworkName = await getFrameworkName(options);
282
+ const previewOrConfigFile = loadPreviewOrConfigFile({ configDir });
283
+ const previewAnnotations = await presets.apply(
284
+ "previewAnnotations",
285
+ [],
286
+ options
287
+ );
288
+ const relativePreviewAnnotations = [...previewAnnotations, previewOrConfigFile].filter(Boolean).map(processPreviewAnnotation);
289
+ const generateHMRHandler = (frameworkName2) => {
290
+ if (frameworkName2 === "@storybook/web-components-vite") {
291
+ return `
87
292
  if (import.meta.hot) {
88
293
  import.meta.hot.decline();
89
- }`.trim():`
294
+ }`.trim();
295
+ }
296
+ return `
90
297
  if (import.meta.hot) {
91
298
  import.meta.hot.accept('${virtualStoriesFile}', (newModule) => {
92
299
  // importFn has changed so we need to patch the new one in
93
300
  window.__STORYBOOK_PREVIEW__.onStoriesChanged({ importFn: newModule.importFn });
94
301
  });
95
302
 
96
- import.meta.hot.accept(${JSON.stringify(relativePreviewAnnotations)}, ([...newConfigEntries]) => {
303
+ import.meta.hot.accept(${JSON.stringify(
304
+ relativePreviewAnnotations
305
+ )}, ([...newConfigEntries]) => {
97
306
  const newGetProjectAnnotations = () => composeConfigs(newConfigEntries);
98
307
 
99
308
  // getProjectAnnotations has changed so we need to patch the new one in
100
309
  window.__STORYBOOK_PREVIEW__.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
101
310
  });
102
- }`.trim();return`
311
+ }`.trim();
312
+ };
313
+ const code = `
103
314
  import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
104
315
  import '${virtualAddonSetupFile}';
105
316
  import { importFn } from '${virtualStoriesFile}';
106
317
 
107
318
  const getProjectAnnotations = async () => {
108
- const configs = await Promise.all([${relativePreviewAnnotations.map(previewAnnotation=>`import('${previewAnnotation}')`).join(`,
109
- `)}])
319
+ const configs = await Promise.all([${relativePreviewAnnotations.map((previewAnnotation) => `import('${previewAnnotation}')`).join(",\n")}])
110
320
  return composeConfigs(configs);
111
321
  }
112
322
 
@@ -118,18 +328,75 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
118
328
  window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
119
329
 
120
330
  ${generateHMRHandler(frameworkName)};
121
- `.trim()}import*as path3 from"path";import{normalizePath as normalizePath2}from"vite";import{logger}from"@storybook/node-logger";import*as path2 from"path";import{promise as glob}from"glob-promise";import{normalizeStories as normalizeStories2}from"@storybook/core-common";async function listStories(options){return(await Promise.all(normalizeStories2(await options.presets.apply("stories",[],options),{configDir:options.configDir,workingDir:options.configDir}).map(({directory,files})=>{let pattern=path2.join(directory,files);return glob(path2.isAbsolute(pattern)?pattern:path2.join(options.configDir,pattern),{follow:!0})}))).reduce((carry,stories)=>carry.concat(stories),[])}function toImportPath(relativePath){return relativePath.startsWith("../")?relativePath:`./${relativePath}`}async function toImportFn(stories){return`
331
+ `.trim();
332
+ return code;
333
+ }
334
+
335
+ // src/codegen-importfn-script.ts
336
+ import * as path3 from "path";
337
+ import { normalizePath as normalizePath2 } from "vite";
338
+ import { logger } from "@storybook/node-logger";
339
+
340
+ // src/list-stories.ts
341
+ import * as path2 from "path";
342
+ import { promise as glob } from "glob-promise";
343
+ import { normalizeStories as normalizeStories2 } from "@storybook/core-common";
344
+ async function listStories(options) {
345
+ return (await Promise.all(
346
+ normalizeStories2(await options.presets.apply("stories", [], options), {
347
+ configDir: options.configDir,
348
+ workingDir: options.configDir
349
+ }).map(({ directory, files }) => {
350
+ const pattern = path2.join(directory, files);
351
+ return glob(path2.isAbsolute(pattern) ? pattern : path2.join(options.configDir, pattern), {
352
+ follow: true
353
+ });
354
+ })
355
+ )).reduce((carry, stories) => carry.concat(stories), []);
356
+ }
357
+
358
+ // src/codegen-importfn-script.ts
359
+ function toImportPath(relativePath) {
360
+ return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
361
+ }
362
+ async function toImportFn(stories) {
363
+ const objectEntries = stories.map((file) => {
364
+ const ext = path3.extname(file);
365
+ const relativePath = normalizePath2(path3.relative(process.cwd(), file));
366
+ if (![".js", ".jsx", ".ts", ".tsx", ".mdx", ".svelte"].includes(ext)) {
367
+ logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`);
368
+ }
369
+ return ` '${toImportPath(relativePath)}': async () => import('/@fs/${file}')`;
370
+ });
371
+ return `
122
372
  const importers = {
123
- ${stories.map(file=>{let ext=path3.extname(file),relativePath=normalizePath2(path3.relative(process.cwd(),file));return[".js",".jsx",".ts",".tsx",".mdx",".svelte"].includes(ext)||logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`),` '${toImportPath(relativePath)}': async () => import('/@fs/${file}')`}).join(`,
124
- `)}
373
+ ${objectEntries.join(",\n")}
125
374
  };
126
375
 
127
376
  export async function importFn(path) {
128
377
  return importers[path]();
129
378
  }
130
- `}async function generateImportFnScriptCode(options){let stories=await listStories(options);return(await toImportFn(stories)).trim()}import{loadPreviewOrConfigFile as loadPreviewOrConfigFile2}from"@storybook/core-common";import slash2 from"slash";import{normalizePath as normalizePath3}from"vite";var absoluteFilesToImport=(files,name)=>files.map((el,i)=>`import ${name?`* as ${name}_${i} from `:""}'/@fs/${normalizePath3(el)}'`).join(`
131
- `);async function generateVirtualStoryEntryCode(options){let storyEntries=await listStories(options),resolveMap=storyEntries.reduce((prev,entry)=>({...prev,[entry]:entry.replace(slash2(process.cwd()),".")}),{}),modules=storyEntries.map((entry,i)=>`${JSON.stringify(entry)}: story_${i}`).join(",");return`
132
- ${absoluteFilesToImport(storyEntries,"story")}
379
+ `;
380
+ }
381
+ async function generateImportFnScriptCode(options) {
382
+ const stories = await listStories(options);
383
+ return (await toImportFn(stories)).trim();
384
+ }
385
+
386
+ // src/codegen-entries.ts
387
+ import { loadPreviewOrConfigFile as loadPreviewOrConfigFile2 } from "@storybook/core-common";
388
+ import slash2 from "slash";
389
+ import { normalizePath as normalizePath3 } from "vite";
390
+ var absoluteFilesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ""}'/@fs/${normalizePath3(el)}'`).join("\n");
391
+ async function generateVirtualStoryEntryCode(options) {
392
+ const storyEntries = await listStories(options);
393
+ const resolveMap = storyEntries.reduce(
394
+ (prev, entry) => ({ ...prev, [entry]: entry.replace(slash2(process.cwd()), ".") }),
395
+ {}
396
+ );
397
+ const modules = storyEntries.map((entry, i) => `${JSON.stringify(entry)}: story_${i}`).join(",");
398
+ return `
399
+ ${absoluteFilesToImport(storyEntries, "story")}
133
400
 
134
401
  function loadable(key) {
135
402
  return {${modules}}[key];
@@ -143,8 +410,19 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
143
410
  export function configStories(configure) {
144
411
  configure(loadable, { hot: import.meta.hot }, false);
145
412
  }
146
- `.trim()}async function generatePreviewEntryCode({configDir}){let previewFile=loadPreviewOrConfigFile2({configDir});return previewFile?`import * as preview from '${slash2(previewFile)}';
147
- export default preview;`:""}async function generateAddonSetupCode(){return`
413
+ `.trim();
414
+ }
415
+ async function generatePreviewEntryCode({ configDir }) {
416
+ const previewFile = loadPreviewOrConfigFile2({ configDir });
417
+ if (!previewFile)
418
+ return "";
419
+ return `import * as preview from '${slash2(previewFile)}';
420
+ export default preview;`;
421
+ }
422
+
423
+ // src/codegen-set-addon-channel.ts
424
+ async function generateAddonSetupCode() {
425
+ return `
148
426
  import { createChannel as createPostMessageChannel } from '@storybook/channel-postmessage';
149
427
  import { createChannel as createWebSocketChannel } from '@storybook/channel-websocket';
150
428
  import { addons } from '@storybook/preview-api';
@@ -159,4 +437,481 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
159
437
  addons.setServerChannel(serverChannel);
160
438
  window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
161
439
  }
162
- `.trim()}function codeGeneratorPlugin(options){let iframePath=__require.resolve("@storybook/builder-vite/input/iframe.html"),iframeId;return{name:"storybook:code-generator-plugin",enforce:"pre",configureServer(server2){server2.watcher.on("change",()=>{let appModule=server2.moduleGraph.getModuleById(virtualFileId);appModule&&server2.moduleGraph.invalidateModule(appModule);let storiesModule=server2.moduleGraph.getModuleById(virtualStoriesFile);storiesModule&&server2.moduleGraph.invalidateModule(storiesModule)}),server2.watcher.on("add",path6=>{(/\.stories\.([tj])sx?$/.test(path6)||/\.(story|stories).mdx$/.test(path6))&&server2.watcher.emit("change",virtualStoriesFile)})},config(config,{command}){command==="build"&&(config.build||(config.build={}),config.build.rollupOptions={...config.build.rollupOptions,input:iframePath});try{__require.resolve("react-dom/client",{paths:[config.root||process.cwd()]})}catch(e){isNodeError(e)&&e.code==="MODULE_NOT_FOUND"&&(config.resolve=mergeConfig(config.resolve??{},{alias:{"react-dom/client":__require.resolve("@storybook/builder-vite/input/react-dom-client-placeholder.js")}}))}},configResolved(config){iframeId=`${config.root}/iframe.html`},resolveId(source){if(source===virtualFileId)return virtualFileId;if(source===iframePath)return iframeId;if(source===virtualStoriesFile)return virtualStoriesFile;if(source===virtualPreviewFile)return virtualPreviewFile;if(source===virtualAddonSetupFile)return virtualAddonSetupFile},async load(id){let storyStoreV7=options.features?.storyStoreV7;if(id===virtualStoriesFile)return storyStoreV7?generateImportFnScriptCode(options):generateVirtualStoryEntryCode(options);if(id===virtualAddonSetupFile)return generateAddonSetupCode();if(id===virtualPreviewFile&&!storyStoreV7)return generatePreviewEntryCode(options);if(id===virtualFileId)return storyStoreV7?generateModernIframeScriptCode(options):generateIframeScriptCode(options);if(id===iframeId)return fs.readFileSync(__require.resolve("@storybook/builder-vite/input/iframe.html"),"utf-8")},async transformIndexHtml(html,ctx){if(ctx.path==="/iframe.html")return transformIframeHtml(html,options)}}}var isNodeError=error=>error instanceof Error;import{vite}from"@storybook/csf-plugin";async function csfPlugin(config){let{presets}=config,docsOptions=(await presets.apply("addons",[])).find(a=>[a,a.name].includes("@storybook/addon-docs"))?.options??{};return vite(docsOptions?.csfPluginOptions)}var configEnvServe={mode:"development",command:"serve",ssrBuild:!1},configEnvBuild={mode:"production",command:"build",ssrBuild:!1};async function commonConfig(options,_type){let configEnv=_type==="development"?configEnvServe:configEnvBuild,{config:{build:buildProperty=void 0,...userConfig}={}}=await loadConfigFromFile(configEnv)??{},sbConfig={configFile:!1,cacheDir:"node_modules/.cache/.vite-storybook",root:path4.resolve(options.configDir,".."),base:"./",plugins:await pluginConfig(options),resolve:{preserveSymlinks:isPreservingSymlinks(),alias:{assert:__require.resolve("browser-assert")}},envPrefix:userConfig.envPrefix?"STORYBOOK_":["VITE_","STORYBOOK_"]};return mergeConfig2(userConfig,sbConfig)}async function pluginConfig(options){let frameworkName=await getFrameworkName2(options),plugins=[codeGeneratorPlugin(options),await csfPlugin(options),await mdxPlugin(options),injectExportOrderPlugin,stripStoryHMRBoundary(),{name:"storybook:allow-storybook-dir",enforce:"post",config(config){config?.server?.fs?.allow&&config.server.fs.allow.push(".storybook")}},externalGlobals(globals)];if(frameworkName==="@storybook/glimmerx-vite"){let plugin=__require("vite-plugin-glimmerx/index.cjs");plugins.push(plugin.default())}return plugins}import*as path5 from"path";import{normalizePath as normalizePath4,resolveConfig}from"vite";var INCLUDE_CANDIDATES=["@base2/pretty-print-object","@emotion/core","@emotion/is-prop-valid","@emotion/styled","@mdx-js/react","@storybook/addon-docs > acorn-jsx","@storybook/addon-docs","@storybook/channel-postmessage","@storybook/channel-websocket","@storybook/client-api","@storybook/client-logger","@storybook/core/client","@storybook/global","@storybook/preview-api","@storybook/preview-web","@storybook/react > acorn-jsx","@storybook/react","@storybook/svelte","@storybook/types","@storybook/vue3","acorn-jsx","acorn-walk","acorn","airbnb-js-shims","ansi-to-html","axe-core","color-convert","deep-object-diff","doctrine","emotion-theming","escodegen","estraverse","fast-deep-equal","html-tags","isobject","jest-mock","loader-utils","lodash/cloneDeep","lodash/isFunction","lodash/isPlainObject","lodash/isString","lodash/mapKeys","lodash/mapValues","lodash/pick","lodash/pickBy","lodash/startCase","lodash/throttle","lodash/uniq","markdown-to-jsx","memoizerific","overlayscrollbars","polished","prettier/parser-babel","prettier/parser-flow","prettier/parser-typescript","prop-types","qs","react-dom","react-dom/client","react-fast-compare","react-is","react-textarea-autosize","react","react/jsx-runtime","refractor/core","refractor/lang/bash.js","refractor/lang/css.js","refractor/lang/graphql.js","refractor/lang/js-extras.js","refractor/lang/json.js","refractor/lang/jsx.js","refractor/lang/markdown.js","refractor/lang/markup.js","refractor/lang/tsx.js","refractor/lang/typescript.js","refractor/lang/yaml.js","regenerator-runtime/runtime.js","slash","store2","synchronous-promise","telejson","ts-dedent","unfetch","util-deprecate","uuid-browser/v4","vue","warning"],asyncFilter=async(arr,predicate)=>Promise.all(arr.map(predicate)).then(results=>arr.filter((_v,index)=>results[index]));async function getOptimizeDeps(config,options){let{root=process.cwd()}=config,stories=(await listStories(options)).map(storyPath=>normalizePath4(path5.relative(root,storyPath))),resolve3=(await resolveConfig(config,"serve","development")).createResolver({asSrc:!1}),include2=await asyncFilter(INCLUDE_CANDIDATES,async id=>Boolean(await resolve3(id)));return{...config.optimizeDeps,entries:stories,include:[...include2,...config.optimizeDeps?.include||[]]}}import{stringifyEnvs}from"@storybook/core-common";var allowedEnvVariables=["STORYBOOK","BASE_URL","MODE","DEV","PROD","SSR"];function stringifyProcessEnvs(raw,envPrefix){let updatedRaw={},envs=Object.entries(raw).reduce((acc,[key,value])=>((allowedEnvVariables.includes(key)||Array.isArray(envPrefix)&&envPrefix.find(prefix=>key.startsWith(prefix))||typeof envPrefix=="string"&&key.startsWith(envPrefix))&&(acc[`import.meta.env.${key}`]=JSON.stringify(value),updatedRaw[key]=value),acc),{});return envs["import.meta.env"]=JSON.stringify(stringifyEnvs(updatedRaw)),envs}async function sanitizeEnvVars(options,config){let{presets}=options,envsRaw=await presets.apply("env"),{define}=config;if(Object.keys(envsRaw).length){let envs=stringifyProcessEnvs(envsRaw,config.envPrefix);define={...define,...envs}}return{...config,define}}async function createViteServer(options,devServer){let{presets}=options,commonCfg=await commonConfig(options,"development"),config={...commonCfg,server:{middlewareMode:!0,hmr:{port:options.port,server:devServer},fs:{strict:!0}},appType:"custom",optimizeDeps:await getOptimizeDeps(commonCfg,options)},finalConfig=await presets.apply("viteFinal",config,options);return createServer(await sanitizeEnvVars(options,finalConfig))}import{build as viteBuild,mergeConfig as mergeConfig3}from"vite";async function build(options){let{presets}=options,config=await commonConfig(options,"build");config.build=mergeConfig3(config,{build:{outDir:options.outputDir,emptyOutDir:!1,sourcemap:!0,rollupOptions:{external:["./sb-preview/runtime.mjs"]}}}).build;let finalConfig=await presets.apply("viteFinal",config,options);await viteBuild(await sanitizeEnvVars(options,finalConfig))}var withoutVitePlugins=async(plugins=[],namesToRemove)=>{let result=[],resolvedPlugins=await Promise.all(plugins);for(let plugin of resolvedPlugins)Array.isArray(plugin)&&result.push(await withoutVitePlugins(plugin,namesToRemove)),plugin&&"name"in plugin&&!namesToRemove.includes(plugin.name)&&result.push(plugin);return result};function checkName(plugin,names){return plugin!==null&&typeof plugin=="object"&&"name"in plugin&&names.includes(plugin.name)}async function hasVitePlugins(plugins,names){let resolvedPlugins=await Promise.all(plugins);for(let plugin of resolvedPlugins)if(Array.isArray(plugin)&&Boolean(await hasVitePlugins(plugin,names))||checkName(plugin,names))return!0;return!1}function iframeMiddleware(options,server2){return async(req,res,next)=>{if(!req.url.match(/^\/iframe\.html($|\?)/)){next();return}if(req.query["html-proxy"]!==void 0){next();return}let indexHtml=await fs2.readFile(__require.resolve("@storybook/builder-vite/input/iframe.html"),"utf-8"),generated=await transformIframeHtml(indexHtml,options),transformed=await server2.transformIndexHtml("/iframe.html",generated);res.setHeader("Content-Type","text/html"),res.status(200).send(transformed)}}var server;async function bail(){return server?.close()}var start=async({startTime,options,router,server:devServer})=>{server=await createViteServer(options,devServer);let previewResolvedDir=dirname(__require.resolve("@storybook/preview/package.json")),previewDirOrigin=join2(previewResolvedDir,"dist");return router.use("/sb-preview",express.static(previewDirOrigin,{immutable:!0,maxAge:"5m"})),router.use(iframeMiddleware(options,server)),router.use(server.middlewares),{bail,stats:{toJson:()=>null},totalTime:process.hrtime(startTime)}},build2=async({options})=>{let viteCompilation=build(options),previewResolvedDir=dirname(__require.resolve("@storybook/preview/package.json")),previewDirOrigin=join2(previewResolvedDir,"dist"),previewDirTarget=join2(options.outputDir||"","sb-preview"),previewFiles=fs2.copy(previewDirOrigin,previewDirTarget,{filter:src=>{let{ext}=parse2(src);return ext?ext===".mjs":!0}}),[out]=await Promise.all([viteCompilation,previewFiles]);return out};export{bail,build2 as build,hasVitePlugins,start,withoutVitePlugins};
440
+ `.trim();
441
+ }
442
+
443
+ // src/plugins/code-generator-plugin.ts
444
+ function codeGeneratorPlugin(options) {
445
+ const iframePath = __require.resolve("@storybook/builder-vite/input/iframe.html");
446
+ let iframeId;
447
+ return {
448
+ name: "storybook:code-generator-plugin",
449
+ enforce: "pre",
450
+ configureServer(server2) {
451
+ server2.watcher.on("change", () => {
452
+ const appModule = server2.moduleGraph.getModuleById(virtualFileId);
453
+ if (appModule) {
454
+ server2.moduleGraph.invalidateModule(appModule);
455
+ }
456
+ const storiesModule = server2.moduleGraph.getModuleById(virtualStoriesFile);
457
+ if (storiesModule) {
458
+ server2.moduleGraph.invalidateModule(storiesModule);
459
+ }
460
+ });
461
+ server2.watcher.on("add", (path6) => {
462
+ if (/\.stories\.([tj])sx?$/.test(path6) || /\.(story|stories).mdx$/.test(path6)) {
463
+ server2.watcher.emit("change", virtualStoriesFile);
464
+ }
465
+ });
466
+ },
467
+ config(config, { command }) {
468
+ if (command === "build") {
469
+ if (!config.build) {
470
+ config.build = {};
471
+ }
472
+ config.build.rollupOptions = {
473
+ ...config.build.rollupOptions,
474
+ input: iframePath
475
+ };
476
+ }
477
+ try {
478
+ __require.resolve("react-dom/client", { paths: [config.root || process.cwd()] });
479
+ } catch (e) {
480
+ if (isNodeError(e) && e.code === "MODULE_NOT_FOUND") {
481
+ config.resolve = mergeConfig(config.resolve ?? {}, {
482
+ alias: {
483
+ "react-dom/client": __require.resolve(
484
+ "@storybook/builder-vite/input/react-dom-client-placeholder.js"
485
+ )
486
+ }
487
+ });
488
+ }
489
+ }
490
+ },
491
+ configResolved(config) {
492
+ iframeId = `${config.root}/iframe.html`;
493
+ },
494
+ resolveId(source) {
495
+ if (source === virtualFileId) {
496
+ return virtualFileId;
497
+ }
498
+ if (source === iframePath) {
499
+ return iframeId;
500
+ }
501
+ if (source === virtualStoriesFile) {
502
+ return virtualStoriesFile;
503
+ }
504
+ if (source === virtualPreviewFile) {
505
+ return virtualPreviewFile;
506
+ }
507
+ if (source === virtualAddonSetupFile) {
508
+ return virtualAddonSetupFile;
509
+ }
510
+ return void 0;
511
+ },
512
+ async load(id) {
513
+ const storyStoreV7 = options.features?.storyStoreV7;
514
+ if (id === virtualStoriesFile) {
515
+ if (storyStoreV7) {
516
+ return generateImportFnScriptCode(options);
517
+ }
518
+ return generateVirtualStoryEntryCode(options);
519
+ }
520
+ if (id === virtualAddonSetupFile) {
521
+ return generateAddonSetupCode();
522
+ }
523
+ if (id === virtualPreviewFile && !storyStoreV7) {
524
+ return generatePreviewEntryCode(options);
525
+ }
526
+ if (id === virtualFileId) {
527
+ if (storyStoreV7) {
528
+ return generateModernIframeScriptCode(options);
529
+ }
530
+ return generateIframeScriptCode(options);
531
+ }
532
+ if (id === iframeId) {
533
+ return fs.readFileSync(
534
+ __require.resolve("@storybook/builder-vite/input/iframe.html"),
535
+ "utf-8"
536
+ );
537
+ }
538
+ return void 0;
539
+ },
540
+ async transformIndexHtml(html, ctx) {
541
+ if (ctx.path !== "/iframe.html") {
542
+ return void 0;
543
+ }
544
+ return transformIframeHtml(html, options);
545
+ }
546
+ };
547
+ }
548
+ var isNodeError = (error) => error instanceof Error;
549
+
550
+ // src/plugins/csf-plugin.ts
551
+ import { vite } from "@storybook/csf-plugin";
552
+ async function csfPlugin(config) {
553
+ const { presets } = config;
554
+ const addons = await presets.apply("addons", []);
555
+ const docsOptions = (
556
+ // @ts-expect-error - not sure what type to use here
557
+ addons.find((a) => [a, a.name].includes("@storybook/addon-docs"))?.options ?? {}
558
+ );
559
+ return vite(docsOptions?.csfPluginOptions);
560
+ }
561
+
562
+ // src/vite-config.ts
563
+ var configEnvServe = {
564
+ mode: "development",
565
+ command: "serve",
566
+ ssrBuild: false
567
+ };
568
+ var configEnvBuild = {
569
+ mode: "production",
570
+ command: "build",
571
+ ssrBuild: false
572
+ };
573
+ async function commonConfig(options, _type) {
574
+ const configEnv = _type === "development" ? configEnvServe : configEnvBuild;
575
+ const { config: { build: buildProperty = void 0, ...userConfig } = {} } = await loadConfigFromFile(configEnv) ?? {};
576
+ const sbConfig = {
577
+ configFile: false,
578
+ cacheDir: "node_modules/.cache/.vite-storybook",
579
+ root: path4.resolve(options.configDir, ".."),
580
+ // Allow storybook deployed as subfolder. See https://github.com/storybookjs/builder-vite/issues/238
581
+ base: "./",
582
+ plugins: await pluginConfig(options),
583
+ resolve: {
584
+ preserveSymlinks: isPreservingSymlinks(),
585
+ alias: {
586
+ assert: __require.resolve("browser-assert")
587
+ }
588
+ },
589
+ // If an envPrefix is specified in the vite config, add STORYBOOK_ to it,
590
+ // otherwise, add VITE_ and STORYBOOK_ so that vite doesn't lose its default.
591
+ envPrefix: userConfig.envPrefix ? "STORYBOOK_" : ["VITE_", "STORYBOOK_"]
592
+ };
593
+ const config = mergeConfig2(userConfig, sbConfig);
594
+ return config;
595
+ }
596
+ async function pluginConfig(options) {
597
+ const frameworkName = await getFrameworkName2(options);
598
+ const plugins = [
599
+ codeGeneratorPlugin(options),
600
+ await csfPlugin(options),
601
+ await mdxPlugin(options),
602
+ injectExportOrderPlugin,
603
+ stripStoryHMRBoundary(),
604
+ {
605
+ name: "storybook:allow-storybook-dir",
606
+ enforce: "post",
607
+ config(config) {
608
+ if (config?.server?.fs?.allow) {
609
+ config.server.fs.allow.push(".storybook");
610
+ }
611
+ }
612
+ },
613
+ viteExternalsPlugin(globals, { useWindow: false })
614
+ ];
615
+ if (frameworkName === "@storybook/glimmerx-vite") {
616
+ const plugin = __require("vite-plugin-glimmerx/index.cjs");
617
+ plugins.push(plugin.default());
618
+ }
619
+ return plugins;
620
+ }
621
+
622
+ // src/optimizeDeps.ts
623
+ import * as path5 from "path";
624
+ import { normalizePath as normalizePath4, resolveConfig } from "vite";
625
+ var INCLUDE_CANDIDATES = [
626
+ "@base2/pretty-print-object",
627
+ "@emotion/core",
628
+ "@emotion/is-prop-valid",
629
+ "@emotion/styled",
630
+ "@mdx-js/react",
631
+ "@storybook/addon-docs > acorn-jsx",
632
+ "@storybook/addon-docs",
633
+ "@storybook/channel-postmessage",
634
+ "@storybook/channel-websocket",
635
+ "@storybook/client-api",
636
+ "@storybook/client-logger",
637
+ "@storybook/core/client",
638
+ "@storybook/global",
639
+ "@storybook/preview-api",
640
+ "@storybook/preview-web",
641
+ "@storybook/react > acorn-jsx",
642
+ "@storybook/react",
643
+ "@storybook/svelte",
644
+ "@storybook/types",
645
+ "@storybook/vue3",
646
+ "acorn-jsx",
647
+ "acorn-walk",
648
+ "acorn",
649
+ "airbnb-js-shims",
650
+ "ansi-to-html",
651
+ "axe-core",
652
+ "color-convert",
653
+ "deep-object-diff",
654
+ "doctrine",
655
+ "emotion-theming",
656
+ "escodegen",
657
+ "estraverse",
658
+ "fast-deep-equal",
659
+ "html-tags",
660
+ "isobject",
661
+ "jest-mock",
662
+ "loader-utils",
663
+ "lodash/cloneDeep",
664
+ "lodash/isFunction",
665
+ "lodash/isPlainObject",
666
+ "lodash/isString",
667
+ "lodash/mapKeys",
668
+ "lodash/mapValues",
669
+ "lodash/pick",
670
+ "lodash/pickBy",
671
+ "lodash/startCase",
672
+ "lodash/throttle",
673
+ "lodash/uniq",
674
+ "markdown-to-jsx",
675
+ "memoizerific",
676
+ "overlayscrollbars",
677
+ "polished",
678
+ "prettier/parser-babel",
679
+ "prettier/parser-flow",
680
+ "prettier/parser-typescript",
681
+ "prop-types",
682
+ "qs",
683
+ "react-dom",
684
+ "react-dom/client",
685
+ "react-fast-compare",
686
+ "react-is",
687
+ "react-textarea-autosize",
688
+ "react",
689
+ "react/jsx-runtime",
690
+ "refractor/core",
691
+ "refractor/lang/bash.js",
692
+ "refractor/lang/css.js",
693
+ "refractor/lang/graphql.js",
694
+ "refractor/lang/js-extras.js",
695
+ "refractor/lang/json.js",
696
+ "refractor/lang/jsx.js",
697
+ "refractor/lang/markdown.js",
698
+ "refractor/lang/markup.js",
699
+ "refractor/lang/tsx.js",
700
+ "refractor/lang/typescript.js",
701
+ "refractor/lang/yaml.js",
702
+ "regenerator-runtime/runtime.js",
703
+ "slash",
704
+ "store2",
705
+ "synchronous-promise",
706
+ "telejson",
707
+ "ts-dedent",
708
+ "unfetch",
709
+ "util-deprecate",
710
+ "uuid-browser/v4",
711
+ "vue",
712
+ "warning"
713
+ ];
714
+ var asyncFilter = async (arr, predicate) => Promise.all(arr.map(predicate)).then((results) => arr.filter((_v, index) => results[index]));
715
+ async function getOptimizeDeps(config, options) {
716
+ const { root = process.cwd() } = config;
717
+ const absoluteStories = await listStories(options);
718
+ const stories = absoluteStories.map((storyPath) => normalizePath4(path5.relative(root, storyPath)));
719
+ const resolvedConfig = await resolveConfig(config, "serve", "development");
720
+ const resolve3 = resolvedConfig.createResolver({ asSrc: false });
721
+ const include2 = await asyncFilter(INCLUDE_CANDIDATES, async (id) => Boolean(await resolve3(id)));
722
+ const optimizeDeps = {
723
+ ...config.optimizeDeps,
724
+ // We don't need to resolve the glob since vite supports globs for entries.
725
+ entries: stories,
726
+ // We need Vite to precompile these dependencies, because they contain non-ESM code that would break
727
+ // if we served it directly to the browser.
728
+ include: [...include2, ...config.optimizeDeps?.include || []]
729
+ };
730
+ return optimizeDeps;
731
+ }
732
+
733
+ // src/envs.ts
734
+ import { stringifyEnvs } from "@storybook/core-common";
735
+ var allowedEnvVariables = [
736
+ "STORYBOOK",
737
+ // Vite `import.meta.env` default variables
738
+ // @see https://github.com/vitejs/vite/blob/6b8d94dca2a1a8b4952e3e3fcd0aed1aedb94215/packages/vite/types/importMeta.d.ts#L68-L75
739
+ "BASE_URL",
740
+ "MODE",
741
+ "DEV",
742
+ "PROD",
743
+ "SSR"
744
+ ];
745
+ function stringifyProcessEnvs(raw, envPrefix) {
746
+ const updatedRaw = {};
747
+ const envs = Object.entries(raw).reduce((acc, [key, value]) => {
748
+ if (allowedEnvVariables.includes(key) || Array.isArray(envPrefix) && !!envPrefix.find((prefix) => key.startsWith(prefix)) || typeof envPrefix === "string" && key.startsWith(envPrefix)) {
749
+ acc[`import.meta.env.${key}`] = JSON.stringify(value);
750
+ updatedRaw[key] = value;
751
+ }
752
+ return acc;
753
+ }, {});
754
+ envs["import.meta.env"] = JSON.stringify(stringifyEnvs(updatedRaw));
755
+ return envs;
756
+ }
757
+ async function sanitizeEnvVars(options, config) {
758
+ const { presets } = options;
759
+ const envsRaw = await presets.apply("env");
760
+ let { define } = config;
761
+ if (Object.keys(envsRaw).length) {
762
+ const envs = stringifyProcessEnvs(envsRaw, config.envPrefix);
763
+ define = {
764
+ ...define,
765
+ ...envs
766
+ };
767
+ }
768
+ return {
769
+ ...config,
770
+ define
771
+ };
772
+ }
773
+
774
+ // src/vite-server.ts
775
+ async function createViteServer(options, devServer) {
776
+ const { presets } = options;
777
+ const commonCfg = await commonConfig(options, "development");
778
+ const config = {
779
+ ...commonCfg,
780
+ // Set up dev server
781
+ server: {
782
+ middlewareMode: true,
783
+ hmr: {
784
+ port: options.port,
785
+ server: devServer
786
+ },
787
+ fs: {
788
+ strict: true
789
+ }
790
+ },
791
+ appType: "custom",
792
+ optimizeDeps: await getOptimizeDeps(commonCfg, options)
793
+ };
794
+ const finalConfig = await presets.apply("viteFinal", config, options);
795
+ return createServer(await sanitizeEnvVars(options, finalConfig));
796
+ }
797
+
798
+ // src/build.ts
799
+ import { build as viteBuild, mergeConfig as mergeConfig3 } from "vite";
800
+ async function build(options) {
801
+ const { presets } = options;
802
+ const config = await commonConfig(options, "build");
803
+ config.build = mergeConfig3(config, {
804
+ build: {
805
+ outDir: options.outputDir,
806
+ emptyOutDir: false,
807
+ // do not clean before running Vite build - Storybook has already added assets in there!
808
+ sourcemap: true,
809
+ rollupOptions: {
810
+ // Do not try to bundle the storybook runtime, it is copied into the output dir after the build.
811
+ external: ["./sb-preview/runtime.mjs"]
812
+ }
813
+ }
814
+ }).build;
815
+ const finalConfig = await presets.apply("viteFinal", config, options);
816
+ await viteBuild(await sanitizeEnvVars(options, finalConfig));
817
+ }
818
+
819
+ // src/utils/without-vite-plugins.ts
820
+ var withoutVitePlugins = async (plugins = [], namesToRemove) => {
821
+ const result = [];
822
+ const resolvedPlugins = await Promise.all(plugins);
823
+ for (const plugin of resolvedPlugins) {
824
+ if (Array.isArray(plugin)) {
825
+ result.push(await withoutVitePlugins(plugin, namesToRemove));
826
+ }
827
+ if (plugin && "name" in plugin && !namesToRemove.includes(plugin.name)) {
828
+ result.push(plugin);
829
+ }
830
+ }
831
+ return result;
832
+ };
833
+
834
+ // src/utils/has-vite-plugins.ts
835
+ function checkName(plugin, names) {
836
+ return plugin !== null && typeof plugin === "object" && "name" in plugin && names.includes(plugin.name);
837
+ }
838
+ async function hasVitePlugins(plugins, names) {
839
+ const resolvedPlugins = await Promise.all(plugins);
840
+ for (const plugin of resolvedPlugins) {
841
+ if (Array.isArray(plugin) && Boolean(await hasVitePlugins(plugin, names))) {
842
+ return true;
843
+ }
844
+ if (checkName(plugin, names)) {
845
+ return true;
846
+ }
847
+ }
848
+ return false;
849
+ }
850
+
851
+ // src/index.ts
852
+ function iframeMiddleware(options, server2) {
853
+ return async (req, res, next) => {
854
+ if (!req.url.match(/^\/iframe\.html($|\?)/)) {
855
+ next();
856
+ return;
857
+ }
858
+ if (req.query["html-proxy"] !== void 0) {
859
+ next();
860
+ return;
861
+ }
862
+ const indexHtml = await fs2.readFile(
863
+ __require.resolve("@storybook/builder-vite/input/iframe.html"),
864
+ "utf-8"
865
+ );
866
+ const generated = await transformIframeHtml(indexHtml, options);
867
+ const transformed = await server2.transformIndexHtml("/iframe.html", generated);
868
+ res.setHeader("Content-Type", "text/html");
869
+ res.status(200).send(transformed);
870
+ };
871
+ }
872
+ var server;
873
+ async function bail() {
874
+ return server?.close();
875
+ }
876
+ var start = async ({
877
+ startTime,
878
+ options,
879
+ router,
880
+ server: devServer
881
+ }) => {
882
+ server = await createViteServer(options, devServer);
883
+ const previewResolvedDir = dirname(__require.resolve("@storybook/preview/package.json"));
884
+ const previewDirOrigin = join2(previewResolvedDir, "dist");
885
+ router.use(`/sb-preview`, express.static(previewDirOrigin, { immutable: true, maxAge: "5m" }));
886
+ router.use(iframeMiddleware(options, server));
887
+ router.use(server.middlewares);
888
+ return {
889
+ bail,
890
+ stats: { toJson: () => null },
891
+ totalTime: process.hrtime(startTime)
892
+ };
893
+ };
894
+ var build2 = async ({ options }) => {
895
+ const viteCompilation = build(options);
896
+ const previewResolvedDir = dirname(__require.resolve("@storybook/preview/package.json"));
897
+ const previewDirOrigin = join2(previewResolvedDir, "dist");
898
+ const previewDirTarget = join2(options.outputDir || "", `sb-preview`);
899
+ const previewFiles = fs2.copy(previewDirOrigin, previewDirTarget, {
900
+ filter: (src) => {
901
+ const { ext } = parse2(src);
902
+ if (ext) {
903
+ return ext === ".mjs";
904
+ }
905
+ return true;
906
+ }
907
+ });
908
+ const [out] = await Promise.all([viteCompilation, previewFiles]);
909
+ return out;
910
+ };
911
+ export {
912
+ bail,
913
+ build2 as build,
914
+ hasVitePlugins,
915
+ start,
916
+ withoutVitePlugins
917
+ };