@modern-js/storybook-builder 0.0.0-next-20230913035856

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 (78) hide show
  1. package/.eslintrc.js +7 -0
  2. package/.turbo/turbo-build.log +6 -0
  3. package/CHANGELOG.md +24 -0
  4. package/LICENSE +21 -0
  5. package/dist/cjs/addons/components/modern.js +65 -0
  6. package/dist/cjs/addons/constants.js +11 -0
  7. package/dist/cjs/addons/index.js +20 -0
  8. package/dist/cjs/addons/preset/preview.js +14 -0
  9. package/dist/cjs/addons/type.js +4 -0
  10. package/dist/cjs/addons/withPluginRuntime.js +20 -0
  11. package/dist/cjs/build.js +109 -0
  12. package/dist/cjs/core.js +40 -0
  13. package/dist/cjs/docgen/actualNameHandler.js +34 -0
  14. package/dist/cjs/docgen/index.js +74 -0
  15. package/dist/cjs/docgen/loader.js +37 -0
  16. package/dist/cjs/docgen/process.js +39 -0
  17. package/dist/cjs/index.js +35 -0
  18. package/dist/cjs/plugin-storybook.js +316 -0
  19. package/dist/cjs/preset.js +61 -0
  20. package/dist/cjs/types.js +11 -0
  21. package/dist/cjs/utils.js +142 -0
  22. package/dist/esm/addons/components/modern.js +44 -0
  23. package/dist/esm/addons/constants.js +1 -0
  24. package/dist/esm/addons/index.js +5 -0
  25. package/dist/esm/addons/preset/preview.js +4 -0
  26. package/dist/esm/addons/type.js +1 -0
  27. package/dist/esm/addons/withPluginRuntime.js +10 -0
  28. package/dist/esm/build.js +83 -0
  29. package/dist/esm/core.js +30 -0
  30. package/dist/esm/docgen/actualNameHandler.js +24 -0
  31. package/dist/esm/docgen/index.js +54 -0
  32. package/dist/esm/docgen/loader.js +26 -0
  33. package/dist/esm/docgen/process.js +28 -0
  34. package/dist/esm/index.js +6 -0
  35. package/dist/esm/plugin-storybook.js +296 -0
  36. package/dist/esm/preset.js +36 -0
  37. package/dist/esm/types.js +1 -0
  38. package/dist/esm/utils.js +95 -0
  39. package/dist/types/addons/components/modern.d.ts +5 -0
  40. package/dist/types/addons/constants.d.ts +1 -0
  41. package/dist/types/addons/index.d.ts +2 -0
  42. package/dist/types/addons/preset/preview.d.ts +1 -0
  43. package/dist/types/addons/type.d.ts +4 -0
  44. package/dist/types/addons/withPluginRuntime.d.ts +2 -0
  45. package/dist/types/build.d.ts +7 -0
  46. package/dist/types/core.d.ts +4 -0
  47. package/dist/types/docgen/actualNameHandler.d.ts +14 -0
  48. package/dist/types/docgen/index.d.ts +9 -0
  49. package/dist/types/docgen/loader.d.ts +2 -0
  50. package/dist/types/docgen/process.d.ts +10 -0
  51. package/dist/types/index.d.ts +3 -0
  52. package/dist/types/plugin-storybook.d.ts +6 -0
  53. package/dist/types/preset.d.ts +6 -0
  54. package/dist/types/types.d.ts +15 -0
  55. package/dist/types/utils.d.ts +12 -0
  56. package/index.js +24 -0
  57. package/modern.config.js +5 -0
  58. package/package.json +96 -0
  59. package/src/addons/components/modern.tsx +52 -0
  60. package/src/addons/constants.ts +1 -0
  61. package/src/addons/index.ts +8 -0
  62. package/src/addons/preset/preview.ts +3 -0
  63. package/src/addons/type.ts +4 -0
  64. package/src/addons/withPluginRuntime.ts +18 -0
  65. package/src/build.ts +119 -0
  66. package/src/core.ts +51 -0
  67. package/src/docgen/actualNameHandler.ts +57 -0
  68. package/src/docgen/index.ts +100 -0
  69. package/src/docgen/loader.ts +34 -0
  70. package/src/docgen/process.ts +44 -0
  71. package/src/index.ts +7 -0
  72. package/src/plugin-storybook.ts +462 -0
  73. package/src/preset.ts +59 -0
  74. package/src/types.ts +21 -0
  75. package/src/utils.ts +131 -0
  76. package/templates/preview.ejs +54 -0
  77. package/templates/virtualModuleModernEntry.js.handlebars +43 -0
  78. package/tsconfig.json +16 -0
@@ -0,0 +1,316 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for (var name in all)
7
+ Object.defineProperty(target, name, {
8
+ enumerable: true,
9
+ get: all[name]
10
+ });
11
+ }
12
+ _export(exports, {
13
+ finalize: function() {
14
+ return finalize;
15
+ },
16
+ pluginStorybook: function() {
17
+ return pluginStorybook;
18
+ }
19
+ });
20
+ const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
21
+ const _path = require("path");
22
+ const _utils = require("@modern-js/utils");
23
+ const _buildershared = require("@modern-js/builder-shared");
24
+ const _corecommon = require("@storybook/core-common");
25
+ const _globals = require("@storybook/preview/globals");
26
+ const _csfplugin = require("@storybook/csf-plugin");
27
+ const _minimatch = require("minimatch");
28
+ const _utils1 = require("./utils");
29
+ const _docgen = require("./docgen");
30
+ const STORIES_FILENAME = "storybook-stories.js";
31
+ const STORYBOOK_CONFIG_ENTRY = "storybook-config-entry.js";
32
+ const closeFn = [];
33
+ const onClose = (f) => {
34
+ closeFn.push(f);
35
+ };
36
+ async function finalize() {
37
+ await Promise.all([
38
+ closeFn.map((close) => close())
39
+ ]);
40
+ }
41
+ const pluginStorybook = (cwd, options) => {
42
+ return {
43
+ name: "builder-plugin-storybook",
44
+ remove: [
45
+ "builder-plugin-inline"
46
+ ],
47
+ async setup(api) {
48
+ const matchers = await options.presets.apply("stories", [], options);
49
+ const storyPatterns = (0, _corecommon.normalizeStories)(matchers, {
50
+ configDir: options.configDir,
51
+ workingDir: options.configDir
52
+ }).map(({ directory, files }) => {
53
+ const pattern = (0, _path.join)(directory, files);
54
+ const absolutePattern = (0, _path.isAbsolute)(pattern) ? pattern : (0, _path.join)(options.configDir, pattern);
55
+ return absolutePattern;
56
+ });
57
+ api.modifyBuilderConfig(async (builderConfig) => {
58
+ await prepareStorybookModules(api.context.cachePath, cwd, options, builderConfig, storyPatterns);
59
+ await applyDefines(builderConfig, options);
60
+ await applyHTML(builderConfig, options);
61
+ await applyReact(builderConfig, options);
62
+ applyExternals(builderConfig);
63
+ });
64
+ const modifyConfig = async (config) => {
65
+ var _config;
66
+ var _resolve;
67
+ (_resolve = (_config = config).resolve) !== null && _resolve !== void 0 ? _resolve : _config.resolve = {};
68
+ config.resolve.conditionNames = [
69
+ "require",
70
+ "node",
71
+ ...config.resolve.conditionNames || []
72
+ ];
73
+ config.resolve.fullySpecified = false;
74
+ await applyMdxLoader(config, options);
75
+ await applyCsfPlugin(config, options);
76
+ };
77
+ if ("modifyWebpackConfig" in api) {
78
+ api.modifyWebpackConfig(modifyConfig);
79
+ api.modifyWebpackChain(async (chain) => {
80
+ await (0, _docgen.applyDocgenWebpack)(chain, options);
81
+ });
82
+ } else if ("modifyRspackConfig" in api) {
83
+ api.modifyRspackConfig(async (config) => {
84
+ await modifyConfig(config);
85
+ await (0, _docgen.applyDocgenRspack)(config, options);
86
+ });
87
+ }
88
+ }
89
+ };
90
+ };
91
+ async function applyCsfPlugin(config, options) {
92
+ var _addons_find;
93
+ var _config;
94
+ const { presets } = options;
95
+ const addons = await presets.apply("addons", []);
96
+ const { options: { bundler } } = await presets.apply("frameworkOptions");
97
+ var _addons_find_options;
98
+ const docsOptions = (_addons_find_options = (_addons_find = addons.find((a) => [
99
+ a,
100
+ a.name
101
+ ].includes("@storybook/addon-docs"))) === null || _addons_find === void 0 ? void 0 : _addons_find.options) !== null && _addons_find_options !== void 0 ? _addons_find_options : {};
102
+ var _plugins;
103
+ (_plugins = (_config = config).plugins) !== null && _plugins !== void 0 ? _plugins : _config.plugins = [];
104
+ config.plugins.push(bundler === "rspack" ? _csfplugin.unplugin.rspack(docsOptions) : _csfplugin.unplugin.webpack(docsOptions));
105
+ }
106
+ async function prepareStorybookModules(tempDir, cwd, options, builderConfig, storyPatterns) {
107
+ var _builderConfig;
108
+ const mappings = await createStorybookModules(cwd, options, storyPatterns);
109
+ const componentsPath = (0, _utils1.maybeGetAbsolutePath)(`@storybook/components`);
110
+ const routerPath = (0, _utils1.maybeGetAbsolutePath)(`@storybook/router`);
111
+ const themingPath = (0, _utils1.maybeGetAbsolutePath)(`@storybook/theming`);
112
+ const storybookPaths = {
113
+ ...componentsPath ? {
114
+ [`@storybook/components`]: componentsPath
115
+ } : {},
116
+ ...routerPath ? {
117
+ [`@storybook/router`]: routerPath
118
+ } : {},
119
+ ...themingPath ? {
120
+ [`@storybook/theming`]: themingPath
121
+ } : {}
122
+ };
123
+ const [mappingsAlias, write] = await (0, _utils1.virtualModule)(tempDir, cwd, mappings);
124
+ var _source;
125
+ (_source = (_builderConfig = builderConfig).source) !== null && _source !== void 0 ? _source : _builderConfig.source = {};
126
+ builderConfig.source.alias = {
127
+ ...builderConfig.source.alias,
128
+ ...storybookPaths,
129
+ ...mappingsAlias
130
+ };
131
+ const watcher = await watchStories(storyPatterns, cwd, write);
132
+ onClose(async () => {
133
+ await watcher.close();
134
+ });
135
+ }
136
+ async function applyDefines(builderConfig, options) {
137
+ var _builderConfig;
138
+ const { presets } = options;
139
+ const envs = await presets.apply("env");
140
+ var _source;
141
+ (_source = (_builderConfig = builderConfig).source) !== null && _source !== void 0 ? _source : _builderConfig.source = {};
142
+ builderConfig.source.define = {
143
+ ...builderConfig.source.define,
144
+ ...(0, _corecommon.stringifyProcessEnvs)(envs),
145
+ "process.env": JSON.stringify(envs),
146
+ NODE_ENV: JSON.stringify(process.env.NODE_ENV)
147
+ };
148
+ }
149
+ async function applyHTML(builderConfig, options) {
150
+ var _builderConfig;
151
+ const { presets, packageJson, configType, features, previewUrl, serverChannelUrl } = options;
152
+ const [coreOptions, frameworkOptions, logLevel, headHtmlSnippet, bodyHtmlSnippet, template, docsOptions] = await Promise.all([
153
+ presets.apply("core"),
154
+ presets.apply("frameworkOptions"),
155
+ presets.apply("logLevel", void 0),
156
+ presets.apply("previewHead"),
157
+ presets.apply("previewBody"),
158
+ presets.apply("previewMainTemplate"),
159
+ presets.apply("docs")
160
+ ]);
161
+ var _tools;
162
+ (_tools = (_builderConfig = builderConfig).tools) !== null && _tools !== void 0 ? _tools : _builderConfig.tools = {};
163
+ builderConfig.tools.htmlPlugin = {
164
+ ...builderConfig.tools.htmlPlugin,
165
+ template,
166
+ filename: "iframe.html",
167
+ templateParameters: {
168
+ ...builderConfig.tools.htmlPlugin ? builderConfig.tools.htmlPlugin.templateParameters || {} : {},
169
+ version: packageJson.version || "",
170
+ globals: {
171
+ CONFIG_TYPE: configType,
172
+ LOGLEVEL: logLevel,
173
+ FRAMEWORK_OPTIONS: frameworkOptions,
174
+ CHANNEL_OPTIONS: coreOptions.channelOptions,
175
+ FEATURES: features,
176
+ PREVIEW_URL: previewUrl,
177
+ DOCS_OPTIONS: docsOptions,
178
+ SERVER_CHANNEL_URL: serverChannelUrl
179
+ },
180
+ headHtmlSnippet,
181
+ bodyHtmlSnippet
182
+ },
183
+ inject: false
184
+ };
185
+ }
186
+ async function applyMdxLoader(config, options) {
187
+ var _mdxPluginOptions, _mdxPluginOptions_mdxCompileOptions, _mdxPluginOptions1, _options_features;
188
+ var _config, _config_module;
189
+ const { presets, mdxPluginOptions } = options;
190
+ const remarkExternalLinks = await Promise.resolve().then(() => /* @__PURE__ */ _interop_require_wildcard._(require("remark-external-links")));
191
+ const remarkSlug = await Promise.resolve().then(() => /* @__PURE__ */ _interop_require_wildcard._(require("remark-slug")));
192
+ var _mdxPluginOptions_mdxCompileOptions_remarkPlugins;
193
+ const mdxLoaderOptions = await presets.apply("mdxLoaderOptions", {
194
+ skipCsf: true,
195
+ mdxCompileOptions: {
196
+ providerImportSource: "@storybook/addon-docs/mdx-react-shim",
197
+ ...(_mdxPluginOptions = mdxPluginOptions) === null || _mdxPluginOptions === void 0 ? void 0 : _mdxPluginOptions.mdxCompileOptions,
198
+ remarkPlugins: [
199
+ remarkSlug,
200
+ remarkExternalLinks,
201
+ ...(_mdxPluginOptions_mdxCompileOptions_remarkPlugins = (_mdxPluginOptions1 = mdxPluginOptions) === null || _mdxPluginOptions1 === void 0 ? void 0 : (_mdxPluginOptions_mdxCompileOptions = _mdxPluginOptions1.mdxCompileOptions) === null || _mdxPluginOptions_mdxCompileOptions === void 0 ? void 0 : _mdxPluginOptions_mdxCompileOptions.remarkPlugins) !== null && _mdxPluginOptions_mdxCompileOptions_remarkPlugins !== void 0 ? _mdxPluginOptions_mdxCompileOptions_remarkPlugins : []
202
+ ]
203
+ }
204
+ });
205
+ const mdxLoader = ((_options_features = options.features) === null || _options_features === void 0 ? void 0 : _options_features.legacyMdx1) ? require.resolve("@storybook/mdx1-csf/loader") : require.resolve("@storybook/mdx2-csf/loader");
206
+ var _module;
207
+ (_module = (_config = config).module) !== null && _module !== void 0 ? _module : _config.module = {};
208
+ var _rules;
209
+ (_rules = (_config_module = config.module).rules) !== null && _rules !== void 0 ? _rules : _config_module.rules = [];
210
+ config.module.rules.push({
211
+ test: /(stories|story)\.mdx$/,
212
+ use: [
213
+ {
214
+ loader: mdxLoader,
215
+ options: {
216
+ ...mdxLoaderOptions,
217
+ skipCsf: false
218
+ }
219
+ }
220
+ ]
221
+ }, {
222
+ test: /\.mdx$/,
223
+ exclude: /(stories|story)\.mdx$/,
224
+ use: [
225
+ {
226
+ loader: mdxLoader,
227
+ options: mdxLoaderOptions
228
+ }
229
+ ]
230
+ });
231
+ }
232
+ function applyExternals(builderConfig) {
233
+ var _builderConfig_output;
234
+ const config = (0, _buildershared.mergeBuilderConfig)({
235
+ output: {
236
+ externals: (_builderConfig_output = builderConfig.output) === null || _builderConfig_output === void 0 ? void 0 : _builderConfig_output.externals
237
+ }
238
+ }, {
239
+ output: {
240
+ externals: _globals.globals
241
+ }
242
+ });
243
+ builderConfig.output = config.output;
244
+ }
245
+ function getStoriesEntryPath(cwd) {
246
+ return (0, _path.resolve)((0, _path.join)(cwd, STORIES_FILENAME));
247
+ }
248
+ function getStoriesConfigPath(cwd) {
249
+ return (0, _path.resolve)((0, _path.join)(cwd, STORYBOOK_CONFIG_ENTRY));
250
+ }
251
+ async function createStorybookModules(cwd, options, storyPatterns) {
252
+ const virtualModuleMappings = {};
253
+ const { presets } = options;
254
+ const storiesEntry = await createStoriesEntry(cwd, storyPatterns);
255
+ virtualModuleMappings[getStoriesEntryPath(cwd)] = storiesEntry;
256
+ const configEntryPath = getStoriesConfigPath(cwd);
257
+ const previewAnnotations = [
258
+ ...(await presets.apply("previewAnnotations", [], options)).map((entry) => {
259
+ if (typeof entry === "object") {
260
+ return entry.absolute;
261
+ }
262
+ return (0, _path.resolve)(cwd, (0, _utils.slash)(entry));
263
+ }),
264
+ (0, _corecommon.loadPreviewOrConfigFile)(options)
265
+ ].filter(Boolean);
266
+ virtualModuleMappings[configEntryPath] = (0, _corecommon.handlebars)(await (0, _corecommon.readTemplate)(require.resolve("@modern-js/storybook-builder/templates/virtualModuleModernEntry.js.handlebars")), {
267
+ storiesFilename: STORIES_FILENAME,
268
+ previewAnnotations
269
+ }).replace(/\\/g, "\\\\");
270
+ return virtualModuleMappings;
271
+ }
272
+ async function createStoriesEntry(cwd, storyPatterns) {
273
+ const stories = (await Promise.all(storyPatterns.map((pattern) => {
274
+ return (0, _utils.globby)((0, _utils.slash)(pattern), {
275
+ followSymbolicLinks: true
276
+ });
277
+ }))).reduce((carry, stories2) => carry.concat(stories2), []);
278
+ return await (0, _utils1.toImportFn)(cwd, stories);
279
+ }
280
+ async function applyReact(config, options) {
281
+ let version = "18.0.0";
282
+ try {
283
+ ({ version } = await Promise.resolve().then(() => /* @__PURE__ */ _interop_require_wildcard._(require("react-dom/package.json"))));
284
+ } catch (_) {
285
+ }
286
+ const { legacyRootApi } = await options.presets.apply("frameworkOptions") || {};
287
+ const isReact18 = version.startsWith("18") || version.startsWith("0.0.0");
288
+ const useReact17 = legacyRootApi !== null && legacyRootApi !== void 0 ? legacyRootApi : !isReact18;
289
+ if (!useReact17) {
290
+ var _config, _config_source;
291
+ var _source;
292
+ (_source = (_config = config).source) !== null && _source !== void 0 ? _source : _config.source = {};
293
+ var _alias;
294
+ (_alias = (_config_source = config.source).alias) !== null && _alias !== void 0 ? _alias : _config_source.alias = {};
295
+ config.source.alias["@storybook/react-dom-shim"] = "@storybook/react-dom-shim/dist/react-18";
296
+ }
297
+ }
298
+ async function watchStories(patterns, cwd, writeModule) {
299
+ const watcher = (0, _utils.watch)(cwd, async ({ changeType, changedFilePath }) => {
300
+ if (changeType !== "add" && changeType !== "unlink") {
301
+ return;
302
+ }
303
+ if (patterns.some((entry) => (0, _minimatch.minimatch)(changedFilePath, entry))) {
304
+ const stories = (await Promise.all(patterns.map((pattern) => {
305
+ return (0, _utils.globby)((0, _utils.slash)(pattern), {
306
+ followSymbolicLinks: true
307
+ });
308
+ }))).reduce((carry, stories2) => carry.concat(stories2), []);
309
+ const newStories = await (0, _utils1.toImportFn)(cwd, stories);
310
+ writeModule(getStoriesEntryPath(cwd), newStories);
311
+ }
312
+ }, [
313
+ /node_modules/
314
+ ]);
315
+ return watcher;
316
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for (var name in all)
7
+ Object.defineProperty(target, name, {
8
+ enumerable: true,
9
+ get: all[name]
10
+ });
11
+ }
12
+ _export(exports, {
13
+ previewMainTemplate: function() {
14
+ return previewMainTemplate;
15
+ },
16
+ entries: function() {
17
+ return entries;
18
+ },
19
+ modern: function() {
20
+ return modern;
21
+ },
22
+ decorators: function() {
23
+ return _preview.decorators;
24
+ }
25
+ });
26
+ const _path = require("path");
27
+ const _build = require("./build");
28
+ const _utils = require("./utils");
29
+ const _preview = require("./addons/preset/preview");
30
+ const previewMainTemplate = () => {
31
+ return require.resolve("@modern-js/storybook-builder/templates/preview.ejs");
32
+ };
33
+ function getStoriesConfigPath(cwd) {
34
+ return (0, _path.resolve)((0, _path.join)(cwd, _utils.STORYBOOK_CONFIG_ENTRY));
35
+ }
36
+ const entries = async (_, options) => {
37
+ const result = [];
38
+ const { bundler } = await (0, _build.getConfig)(options);
39
+ if (options.configType === "DEVELOPMENT") {
40
+ result.push(...[
41
+ `${require.resolve("webpack-hot-middleware/client")}?reload=true&quiet=false&noInfo=${options.quiet}`,
42
+ bundler === "rspack" ? require.resolve("@rspack/dev-client/react-refresh-entry") : null
43
+ ].filter(Boolean));
44
+ }
45
+ result.push(getStoriesConfigPath(process.cwd()));
46
+ return result;
47
+ };
48
+ const modern = (builderConfig, options) => {
49
+ var _builderConfig_output;
50
+ return {
51
+ ...builderConfig,
52
+ output: {
53
+ ...builderConfig.output,
54
+ disableInlineRuntimeChunk: true,
55
+ distPath: {
56
+ ...(_builderConfig_output = builderConfig.output) === null || _builderConfig_output === void 0 ? void 0 : _builderConfig_output.distPath,
57
+ root: options.outputDir
58
+ }
59
+ }
60
+ };
61
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "defineConfig", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return _cli.defineConfig;
9
+ }
10
+ });
11
+ const _cli = require("@modern-js/builder/cli");
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for (var name in all)
7
+ Object.defineProperty(target, name, {
8
+ enumerable: true,
9
+ get: all[name]
10
+ });
11
+ }
12
+ _export(exports, {
13
+ VIRTUAL_MODULE_BASE: function() {
14
+ return VIRTUAL_MODULE_BASE;
15
+ },
16
+ STORIES_FILENAME: function() {
17
+ return STORIES_FILENAME;
18
+ },
19
+ STORYBOOK_CONFIG_ENTRY: function() {
20
+ return STORYBOOK_CONFIG_ENTRY;
21
+ },
22
+ requireResolve: function() {
23
+ return requireResolve;
24
+ },
25
+ getProvider: function() {
26
+ return getProvider;
27
+ },
28
+ virtualModule: function() {
29
+ return virtualModule;
30
+ },
31
+ toImportFn: function() {
32
+ return toImportFn;
33
+ },
34
+ getAbsolutePath: function() {
35
+ return getAbsolutePath;
36
+ },
37
+ maybeGetAbsolutePath: function() {
38
+ return maybeGetAbsolutePath;
39
+ },
40
+ runWithErrorMsg: function() {
41
+ return runWithErrorMsg;
42
+ },
43
+ isDev: function() {
44
+ return isDev;
45
+ }
46
+ });
47
+ const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
48
+ const _path = /* @__PURE__ */ _interop_require_wildcard._(require("path"));
49
+ const _nodemodule = require("node:module");
50
+ const _utils = require("@modern-js/utils");
51
+ const VIRTUAL_MODULE_BASE = ".MODERN_STORYBOOK";
52
+ const STORIES_FILENAME = "storybook-stories.js";
53
+ const STORYBOOK_CONFIG_ENTRY = "storybook-config-entry.js";
54
+ const requireResolve = (importer, path) => {
55
+ const require1 = (0, _nodemodule.createRequire)(importer);
56
+ require1.resolve(path);
57
+ };
58
+ async function getProvider(bundler, builderConfig) {
59
+ try {
60
+ if (bundler === "webpack") {
61
+ const { builderWebpackProvider } = await Promise.resolve().then(() => /* @__PURE__ */ _interop_require_wildcard._(require("@modern-js/builder-webpack-provider")));
62
+ return builderWebpackProvider({
63
+ builderConfig
64
+ });
65
+ } else {
66
+ const { builderRspackProvider } = await Promise.resolve().then(() => /* @__PURE__ */ _interop_require_wildcard._(require("@modern-js/builder-rspack-provider")));
67
+ return builderRspackProvider({
68
+ builderConfig
69
+ });
70
+ }
71
+ } catch (e) {
72
+ _utils.logger.error(`Cannot find provider, you need to install @modern-js/builder-${bundler}-provider first`);
73
+ }
74
+ }
75
+ async function virtualModule(tempDir, cwd, virtualModuleMap) {
76
+ _utils.fs.ensureDirSync(tempDir);
77
+ const alias = {};
78
+ await Promise.all(Reflect.ownKeys(virtualModuleMap).map((k) => {
79
+ const virtualPath = k;
80
+ const relativePath = _path.default.relative(cwd, virtualPath);
81
+ const realPath = _path.default.join(tempDir, relativePath);
82
+ alias[virtualPath] = realPath;
83
+ return _utils.fs.writeFile(realPath, virtualModuleMap[virtualPath]);
84
+ }));
85
+ return [
86
+ alias,
87
+ (virtualPath, content) => {
88
+ const relativePath = _path.default.relative(cwd, virtualPath);
89
+ const realPath = _path.default.join(tempDir, relativePath);
90
+ _utils.fs.writeFileSync(realPath, content);
91
+ }
92
+ ];
93
+ }
94
+ async function toImportFn(cwd, stories) {
95
+ const objectEntries = stories.map((file) => {
96
+ const ext = _path.default.extname(file);
97
+ const relativePath = _path.default.relative(cwd, file);
98
+ if (![
99
+ ".js",
100
+ ".jsx",
101
+ ".ts",
102
+ ".tsx",
103
+ ".mdx"
104
+ ].includes(ext)) {
105
+ _utils.logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`);
106
+ }
107
+ return ` '${toImportPath(relativePath)}': async () => import('${file}')`;
108
+ });
109
+ return `
110
+ const importers = {
111
+ ${objectEntries.join(",\n")}
112
+ };
113
+
114
+ export async function importFn(path) {
115
+ return importers[path]();
116
+ }
117
+ `;
118
+ }
119
+ function toImportPath(relativePath) {
120
+ return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
121
+ }
122
+ function getAbsolutePath(input) {
123
+ return (0, _path.dirname)(require.resolve((0, _path.join)(input, "package.json")));
124
+ }
125
+ function maybeGetAbsolutePath(input) {
126
+ try {
127
+ return getAbsolutePath(input);
128
+ } catch (e) {
129
+ return false;
130
+ }
131
+ }
132
+ async function runWithErrorMsg(op, msg) {
133
+ try {
134
+ return await op();
135
+ } catch (e) {
136
+ _utils.logger.error(msg);
137
+ console.error(e);
138
+ }
139
+ }
140
+ function isDev() {
141
+ return process.env.NODE_ENV === "development";
142
+ }
@@ -0,0 +1,44 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createApp } from "@modern-js/runtime";
3
+ import router from "@modern-js/runtime/router";
4
+ import state from "@modern-js/runtime/model";
5
+ export const WrapProviders = (storyFn, config) => {
6
+ const App = createApp({
7
+ plugins: resolvePlugins(config.modernConfigRuntime)
8
+ })(storyFn);
9
+ return /* @__PURE__ */ _jsx(App, {});
10
+ };
11
+ const allowedRuntimeAPI = {
12
+ router: "router",
13
+ state: "state"
14
+ };
15
+ const allowedRuntimeAPIValues = Object.values(allowedRuntimeAPI);
16
+ export const resolvePlugins = (runtime) => {
17
+ const plugins = [];
18
+ if (!runtime) {
19
+ return plugins;
20
+ }
21
+ Object.keys(runtime).forEach((api) => {
22
+ if (allowedRuntimeAPIValues.includes(api)) {
23
+ if (api === allowedRuntimeAPI.state) {
24
+ if (typeof runtime.state === "boolean") {
25
+ if (runtime.state) {
26
+ plugins.push(state({}));
27
+ }
28
+ } else if (typeof runtime.state === "object") {
29
+ plugins.push(state(runtime.state));
30
+ }
31
+ } else if (api === allowedRuntimeAPI.router) {
32
+ plugins.push(router({
33
+ ...{
34
+ serverBase: [
35
+ "/"
36
+ ]
37
+ },
38
+ ...runtime.router
39
+ }));
40
+ }
41
+ }
42
+ });
43
+ return plugins;
44
+ };
@@ -0,0 +1 @@
1
+ export const ADDON_ID = "storybook/modern-runtime";
@@ -0,0 +1,5 @@
1
+ var _module_hot, _module;
2
+ if ((_module = module) === null || _module === void 0 ? void 0 : (_module_hot = _module.hot) === null || _module_hot === void 0 ? void 0 : _module_hot.decline) {
3
+ module.hot.decline();
4
+ }
5
+ export default {};
@@ -0,0 +1,4 @@
1
+ import { withPluginRuntime } from "../withPluginRuntime";
2
+ export const decorators = [
3
+ withPluginRuntime
4
+ ];
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import { useParameter } from "@storybook/preview-api";
2
+ import { WrapProviders } from "./components/modern";
3
+ export const withPluginRuntime = (storyFn) => {
4
+ const modernConfigRuntime = useParameter("modernConfigRuntime");
5
+ const modernConfigDesignToken = useParameter("modernConfigDesignToken");
6
+ return WrapProviders(storyFn, {
7
+ modernConfigRuntime: modernConfigRuntime || {},
8
+ modernConfigDesignToken
9
+ });
10
+ };
@@ -0,0 +1,83 @@
1
+ import { dirname, join, parse } from "path";
2
+ import webpackDevMiddleware from "@modern-js/utils/webpack-dev-middleware";
3
+ import webpackHotMiddleware from "webpack-hot-middleware";
4
+ import serveStatic from "serve-static";
5
+ import { fs } from "@modern-js/utils";
6
+ import { getCompiler } from "./core";
7
+ import { finalize } from "./plugin-storybook";
8
+ export const getConfig = async (options) => {
9
+ var _frameworkOptions;
10
+ const { presets } = options;
11
+ const frameworkOptions = await presets.apply("frameworkOptions");
12
+ return ((_frameworkOptions = frameworkOptions) === null || _frameworkOptions === void 0 ? void 0 : _frameworkOptions.options) || {};
13
+ };
14
+ export const build = async ({ options }) => {
15
+ const config = await getConfig(options);
16
+ const compiler = await getCompiler(process.cwd(), config, options);
17
+ const previewResolvedDir = dirname(require.resolve("@storybook/preview/package.json"));
18
+ const previewDirOrigin = join(previewResolvedDir, "dist");
19
+ const previewDirTarget = join(options.outputDir || "", `sb-preview`);
20
+ const previewFiles = fs.copy(previewDirOrigin, previewDirTarget, {
21
+ filter: (src) => {
22
+ const { ext } = parse(src);
23
+ if (ext) {
24
+ return ext === ".js";
25
+ }
26
+ return true;
27
+ }
28
+ });
29
+ const compilation = new Promise((resolve, reject) => {
30
+ compiler.run((err, stats2) => {
31
+ if (err) {
32
+ reject(err);
33
+ } else {
34
+ resolve(stats2);
35
+ }
36
+ });
37
+ });
38
+ const [stats] = await Promise.all([
39
+ compilation,
40
+ previewFiles
41
+ ]);
42
+ return stats;
43
+ };
44
+ export const start = async ({ options, router, startTime }) => {
45
+ var _config_builderConfig_tools_devServer_devMiddleware, _config_builderConfig_tools_devServer, _config_builderConfig_tools, _config_builderConfig;
46
+ const previewResolvedDir = dirname(require.resolve("@storybook/preview/package.json"));
47
+ const previewDirOrigin = join(previewResolvedDir, "dist");
48
+ router.use(`/sb-preview`, serveStatic(previewDirOrigin, {
49
+ immutable: true,
50
+ maxAge: "5m"
51
+ }));
52
+ const config = await getConfig(options);
53
+ const compiler = await getCompiler(process.cwd(), config, options);
54
+ const middleware = webpackDevMiddleware(compiler, {
55
+ writeToDisk: ((_config_builderConfig = config.builderConfig) === null || _config_builderConfig === void 0 ? void 0 : (_config_builderConfig_tools = _config_builderConfig.tools) === null || _config_builderConfig_tools === void 0 ? void 0 : (_config_builderConfig_tools_devServer = _config_builderConfig_tools.devServer) === null || _config_builderConfig_tools_devServer === void 0 ? void 0 : (_config_builderConfig_tools_devServer_devMiddleware = _config_builderConfig_tools_devServer.devMiddleware) === null || _config_builderConfig_tools_devServer_devMiddleware === void 0 ? void 0 : _config_builderConfig_tools_devServer_devMiddleware.writeToDisk) || true,
56
+ // builder can log errors, so not using dev-middleware logs
57
+ stats: false
58
+ });
59
+ router.use(middleware);
60
+ router.use(webpackHotMiddleware(compiler, {
61
+ log: false
62
+ }));
63
+ const stats = await new Promise((resolve) => {
64
+ middleware.waitUntilValid((stats2) => {
65
+ resolve(stats2);
66
+ });
67
+ });
68
+ if (!stats) {
69
+ throw new Error("build failed");
70
+ }
71
+ const statsJson = stats.toJson();
72
+ if (statsJson.errors.length > 1) {
73
+ throw stats;
74
+ }
75
+ return {
76
+ bail,
77
+ stats,
78
+ totalTime: process.hrtime(startTime)
79
+ };
80
+ };
81
+ export const bail = async () => {
82
+ await finalize();
83
+ };