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

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