@storybook/builder-vite 7.0.0-beta.4 → 7.0.0-beta.41
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.
- package/README.md +46 -100
- package/dist/index.d.ts +27 -11
- package/dist/index.js +33 -37
- package/dist/index.mjs +11 -15
- package/input/iframe.html +38 -28
- package/package.json +22 -17
package/README.md
CHANGED
|
@@ -4,68 +4,34 @@ Build your stories with [vite](https://vitejs.dev/) for fast startup times and n
|
|
|
4
4
|
|
|
5
5
|
# Table of Contents <!-- omit in toc -->
|
|
6
6
|
|
|
7
|
-
- [Migration from storybook-builder-vite](#migration-from-storybook-builder-vite)
|
|
8
7
|
- [Installation](#installation)
|
|
9
8
|
- [Usage](#usage)
|
|
10
9
|
- [Getting started with Vite and Storybook (on a new project)](#getting-started-with-vite-and-storybook-on-a-new-project)
|
|
11
10
|
- [Migration from webpack / CRA](#migration-from-webpack--cra)
|
|
12
11
|
- [Customize Vite config](#customize-vite-config)
|
|
13
|
-
- [Svelte
|
|
12
|
+
- [Svelte Options](#svelte-options)
|
|
14
13
|
- [TypeScript](#typescript)
|
|
15
14
|
- [React Docgen](#react-docgen)
|
|
16
15
|
- [Note about working directory](#note-about-working-directory)
|
|
17
16
|
- [Known issues](#known-issues)
|
|
18
17
|
- [Contributing](#contributing)
|
|
19
|
-
- [About this codebase](#about-this-codebase)
|
|
20
|
-
|
|
21
|
-
## Migration from storybook-builder-vite
|
|
22
|
-
|
|
23
|
-
This project has moved from `storybook-builder-vite` to `@storybook/builder-vite` as part of a larger effort to improve Vite support in Storybook. To automatically migrate your existing project, you can run
|
|
24
|
-
|
|
25
|
-
```bash
|
|
26
|
-
npx sb@next automigrate
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
To manually migrate:
|
|
30
|
-
|
|
31
|
-
1. Remove `storybook-builder-vite` from your `package.json` dependencies
|
|
32
|
-
2. Install `@storybook/builder-vite`
|
|
33
|
-
3. Update your `core.builder` setting in `.storybook/main.js` to `@storybook/builder-vite`.
|
|
34
18
|
|
|
35
19
|
## Installation
|
|
36
20
|
|
|
37
21
|
Requirements:
|
|
38
22
|
|
|
39
|
-
- Vite 3.0 or newer (
|
|
40
|
-
- Storybook 6.4.0 or newer (for storybook 6.3, use `storybook-builder-vite@0.1.16`)
|
|
41
|
-
|
|
42
|
-
```bash
|
|
43
|
-
npm install @storybook/builder-vite --save-dev
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
or
|
|
47
|
-
|
|
48
|
-
```bash
|
|
49
|
-
yarn add --dev @storybook/builder-vite
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
or
|
|
23
|
+
- Vite 3.0 or newer (4.X recommended)
|
|
53
24
|
|
|
54
|
-
|
|
55
|
-
pnpm add --save-dev @storybook/builder-vite
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
Note: when using `pnpm`, you may need to enable [shamefully-hoist](https://pnpm.io/npmrc#shamefully-hoist), until https://github.com/storybookjs/builder-vite/issues/55 can be fixed.
|
|
25
|
+
When installing Storybook, use the `--builder=vite` flag if you do not have a `vite.config` file at your project root (if you do, the vite builder is chosen automatically).
|
|
59
26
|
|
|
60
27
|
## Usage
|
|
61
28
|
|
|
62
|
-
|
|
63
|
-
set `core: { builder: "@storybook/builder-vite" }`.
|
|
29
|
+
The builder supports both development mode in Storybook and building a static production version.
|
|
64
30
|
|
|
65
|
-
|
|
66
|
-
> See also [#53](https://github.com/storybookjs/builder-vite/pull/53)
|
|
31
|
+
Your `vite.config` file will be used by Storybook. If you need to customize the vite config for Storybook, you have two choices:
|
|
67
32
|
|
|
68
|
-
|
|
33
|
+
1. Set values in your `vite.config` conditionally, based on an environment variable, for example.
|
|
34
|
+
2. Add a `viteFinal` config to your `.storybook/main.js` file. See [Customize Vite config](#customize-vite-config) for details.
|
|
69
35
|
|
|
70
36
|
### Getting started with Vite and Storybook (on a new project)
|
|
71
37
|
|
|
@@ -73,15 +39,15 @@ See https://vitejs.dev/guide/#scaffolding-your-first-vite-project,
|
|
|
73
39
|
|
|
74
40
|
```
|
|
75
41
|
npm create vite@latest # follow the prompts
|
|
76
|
-
npx sb init --builder
|
|
42
|
+
npx sb@next init --builder vite && npm run storybook
|
|
77
43
|
```
|
|
78
44
|
|
|
79
45
|
### Migration from webpack / CRA
|
|
80
46
|
|
|
81
47
|
1. Install `vite` and `@storybook/builder-vite`
|
|
82
48
|
2. Remove any explicit project dependencies on `webpack`, `react-scripts`, and any other webpack plugins or loaders.
|
|
83
|
-
3. If you were previously using `@storybook/manager-webpack5`, you
|
|
84
|
-
4.
|
|
49
|
+
3. If you were previously using `@storybook/manager-webpack5`, you can remove it. Also remove `@storybook/builder-webpack5` or `@storybook/builder-webpack4` if they are installed.
|
|
50
|
+
4. Choose a vite-based Storybook "framework" to set in the `framework` option of your `.storybook/main.js` file.
|
|
85
51
|
5. Remove storybook webpack cache (`rm -rf node_modules/.cache`)
|
|
86
52
|
6. Update your `/public/index.html` file for vite (be sure there are no `%PUBLIC_URL%` inside it, which is a CRA variable)
|
|
87
53
|
7. Be sure that any files containing JSX syntax use a `.jsx` or `.tsx` file extension, which [vite requires](https://vitejs.dev/guide/features.html#jsx). This includes `.storybook/preview.jsx` if it contains JSX syntax.
|
|
@@ -99,65 +65,66 @@ For other details about the differences between vite and webpack projects, be su
|
|
|
99
65
|
|
|
100
66
|
### Customize Vite config
|
|
101
67
|
|
|
102
|
-
The builder
|
|
68
|
+
The builder _will_ read your `vite.config.js` file, though it may change some of the options in order to work correctly.
|
|
69
|
+
It looks for the Vite config in the CWD. If your config is located elsewhere, specify the path using the `viteConfigPath` builder option:
|
|
103
70
|
|
|
104
|
-
|
|
105
|
-
|
|
71
|
+
```javascript
|
|
72
|
+
// .storybook/main.mjs
|
|
73
|
+
|
|
74
|
+
const config = {
|
|
75
|
+
framework: {
|
|
76
|
+
name: '@storybook/react-vite', // Your framework name here.
|
|
77
|
+
options: {
|
|
78
|
+
builder: {
|
|
79
|
+
viteConfigPath: '.storybook/customViteConfig.js',
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export default config;
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
You can also override the merged Vite config:
|
|
106
89
|
|
|
107
90
|
```javascript
|
|
108
91
|
// use `mergeConfig` to recursively merge Vite options
|
|
109
|
-
|
|
92
|
+
import { mergeConfig } from 'vite';
|
|
110
93
|
|
|
111
|
-
|
|
94
|
+
const config = {
|
|
112
95
|
async viteFinal(config, { configType }) {
|
|
113
|
-
// return the customized config
|
|
96
|
+
// Be sure to return the customized config
|
|
114
97
|
return mergeConfig(config, {
|
|
115
|
-
//
|
|
98
|
+
// Customize the Vite config for Storybook
|
|
116
99
|
resolve: {
|
|
117
100
|
alias: { foo: 'bar' },
|
|
118
101
|
},
|
|
119
102
|
});
|
|
120
103
|
},
|
|
121
|
-
// ... other options here
|
|
122
104
|
};
|
|
105
|
+
|
|
106
|
+
export default config;
|
|
123
107
|
```
|
|
124
108
|
|
|
125
|
-
The `viteFinal` function will give you `config` which is
|
|
126
|
-
|
|
127
|
-
for example to set up aliases, add new plugins etc.
|
|
109
|
+
The `viteFinal` function will give you `config` which is the combination of your project's vite config and the builder's own Vite config.
|
|
110
|
+
You can tweak this as you want, for example to set up aliases, add new plugins etc.
|
|
128
111
|
|
|
129
112
|
The `configType` variable will be either `"DEVELOPMENT"` or `"PRODUCTION"`.
|
|
130
113
|
|
|
131
114
|
The function should return the updated Vite configuration.
|
|
132
115
|
|
|
133
|
-
### Svelte
|
|
134
|
-
|
|
135
|
-
When using this builder with Svelte, your `.storybook/main.js` (or equivalent)
|
|
136
|
-
can contain a `svelteOptions` object to pass custom options to
|
|
137
|
-
[`vite-plugin-svelte`](https://github.com/sveltejs/vite-plugin-svelte/tree/main/packages/vite-plugin-svelte):
|
|
116
|
+
### Svelte Options
|
|
138
117
|
|
|
139
|
-
|
|
140
|
-
const preprocess = require('svelte-preprocess');
|
|
141
|
-
|
|
142
|
-
module.exports = {
|
|
143
|
-
svelteOptions: {
|
|
144
|
-
preprocess: preprocess({
|
|
145
|
-
typescript: true,
|
|
146
|
-
postcss: true,
|
|
147
|
-
sourceMap: true,
|
|
148
|
-
}),
|
|
149
|
-
},
|
|
150
|
-
};
|
|
151
|
-
```
|
|
118
|
+
When using this builder with Svelte, your `svelte.config.js` file will be used automatically.
|
|
152
119
|
|
|
153
120
|
### TypeScript
|
|
154
121
|
|
|
155
122
|
Configure your `.storybook/main.ts` to use TypeScript:
|
|
156
123
|
|
|
157
124
|
```typescript
|
|
158
|
-
import type {
|
|
125
|
+
import type { StorybookConfig } from '@storybook/react-vite'; // (or whatever framework you are using)
|
|
159
126
|
|
|
160
|
-
const config:
|
|
127
|
+
const config: StorybookConfig = {
|
|
161
128
|
// other storybook options...,
|
|
162
129
|
async viteFinal(config, options) {
|
|
163
130
|
// modify and return config
|
|
@@ -167,24 +134,14 @@ const config: StorybookViteConfig = {
|
|
|
167
134
|
export default config;
|
|
168
135
|
```
|
|
169
136
|
|
|
170
|
-
Or alternatively, you can use named exports:
|
|
171
|
-
|
|
172
|
-
```typescript
|
|
173
|
-
import type { ViteFinal } from '@storybook/builder-vite';
|
|
174
|
-
|
|
175
|
-
export const viteFinal: ViteFinal = async (config, options) => {
|
|
176
|
-
// modify and return config
|
|
177
|
-
};
|
|
178
|
-
```
|
|
179
|
-
|
|
180
137
|
See [Customize Vite config](#customize-vite-config) for details about using `viteFinal`.
|
|
181
138
|
|
|
182
139
|
### React Docgen
|
|
183
140
|
|
|
184
|
-
Docgen is used in Storybook to populate the props table in docs view, the controls panel, and for several other addons. Docgen is supported in
|
|
141
|
+
Docgen is used in Storybook to populate the props table in docs view, the controls panel, and for several other addons. Docgen is supported in Svelte, Vue, and React, and there are two docgen options when using react, `react-docgen` and `react-docgen-typescript`. You can learn more about the pros/cons of each in [this gist](https://gist.github.com/shilman/036313ffa3af52ca986b375d90ea46b0). By default, if we find a `typescript` dependency in your `package.json` file, we will assume you're using typescript and will choose `react-docgen-typescript`. You can change this by setting the `typescript.reactDocgen` option in your `.storybook/main.js` file:
|
|
185
142
|
|
|
186
143
|
```javascript
|
|
187
|
-
|
|
144
|
+
export default {
|
|
188
145
|
typescript: {
|
|
189
146
|
reactDocgen: 'react-docgen`
|
|
190
147
|
}
|
|
@@ -206,20 +163,9 @@ storybook configuration directory. This can be overridden in viteFinal.
|
|
|
206
163
|
## Contributing
|
|
207
164
|
|
|
208
165
|
The Vite builder cannot build itself.
|
|
209
|
-
Are you willing to contribute? We are especially looking for
|
|
166
|
+
Are you willing to contribute? We are especially looking for Vue and Svelte experts, as the current maintainers are react users.
|
|
210
167
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
Have a look at the GitHub issues for known bugs. If you find any new bugs,
|
|
168
|
+
Have a look at the GitHub issues with the `vite` label for known bugs. If you find any new bugs,
|
|
214
169
|
feel free to create an issue or send a pull request!
|
|
215
170
|
|
|
216
171
|
Please read the [How to contribute](/CONTRIBUTING.md) guide.
|
|
217
|
-
|
|
218
|
-
### About this codebase
|
|
219
|
-
|
|
220
|
-
The code is a monorepo with the core `@storybook/builder-vite` package,
|
|
221
|
-
and examples (like `examples/react`) to test the builder implementation.
|
|
222
|
-
|
|
223
|
-
Similar to the main storybook monorepo, you need yarn to develop this builder, because the project is organized as yarn workspaces.
|
|
224
|
-
This lets you write new code in the core builder package, and instantly use them from
|
|
225
|
-
the example packages.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,43 @@
|
|
|
1
|
-
import { Builder, Options, StorybookConfig
|
|
2
|
-
|
|
3
|
-
import { PluginOption, UserConfig, InlineConfig } from 'vite';
|
|
4
|
-
|
|
5
|
-
declare const withoutVitePlugins: (plugins: PluginOption[] | undefined, namesToRemove: string[]) => PluginOption[];
|
|
1
|
+
import { Builder, Options, StorybookConfig } from '@storybook/types';
|
|
2
|
+
import { UserConfig, InlineConfig, PluginOption } from 'vite';
|
|
6
3
|
|
|
7
4
|
type ViteStats = {
|
|
8
5
|
toJson: () => any;
|
|
9
6
|
};
|
|
10
7
|
type ViteBuilder = Builder<UserConfig, ViteStats>;
|
|
11
8
|
type ViteFinal = (config: InlineConfig, options: Options) => InlineConfig | Promise<InlineConfig>;
|
|
12
|
-
type
|
|
9
|
+
type StorybookConfigVite = {
|
|
13
10
|
viteFinal?: ViteFinal;
|
|
14
11
|
};
|
|
12
|
+
type BuilderOptions = {
|
|
13
|
+
/**
|
|
14
|
+
* Path to vite.config file, relative to CWD.
|
|
15
|
+
*/
|
|
16
|
+
viteConfigPath?: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Recursively removes all plugins with the names given
|
|
21
|
+
* Resolves async plugins
|
|
22
|
+
*/
|
|
23
|
+
declare const withoutVitePlugins: (plugins: PluginOption[] | undefined, namesToRemove: string[]) => Promise<PluginOption[]>;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Returns true if ANY of the plugins in the array have a name that matches one of the names in the names array.
|
|
27
|
+
* Will resolve any promises in the array.
|
|
28
|
+
*/
|
|
29
|
+
declare function hasVitePlugins(plugins: PluginOption[], names: string[]): Promise<boolean>;
|
|
30
|
+
|
|
15
31
|
/**
|
|
16
32
|
* @deprecated
|
|
17
33
|
*
|
|
18
|
-
*
|
|
34
|
+
* Import `StorybookConfig` from your framework, such as:
|
|
19
35
|
*
|
|
20
|
-
*
|
|
36
|
+
* `import type { StorybookConfig } from '@storybook/react-vite';`
|
|
21
37
|
*/
|
|
22
|
-
type StorybookViteConfig = StorybookConfig;
|
|
23
|
-
declare function bail(
|
|
38
|
+
type StorybookViteConfig = StorybookConfig & StorybookConfigVite;
|
|
39
|
+
declare function bail(): Promise<void>;
|
|
24
40
|
declare const start: ViteBuilder['start'];
|
|
25
41
|
declare const build: ViteBuilder['build'];
|
|
26
42
|
|
|
27
|
-
export {
|
|
43
|
+
export { BuilderOptions, StorybookConfigVite, StorybookViteConfig, ViteBuilder, ViteFinal, bail, build, hasVitePlugins, start, withoutVitePlugins };
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
|
|
3
|
-
${e}
|
|
4
|
-
`}function G(e){let r,t=(0,U.createFilter)(/\.mdx?$/);return{name:"storybook:mdx-plugin",enforce:"pre",configResolved({plugins:n}){r=n.filter(s=>s.name==="react-refresh"||s.name==="vite:react-babel"||s.name==="vite:react-refresh"||s.name==="vite:react-jsx").find(s=>s.transform)},async transform(n,i,s){if(!t(i))return;let{compile:c}=await import("@storybook/mdx2-csf"),m=await e.presets.apply("mdxLoaderOptions",{mdxCompileOptions:{providerImportSource:"@storybook/addon-docs/mdx-react-shim"}}),p=String(await c(n,{skipCsf:!Be(i),...m})),u=Me(p),f=r==null?void 0:r.transform,y=await(f&&"handler"in f?f.handler:f).call(this,u,`${i}.jsx`,s);if(!y)return u;if(typeof y=="string")return y;let{code:x,map:O}=y;return{code:x,map:!O||typeof O=="string"?O:{...O,sources:[i]}}}}}var W=require("vite"),Y=a(require("magic-string"));function K(){let e=(0,W.createFilter)(/\.stories\.([tj])sx?$/);return{name:"storybook:strip-hmr-boundary-plugin",enforce:"post",async transform(r,o){if(!e(o))return;let t=new Y.default(r);return t.replace(/import\.meta\.hot\.accept\(\);/,""),{code:t.toString(),map:t.generateMap({hires:!0,source:o})}}}}var ue=a(require("fs")),ye=require("vite");var te=require("@storybook/core-common");var h="/virtual:/@storybook/builder-vite/vite-app.js",l="/virtual:/@storybook/builder-vite/storybook-stories.js",g="/virtual:/@storybook/builder-vite/preview-entry.js",v="/virtual:/@storybook/builder-vite/setup-addons.js";var ee=require("path"),N=a(require("slash"));var Q=a(require("path")),X=require("vite");function Z(e){let r=e.split(`node_modules${Q.default.sep}`);return(0,X.normalizePath)(r[r.length-1])}function P(e){if(typeof e=="object")return e.bare;if((e==null?void 0:e.startsWith("./"))||(e==null?void 0:e.startsWith("../")))return(0,N.default)((0,ee.resolve)(e));if(!e)throw new Error("Could not determine path for previewAnnotation");return e.includes("node_modules")?Z(e):(0,N.default)(e)}async function re(e){let{presets:r}=e,o=await(0,te.getRendererName)(e),n=[...await r.apply("previewAnnotations",[],e)].filter(Boolean).map(P),i=(m,p)=>m.map((u,f)=>`import ${p?`* as ${p}_${f} from `:""}'${u}'`).join(`
|
|
5
|
-
`),s=(m,p)=>new Array(p).fill(0).map((u,f)=>`${m}_${f}`);return`
|
|
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}=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("[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_vite11=require("vite");var path4=__toESM(require("path")),import_vite9=require("vite"),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){let filter2=(0,import_vite2.createFilter)(/\.mdx$/),{mdxPluginOptions,jsxOptions}=await options.presets.apply("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",{...mdxPluginOptions,mdxCompileOptions:{providerImportSource:"@storybook/addon-docs/mdx-react-shim",...mdxPluginOptions==null?void 0:mdxPluginOptions.mdxCompileOptions},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`
|
|
6
3
|
// Ensure that the client API is initialized by the framework before any other iframe code
|
|
7
4
|
// is loaded. That way our client-apis can assume the existence of the API+store
|
|
8
|
-
import { configure } from '${
|
|
5
|
+
import { configure } from '${rendererName}';
|
|
9
6
|
|
|
10
7
|
import { logger } from '@storybook/client-logger';
|
|
11
|
-
import * as
|
|
12
|
-
${
|
|
8
|
+
import * as previewApi from "@storybook/preview-api";
|
|
9
|
+
${filesToImport(configEntries,"config")}
|
|
13
10
|
|
|
14
|
-
import * as preview from '${
|
|
15
|
-
import { configStories } from '${
|
|
11
|
+
import * as preview from '${virtualPreviewFile}';
|
|
12
|
+
import { configStories } from '${virtualStoriesFile}';
|
|
16
13
|
|
|
17
14
|
const {
|
|
18
15
|
addDecorator,
|
|
@@ -26,7 +23,7 @@
|
|
|
26
23
|
setGlobalRender,
|
|
27
24
|
} = previewApi;
|
|
28
25
|
|
|
29
|
-
const configs = [${
|
|
26
|
+
const configs = [${importArray("config",configEntries.length).concat("preview.default").join(",")}].filter(Boolean)
|
|
30
27
|
|
|
31
28
|
configs.forEach(config => {
|
|
32
29
|
Object.keys(config).forEach((key) => {
|
|
@@ -86,69 +83,68 @@
|
|
|
86
83
|
*/
|
|
87
84
|
|
|
88
85
|
configStories(configure);
|
|
89
|
-
`.trim()}var
|
|
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"?`
|
|
90
87
|
if (import.meta.hot) {
|
|
91
88
|
import.meta.hot.decline();
|
|
92
89
|
}`.trim():`
|
|
93
90
|
if (import.meta.hot) {
|
|
94
|
-
import.meta.hot.accept('${
|
|
91
|
+
import.meta.hot.accept('${virtualStoriesFile}', (newModule) => {
|
|
95
92
|
// importFn has changed so we need to patch the new one in
|
|
96
|
-
|
|
93
|
+
window.__STORYBOOK_PREVIEW__.onStoriesChanged({ importFn: newModule.importFn });
|
|
97
94
|
});
|
|
98
95
|
|
|
99
|
-
import.meta.hot.accept(${JSON.stringify(
|
|
96
|
+
import.meta.hot.accept(${JSON.stringify(relativePreviewAnnotations)}, ([...newConfigEntries]) => {
|
|
100
97
|
const newGetProjectAnnotations = () => composeConfigs(newConfigEntries);
|
|
101
98
|
|
|
102
99
|
// getProjectAnnotations has changed so we need to patch the new one in
|
|
103
|
-
|
|
100
|
+
window.__STORYBOOK_PREVIEW__.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
|
|
104
101
|
});
|
|
105
102
|
}`.trim();return`
|
|
106
103
|
import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
|
|
107
|
-
import '${
|
|
108
|
-
import { importFn } from '${
|
|
104
|
+
import '${virtualAddonSetupFile}';
|
|
105
|
+
import { importFn } from '${virtualStoriesFile}';
|
|
109
106
|
|
|
110
107
|
const getProjectAnnotations = async () => {
|
|
111
|
-
const configs = await Promise.all([${
|
|
108
|
+
const configs = await Promise.all([${relativePreviewAnnotations.map(previewAnnotation=>`import('${previewAnnotation}')`).join(`,
|
|
112
109
|
`)}])
|
|
113
110
|
return composeConfigs(configs);
|
|
114
111
|
}
|
|
115
112
|
|
|
116
|
-
const preview = new PreviewWeb();
|
|
117
113
|
|
|
118
|
-
window.__STORYBOOK_PREVIEW__ =
|
|
119
|
-
|
|
120
|
-
window.
|
|
121
|
-
|
|
122
|
-
|
|
114
|
+
window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
|
|
115
|
+
|
|
116
|
+
window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
|
|
117
|
+
window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
|
|
118
|
+
window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
|
|
123
119
|
|
|
124
|
-
${
|
|
125
|
-
`.trim()}var
|
|
120
|
+
${generateHMRHandler(frameworkName)};
|
|
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`
|
|
126
122
|
const importers = {
|
|
127
|
-
${
|
|
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(`,
|
|
128
124
|
`)}
|
|
129
125
|
};
|
|
130
126
|
|
|
131
127
|
export async function importFn(path) {
|
|
132
128
|
return importers[path]();
|
|
133
129
|
}
|
|
134
|
-
`}async function
|
|
135
|
-
`);async function
|
|
136
|
-
${
|
|
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")}
|
|
137
133
|
|
|
138
134
|
function loadable(key) {
|
|
139
|
-
return {${
|
|
135
|
+
return {${modules}}[key];
|
|
140
136
|
}
|
|
141
137
|
|
|
142
138
|
Object.assign(loadable, {
|
|
143
|
-
keys: () => (${JSON.stringify(Object.keys(
|
|
144
|
-
resolve: (key) => (${JSON.stringify(
|
|
139
|
+
keys: () => (${JSON.stringify(Object.keys(resolveMap))}),
|
|
140
|
+
resolve: (key) => (${JSON.stringify(resolveMap)}[key])
|
|
145
141
|
});
|
|
146
142
|
|
|
147
143
|
export function configStories(configure) {
|
|
148
144
|
configure(loadable, { hot: import.meta.hot }, false);
|
|
149
145
|
}
|
|
150
|
-
`.trim()}async function
|
|
151
|
-
export default preview;`:""}async function
|
|
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`
|
|
152
148
|
import { createChannel as createPostMessageChannel } from '@storybook/channel-postmessage';
|
|
153
149
|
import { createChannel as createWebSocketChannel } from '@storybook/channel-websocket';
|
|
154
150
|
import { addons } from '@storybook/preview-api';
|
|
@@ -163,4 +159,4 @@
|
|
|
163
159
|
addons.setServerChannel(serverChannel);
|
|
164
160
|
window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
|
|
165
161
|
}
|
|
166
|
-
`.trim()}function ge(e){let r=require.resolve("@storybook/builder-vite/input/iframe.html"),o;return{name:"storybook:code-generator-plugin",enforce:"pre",configureServer(t){t.watcher.on("change",()=>{let n=t.moduleGraph.getModuleById(h);n&&t.moduleGraph.invalidateModule(n);let i=t.moduleGraph.getModuleById(l);i&&t.moduleGraph.invalidateModule(i)}),t.watcher.on("add",n=>{(/\.stories\.([tj])sx?$/.test(n)||/\.(story|stories).mdx$/.test(n))&&t.watcher.emit("change",l)})},config(t,{command:n}){n==="build"&&(t.build||(t.build={}),t.build.rollupOptions={...t.build.rollupOptions,input:r});try{require.resolve("react-dom/client",{paths:[t.root||process.cwd()]})}catch(i){Je(i)&&i.code==="MODULE_NOT_FOUND"&&(t.resolve=(0,ye.mergeConfig)(t.resolve??{},{alias:{"react-dom/client":require.resolve("@storybook/builder-vite/input/react-dom-client-placeholder.js")}}))}},configResolved(t){o=`${t.root}/iframe.html`},resolveId(t){if(t===h)return h;if(t===r)return o;if(t===l)return l;if(t===g)return g;if(t===v)return v},async load(t){var i;let n=(i=e.features)==null?void 0:i.storyStoreV7;if(t===l)return n?pe(e):le(e);if(t===v)return de();if(t===g&&!n)return fe(e);if(t===h)return n?oe(e):re(e);if(t===o)return ue.readFileSync(require.resolve("@storybook/builder-vite/input/iframe.html"),"utf-8")},async transformIndexHtml(t,n){if(n.path==="/iframe.html")return C(t,e)}}}var Je=e=>e instanceof Error;var ve=require("@storybook/csf-plugin");async function we(e){var n;let{presets:r}=e,t=((n=(await r.apply("addons",[])).find(i=>[i,i.name].includes("@storybook/addon-docs")))==null?void 0:n.options)??{};return(0,ve.vite)(t==null?void 0:t.csfPluginOptions)}var Ue={mode:"development",command:"serve",ssrBuild:!1},Ge={mode:"production",command:"build",ssrBuild:!1};async function _(e,r){let o=r==="development"?Ue:Ge,{config:{build:t=void 0,...n}={}}=await(0,R.loadConfigFromFile)(o)??{},i={configFile:!1,cacheDir:"node_modules/.cache/.vite-storybook",root:he.resolve(e.configDir,".."),base:"./",plugins:await We(e),resolve:{preserveSymlinks:(0,A.isPreservingSymlinks)(),alias:{assert:require.resolve("browser-assert")}},envPrefix:n.envPrefix?"STORYBOOK_":["VITE_","STORYBOOK_"]};return(0,R.mergeConfig)(n,i)}async function We(e){let r=await(0,A.getFrameworkName)(e),o=[ge(e),await we(e),G(e),J,K(),{name:"storybook:allow-storybook-dir",enforce:"post",config(t){var n,i;(i=(n=t==null?void 0:t.server)==null?void 0:n.fs)!=null&&i.allow&&t.server.fs.allow.push(".storybook")}},(0,Ee.default)(xe.globals)];if(r!=="@storybook/react-vite"&&o.push((0,be.default)({exclude:[/\.stories\.([tj])sx?$/,/node_modules/,/\.([tj])sx?$/]})),r==="@storybook/preact-vite"&&o.push(require("@preact/preset-vite").default()),r==="@storybook/glimmerx-vite"){let t=require("vite-plugin-glimmerx/index.cjs");o.push(t.default())}return o}var Oe=a(require("path")),D=require("vite");var Ye=["@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/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","global","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"],Ke=async(e,r)=>Promise.all(e.map(r)).then(o=>e.filter((t,n)=>o[n]));async function Se(e,r){let{root:o=process.cwd()}=e,n=(await w(r)).map(p=>(0,D.normalizePath)(Oe.relative(o,p))),s=(await(0,D.resolveConfig)(e,"serve","development")).createResolver({asSrc:!1}),c=await Ke(Ye,async p=>Boolean(await s(p)));return{entries:n,include:c}}var Ce=require("@storybook/core-common"),Qe=["STORYBOOK","BASE_URL","MODE","DEV","PROD","SSR"];function Xe(e,r){let o={},t=Object.entries(e).reduce((n,[i,s])=>((Qe.includes(i)||Array.isArray(r)&&!!r.find(c=>i.startsWith(c))||typeof r=="string"&&i.startsWith(r))&&(n[`import.meta.env.${i}`]=JSON.stringify(s),o[i]=s),n),{});return t["import.meta.env"]=JSON.stringify((0,Ce.stringifyEnvs)(o)),t}async function I(e,r){let{presets:o}=e,t=await o.apply("env"),{define:n}=r;if(Object.keys(t).length){let i=Xe(t,r.envPrefix);n={...n,...i}}return{...r,define:n}}async function ke(e,r){let{presets:o}=e,t=await _(e,"development"),n={...t,server:{middlewareMode:!0,hmr:{port:e.port,server:r},fs:{strict:!0}},appType:"custom",optimizeDeps:await Se(t,e)},i=await o.apply("viteFinal",n,e);return(0,Pe.createServer)(await I(e,i))}var $=require("vite");async function je(e){let{presets:r}=e,o=await _(e,"build");o.build=(0,$.mergeConfig)(o,{build:{outDir:e.outputDir,emptyOutDir:!1,sourcemap:!0,rollupOptions:{external:["/sb-preview/runtime.mjs"]}}}).build;let t=await r.apply("viteFinal",o,e);await(0,$.build)(await I(e,t))}var H=(e=[],r)=>e.map(o=>Array.isArray(o)?H(o,r):o&&"name"in o&&r.includes(o.name)?!1:o);function Ze(e,r){return async(o,t,n)=>{if(!o.url.match(/^\/iframe\.html($|\?)/)){n();return}if(o.query["html-proxy"]!==void 0){n();return}let i=await F.readFile(require.resolve("@storybook/builder-vite/input/iframe.html"),"utf-8"),s=await C(i,e),c=await r.transformIndexHtml("/iframe.html",s);t.setHeader("Content-Type","text/html"),t.status(200).send(c)}}var T;async function Ae(e){try{return await T.close()}catch{console.warn("unable to close vite server")}throw e}var et=async({startTime:e,options:r,router:o,server:t})=>{T=await ke(r,t);let n=(0,d.dirname)(require.resolve("@storybook/preview/package.json")),i=(0,d.join)(n,"dist");return o.use("/sb-preview",Re.default.static(i,{immutable:!0,maxAge:"5m"})),o.use(Ze(r,T)),o.use(T.middlewares),{bail:Ae,stats:{toJson:()=>null},totalTime:process.hrtime(e)}},tt=async({options:e})=>{let r=je(e),o=(0,d.dirname)(require.resolve("@storybook/preview/package.json")),t=(0,d.join)(o,"dist"),n=(0,d.join)(e.outputDir||"","sb-preview"),i=F.copy(t,n,{filter:c=>{let{ext:m}=(0,d.parse)(c);return m?m===".mjs":!0}}),[s]=await Promise.all([r,i]);return s};0&&(module.exports={bail,build,start,withoutVitePlugins});
|
|
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 import_node_path=require("path"),import_es_module_lexer2=require("es-module-lexer"),import_magic_string3=__toESM(require("magic-string")),import_fs_extra=require("fs-extra"),import_vite8=require("vite"),escapeKeys=key=>key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),defaultImportRegExp="import ([^*{}]+) from",replacementMap=new Map([["import ","const "],["import{","const {"],["* as ",""],[" as ",": "],[" from "," = "],["}from","} ="]]);async function externalGlobalsPlugin(externals){return await import_es_module_lexer2.init,{name:"storybook:external-globals-plugin",enforce:"post",async config(config,{command}){var _a;if(command!=="serve")return;let newAlias=(0,import_vite8.mergeAlias)([],(_a=config.resolve)==null?void 0:_a.alias),cachePath=(0,import_node_path.join)(process.cwd(),"node_modules",".cache","vite-plugin-externals");return await(0,import_fs_extra.ensureDir)(cachePath),await(0,import_fs_extra.emptyDir)(cachePath),await Promise.all(Object.keys(externals).map(async externalKey=>{let externalCachePath=(0,import_node_path.join)(cachePath,`${externalKey}.js`);newAlias.push({find:new RegExp(`^${externalKey}$`),replacement:externalCachePath}),await(0,import_fs_extra.ensureFile)(externalCachePath),await(0,import_fs_extra.writeFile)(externalCachePath,`module.exports = ${externals[externalKey]};`)})),{resolve:{alias:newAlias}}},async transform(code,id){let globalsList=Object.keys(externals);if(globalsList.every(glob2=>!code.includes(glob2)))return;let[imports]=(0,import_es_module_lexer2.parse)(code),src=new import_magic_string3.default(code);return imports.forEach(({n:path6,ss:startPosition,se:endPosition})=>{let packageName=path6;if(packageName&&globalsList.includes(packageName)){let importStatement=src.slice(startPosition,endPosition),transformedImport=rewriteImport(importStatement,externals,packageName);src.update(startPosition,endPosition,transformedImport)}}),{code:src.toString(),map:src.generateMap({source:id,includeContent:!0,hires:!0})}}}}function getDefaultImportReplacement(match){let matched=match.match(defaultImportRegExp);return matched&&`const {default: ${matched[1]}} =`}function getSearchRegExp(packageName){let staticKeys=[...replacementMap.keys()].map(escapeKeys),packageNameLiteral=`.${packageName}.`,dynamicImportExpression=`await import\\(.${packageName}.\\)`,lookup=[defaultImportRegExp,...staticKeys,packageNameLiteral,dynamicImportExpression];return new RegExp(`(${lookup.join("|")})`,"g")}function rewriteImport(importStatement,globs,packageName){let search=getSearchRegExp(packageName);return importStatement.replace(search,match=>replacementMap.get(match)??getDefaultImportReplacement(match)??globs[packageName])}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,{viteConfigPath}=await(0,import_core_common6.getBuilderOptions)(options),{config:{build:buildProperty=void 0,...userConfig}={}}=await(0,import_vite9.loadConfigFromFile)(configEnv,viteConfigPath)??{},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_vite9.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")}},await externalGlobalsPlugin(import_globals.globals)];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_vite10=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_vite10.normalizePath)(path5.relative(root,storyPath))),resolve3=(await(0,import_vite10.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_vite11.createServer)(await sanitizeEnvVars(options,finalConfig))}var import_vite12=require("vite");async function build(options){let{presets}=options,config=await commonConfig(options,"build");config.build=(0,import_vite12.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_vite12.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});
|
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
var __require=(x=>typeof require
|
|
2
|
-
import React from 'react';
|
|
3
|
-
${code}
|
|
4
|
-
`}function mdxPlugin(options){let reactRefresh,filter2=createFilter2(/\.mdx?$/);return{name:"storybook:mdx-plugin",enforce:"pre",configResolved({plugins}){reactRefresh=plugins.filter(p=>p.name==="react-refresh"||p.name==="vite:react-babel"||p.name==="vite:react-refresh"||p.name==="vite:react-jsx").find(p=>p.transform)},async transform(src,id,transformOptions){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"}}),mdxCode=String(await compile(src,{skipCsf:!isStorybookMdx(id),...mdxLoaderOptions})),modifiedCode=injectRenderer(mdxCode),rTransform=reactRefresh?.transform,result=await(rTransform&&"handler"in rTransform?rTransform.handler:rTransform).call(this,modifiedCode,`${id}.jsx`,transformOptions);if(!result)return modifiedCode;if(typeof result=="string")return result;let{code,map:resultMap}=result;return{code,map:!resultMap||typeof resultMap=="string"?resultMap:{...resultMap,sources:[id]}}}}}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(`
|
|
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 join3,parse as parse3}from"path";import{normalizeStories}from"@storybook/core-common";async function transformIframeHtml(html,options){let{configType,features,presets,serverChannelUrl}=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("[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{isPreservingSymlinks,getFrameworkName as getFrameworkName2,getBuilderOptions}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$/),{mdxPluginOptions,jsxOptions}=await options.presets.apply("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",{...mdxPluginOptions,mdxCompileOptions:{providerImportSource:"@storybook/addon-docs/mdx-react-shim",...mdxPluginOptions?.mdxCompileOptions},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(`
|
|
5
2
|
`),importArray=(name,length)=>new Array(length).fill(0).map((_,i)=>`${name}_${i}`);return`
|
|
6
3
|
// Ensure that the client API is initialized by the framework before any other iframe code
|
|
7
4
|
// is loaded. That way our client-apis can assume the existence of the API+store
|
|
8
5
|
import { configure } from '${rendererName}';
|
|
9
6
|
|
|
10
7
|
import { logger } from '@storybook/client-logger';
|
|
11
|
-
import * as
|
|
8
|
+
import * as previewApi from "@storybook/preview-api";
|
|
12
9
|
${filesToImport(configEntries,"config")}
|
|
13
10
|
|
|
14
11
|
import * as preview from '${virtualPreviewFile}';
|
|
@@ -93,14 +90,14 @@ var __require=(x=>typeof require!="undefined"?require:typeof Proxy!="undefined"?
|
|
|
93
90
|
if (import.meta.hot) {
|
|
94
91
|
import.meta.hot.accept('${virtualStoriesFile}', (newModule) => {
|
|
95
92
|
// importFn has changed so we need to patch the new one in
|
|
96
|
-
|
|
93
|
+
window.__STORYBOOK_PREVIEW__.onStoriesChanged({ importFn: newModule.importFn });
|
|
97
94
|
});
|
|
98
95
|
|
|
99
96
|
import.meta.hot.accept(${JSON.stringify(relativePreviewAnnotations)}, ([...newConfigEntries]) => {
|
|
100
97
|
const newGetProjectAnnotations = () => composeConfigs(newConfigEntries);
|
|
101
98
|
|
|
102
99
|
// getProjectAnnotations has changed so we need to patch the new one in
|
|
103
|
-
|
|
100
|
+
window.__STORYBOOK_PREVIEW__.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
|
|
104
101
|
});
|
|
105
102
|
}`.trim();return`
|
|
106
103
|
import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
|
|
@@ -113,18 +110,17 @@ var __require=(x=>typeof require!="undefined"?require:typeof Proxy!="undefined"?
|
|
|
113
110
|
return composeConfigs(configs);
|
|
114
111
|
}
|
|
115
112
|
|
|
116
|
-
const preview = new PreviewWeb();
|
|
117
113
|
|
|
118
|
-
window.__STORYBOOK_PREVIEW__ =
|
|
119
|
-
|
|
120
|
-
window.
|
|
121
|
-
|
|
122
|
-
|
|
114
|
+
window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
|
|
115
|
+
|
|
116
|
+
window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
|
|
117
|
+
window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
|
|
118
|
+
window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
|
|
123
119
|
|
|
124
120
|
${generateHMRHandler(frameworkName)};
|
|
125
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`
|
|
126
122
|
const importers = {
|
|
127
|
-
${stories.map(file=>{let ext=path3.extname(file),relativePath=normalizePath2(path3.relative(process.cwd(),file));return[".js",".jsx",".ts",".tsx",".mdx"].includes(ext)||logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`),` '${toImportPath(relativePath)}': async () => import('/@fs/${file}')`}).join(`,
|
|
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(`,
|
|
128
124
|
`)}
|
|
129
125
|
};
|
|
130
126
|
|
|
@@ -163,4 +159,4 @@ var __require=(x=>typeof require!="undefined"?require:typeof Proxy!="undefined"?
|
|
|
163
159
|
addons.setServerChannel(serverChannel);
|
|
164
160
|
window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
|
|
165
161
|
}
|
|
166
|
-
`.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),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/react-vite"&&plugins.push(viteReact({exclude:[/\.stories\.([tj])sx?$/,/node_modules/,/\.([tj])sx?$/]})),frameworkName==="@storybook/preact-vite"&&plugins.push(__require("@preact/preset-vite").default()),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/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","global","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{entries:stories,include:include2}}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=(plugins=[],namesToRemove)=>plugins.map(plugin=>Array.isArray(plugin)?withoutVitePlugins(plugin,namesToRemove):plugin&&"name"in plugin&&namesToRemove.includes(plugin.name)?!1:plugin);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(e){try{return await server.close()}catch{console.warn("unable to close vite server")}throw e}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,start,withoutVitePlugins};
|
|
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)}import{join as join2}from"path";import{init,parse as parse2}from"es-module-lexer";import MagicString3 from"magic-string";import{emptyDir,ensureDir,ensureFile,writeFile}from"fs-extra";import{mergeAlias}from"vite";var escapeKeys=key=>key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),defaultImportRegExp="import ([^*{}]+) from",replacementMap=new Map([["import ","const "],["import{","const {"],["* as ",""],[" as ",": "],[" from "," = "],["}from","} ="]]);async function externalGlobalsPlugin(externals){return await init,{name:"storybook:external-globals-plugin",enforce:"post",async config(config,{command}){if(command!=="serve")return;let newAlias=mergeAlias([],config.resolve?.alias),cachePath=join2(process.cwd(),"node_modules",".cache","vite-plugin-externals");return await ensureDir(cachePath),await emptyDir(cachePath),await Promise.all(Object.keys(externals).map(async externalKey=>{let externalCachePath=join2(cachePath,`${externalKey}.js`);newAlias.push({find:new RegExp(`^${externalKey}$`),replacement:externalCachePath}),await ensureFile(externalCachePath),await writeFile(externalCachePath,`module.exports = ${externals[externalKey]};`)})),{resolve:{alias:newAlias}}},async transform(code,id){let globalsList=Object.keys(externals);if(globalsList.every(glob2=>!code.includes(glob2)))return;let[imports]=parse2(code),src=new MagicString3(code);return imports.forEach(({n:path6,ss:startPosition,se:endPosition})=>{let packageName=path6;if(packageName&&globalsList.includes(packageName)){let importStatement=src.slice(startPosition,endPosition),transformedImport=rewriteImport(importStatement,externals,packageName);src.update(startPosition,endPosition,transformedImport)}}),{code:src.toString(),map:src.generateMap({source:id,includeContent:!0,hires:!0})}}}}function getDefaultImportReplacement(match){let matched=match.match(defaultImportRegExp);return matched&&`const {default: ${matched[1]}} =`}function getSearchRegExp(packageName){let staticKeys=[...replacementMap.keys()].map(escapeKeys),packageNameLiteral=`.${packageName}.`,dynamicImportExpression=`await import\\(.${packageName}.\\)`,lookup=[defaultImportRegExp,...staticKeys,packageNameLiteral,dynamicImportExpression];return new RegExp(`(${lookup.join("|")})`,"g")}function rewriteImport(importStatement,globs,packageName){let search=getSearchRegExp(packageName);return importStatement.replace(search,match=>replacementMap.get(match)??getDefaultImportReplacement(match)??globs[packageName])}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,{viteConfigPath}=await getBuilderOptions(options),{config:{build:buildProperty=void 0,...userConfig}={}}=await loadConfigFromFile(configEnv,viteConfigPath)??{},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")}},await externalGlobalsPlugin(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=join3(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=join3(previewResolvedDir,"dist"),previewDirTarget=join3(options.outputDir||"","sb-preview"),previewFiles=fs2.copy(previewDirOrigin,previewDirTarget,{filter:src=>{let{ext}=parse3(src);return ext?ext===".mjs":!0}}),[out]=await Promise.all([viteCompilation,previewFiles]);return out};export{bail,build2 as build,hasVitePlugins,start,withoutVitePlugins};
|
package/input/iframe.html
CHANGED
|
@@ -1,31 +1,41 @@
|
|
|
1
1
|
<!DOCTYPE html>
|
|
2
2
|
<!--suppress HtmlUnknownTarget -->
|
|
3
3
|
<html lang="en">
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
</
|
|
4
|
+
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8" />
|
|
7
|
+
<title>Storybook</title>
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
9
|
+
|
|
10
|
+
<link rel="preload" href="./sb-common-assets/nunito-sans-regular.woff2" as="font" type="font/woff2" crossorigin />
|
|
11
|
+
<link rel="preload" href="./sb-common-assets/nunito-sans-italic.woff2" as="font" type="font/woff2" crossorigin />
|
|
12
|
+
<link rel="preload" href="./sb-common-assets/nunito-sans-bold.woff2" as="font" type="font/woff2" crossorigin />
|
|
13
|
+
<link rel="preload" href="./sb-common-assets/nunito-sans-bold-italic.woff2" as="font" type="font/woff2" crossorigin />
|
|
14
|
+
<link rel="stylesheet" href="./sb-common-assets/fonts.css" />
|
|
15
|
+
|
|
16
|
+
<script>
|
|
17
|
+
window.CONFIG_TYPE = '[CONFIG_TYPE HERE]';
|
|
18
|
+
window.LOGLEVEL = '[LOGLEVEL HERE]';
|
|
19
|
+
window.FRAMEWORK_OPTIONS = '[FRAMEWORK_OPTIONS HERE]';
|
|
20
|
+
window.CHANNEL_OPTIONS = '[CHANNEL_OPTIONS HERE]';
|
|
21
|
+
window.FEATURES = '[FEATURES HERE]';
|
|
22
|
+
window.STORIES = '[STORIES HERE]';
|
|
23
|
+
window.DOCS_OPTIONS = '[DOCS_OPTIONS HERE]';
|
|
24
|
+
window.SERVER_CHANNEL_URL = '[SERVER_CHANNEL_URL HERE]';
|
|
25
|
+
|
|
26
|
+
// We do this so that "module && module.hot" etc. in Storybook source code
|
|
27
|
+
// doesn't fail (it will simply be disabled)
|
|
28
|
+
window.module = undefined;
|
|
29
|
+
</script>
|
|
30
|
+
<!-- [HEAD HTML SNIPPET HERE] -->
|
|
31
|
+
</head>
|
|
32
|
+
|
|
33
|
+
<body>
|
|
34
|
+
<!-- [BODY HTML SNIPPET HERE] -->
|
|
35
|
+
<div id="storybook-root"></div>
|
|
36
|
+
<div id="storybook-docs"></div>
|
|
37
|
+
<script type="module" src="./sb-preview/runtime.mjs"></script>
|
|
38
|
+
<script type="module" src="/virtual:/@storybook/builder-vite/vite-app.js"></script>
|
|
39
|
+
</body>
|
|
40
|
+
|
|
41
|
+
</html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storybook/builder-vite",
|
|
3
|
-
"version": "7.0.0-beta.
|
|
3
|
+
"version": "7.0.0-beta.41",
|
|
4
4
|
"description": "A plugin to run and build Storybooks with Vite",
|
|
5
5
|
"homepage": "https://github.com/storybookjs/storybook/tree/main/code/lib/builder-vite/#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"author": "Eirik Sletteberg",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": {
|
|
22
|
+
"node": "./dist/index.js",
|
|
22
23
|
"require": "./dist/index.js",
|
|
23
24
|
"import": "./dist/index.mjs",
|
|
24
25
|
"types": "./dist/index.d.ts"
|
|
@@ -33,6 +34,7 @@
|
|
|
33
34
|
"files": [
|
|
34
35
|
"dist/**/*",
|
|
35
36
|
"input/**/*",
|
|
37
|
+
"README.md",
|
|
36
38
|
"*.js",
|
|
37
39
|
"*.d.ts"
|
|
38
40
|
],
|
|
@@ -41,43 +43,46 @@
|
|
|
41
43
|
"prep": "../../../scripts/prepare/bundle.ts"
|
|
42
44
|
},
|
|
43
45
|
"dependencies": {
|
|
44
|
-
"@
|
|
45
|
-
"@storybook/
|
|
46
|
-
"@storybook/
|
|
47
|
-
"@storybook/
|
|
46
|
+
"@storybook/channel-postmessage": "7.0.0-beta.41",
|
|
47
|
+
"@storybook/channel-websocket": "7.0.0-beta.41",
|
|
48
|
+
"@storybook/client-logger": "7.0.0-beta.41",
|
|
49
|
+
"@storybook/core-common": "7.0.0-beta.41",
|
|
50
|
+
"@storybook/csf-plugin": "7.0.0-beta.41",
|
|
48
51
|
"@storybook/mdx2-csf": "next",
|
|
49
|
-
"@storybook/node-logger": "7.0.0-beta.
|
|
50
|
-
"@storybook/preview": "7.0.0-beta.
|
|
51
|
-
"@storybook/preview-api": "7.0.0-beta.
|
|
52
|
-
"@storybook/types": "7.0.0-beta.
|
|
53
|
-
"@vitejs/plugin-react": "^2.0.0",
|
|
52
|
+
"@storybook/node-logger": "7.0.0-beta.41",
|
|
53
|
+
"@storybook/preview": "7.0.0-beta.41",
|
|
54
|
+
"@storybook/preview-api": "7.0.0-beta.41",
|
|
55
|
+
"@storybook/types": "7.0.0-beta.41",
|
|
54
56
|
"browser-assert": "^1.2.1",
|
|
55
57
|
"es-module-lexer": "^0.9.3",
|
|
56
58
|
"express": "^4.17.3",
|
|
57
|
-
"fs-extra": "^
|
|
59
|
+
"fs-extra": "^11.1.0",
|
|
58
60
|
"glob": "^7.2.0",
|
|
59
61
|
"glob-promise": "^4.2.0",
|
|
60
|
-
"magic-string": "^0.
|
|
62
|
+
"magic-string": "^0.27.0",
|
|
61
63
|
"rollup": "^2.25.0 || ^3.3.0",
|
|
62
|
-
"
|
|
63
|
-
"slash": "^3.0.0",
|
|
64
|
-
"vite": "^3.0.0||^4.0.0"
|
|
64
|
+
"slash": "^3.0.0"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@types/express": "^4.17.13",
|
|
68
68
|
"@types/node": "^16.0.0",
|
|
69
69
|
"rollup": "^3.0.0",
|
|
70
70
|
"typescript": "~4.9.3",
|
|
71
|
-
"vite": "^4.0.
|
|
71
|
+
"vite": "^4.0.4"
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"@preact/preset-vite": "*",
|
|
75
|
+
"typescript": ">= 4.3.x",
|
|
76
|
+
"vite": "^3.0.0 || ^4.0.0",
|
|
75
77
|
"vite-plugin-glimmerx": "*"
|
|
76
78
|
},
|
|
77
79
|
"peerDependenciesMeta": {
|
|
78
80
|
"@preact/preset-vite": {
|
|
79
81
|
"optional": true
|
|
80
82
|
},
|
|
83
|
+
"typescript": {
|
|
84
|
+
"optional": true
|
|
85
|
+
},
|
|
81
86
|
"vite-plugin-glimmerx": {
|
|
82
87
|
"optional": true
|
|
83
88
|
}
|
|
@@ -91,5 +96,5 @@
|
|
|
91
96
|
],
|
|
92
97
|
"platform": "node"
|
|
93
98
|
},
|
|
94
|
-
"gitHead": "
|
|
99
|
+
"gitHead": "b73df3011fe6ccda407ebb6ed15b80e0d01d4230"
|
|
95
100
|
}
|