@storybook/builder-vite 0.1.38 → 0.1.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.
@@ -1,5 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
+ import { mergeConfig } from 'vite';
3
4
  import { transformIframeHtml } from './transform-iframe-html';
4
5
  import { generateIframeScriptCode } from './codegen-iframe-script';
5
6
  import { generateModernIframeScriptCode } from './codegen-modern-iframe-script';
@@ -64,13 +65,11 @@ export function codeGeneratorPlugin(options: ExtendedOptions): Plugin {
64
65
  require.resolve('react-dom/client', { paths: [config.root || process.cwd()] });
65
66
  } catch (e) {
66
67
  if (isNodeError(e) && e.code === 'MODULE_NOT_FOUND') {
67
- config.resolve = {
68
- ...config.resolve,
68
+ config.resolve = mergeConfig(config.resolve ?? {}, {
69
69
  alias: {
70
- ...config.resolve?.alias,
71
70
  'react-dom/client': path.resolve(__dirname, '..', 'input', 'react-dom-client-placeholder.js'),
72
71
  },
73
- };
72
+ });
74
73
  }
75
74
  }
76
75
  },
@@ -26,6 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.codeGeneratorPlugin = void 0;
27
27
  const fs = __importStar(require("fs"));
28
28
  const path = __importStar(require("path"));
29
+ const vite_1 = require("vite");
29
30
  const transform_iframe_html_1 = require("./transform-iframe-html");
30
31
  const codegen_iframe_script_1 = require("./codegen-iframe-script");
31
32
  const codegen_modern_iframe_script_1 = require("./codegen-modern-iframe-script");
@@ -84,13 +85,11 @@ function codeGeneratorPlugin(options) {
84
85
  }
85
86
  catch (e) {
86
87
  if (isNodeError(e) && e.code === 'MODULE_NOT_FOUND') {
87
- config.resolve = {
88
- ...config.resolve,
88
+ config.resolve = (0, vite_1.mergeConfig)((_a = config.resolve) !== null && _a !== void 0 ? _a : {}, {
89
89
  alias: {
90
- ...(_a = config.resolve) === null || _a === void 0 ? void 0 : _a.alias,
91
90
  'react-dom/client': path.resolve(__dirname, '..', 'input', 'react-dom-client-placeholder.js'),
92
91
  },
93
- };
92
+ });
94
93
  }
95
94
  }
96
95
  },
@@ -1 +1 @@
1
- {"version":3,"file":"code-generator-plugin.js","sourceRoot":"","sources":["../code-generator-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,mEAA8D;AAC9D,mEAAmE;AACnE,iFAAgF;AAChF,uEAAuE;AACvE,uDAA4F;AAC5F,2EAAqE;AAKrE,6DAAoH;AAEpH,SAAgB,mBAAmB,CAAC,OAAwB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;IACzE,IAAI,QAAgB,CAAC;IAErB,qCAAqC;IACrC,OAAO;QACL,IAAI,EAAE,sCAAsC;QAC5C,OAAO,EAAE,KAAK;QACd,eAAe,CAAC,MAAM;YACpB,gEAAgE;YAChE,2CAA2C;YAC3C,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;gBAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,kCAAa,CAAC,CAAC;gBAClE,IAAI,SAAS,EAAE;oBACb,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;iBAChD;gBACD,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,uCAAkB,CAAC,CAAC;gBAC3E,IAAI,aAAa,EAAE;oBACjB,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;iBACpD;YACH,CAAC,CAAC,CAAC;YAEH,yGAAyG;YACzG,8BAA8B;YAC9B,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE;gBAChC,iDAAiD;gBACjD,IAAI,uBAAuB,CAAC,IAAI,C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aACxF;QACH,CAAC;QACD,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,GAAG;YAChC,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE;gBAC/B,OAAO;aACR;YACD,OAAO,IAAA,2CAAmB,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC5C,CAAC;KACF,CAAC;AACJ,CAAC;AAnHD,kDAmHC;AAED,kEAAkE;AAClE,MAAM,WAAW,GAAG,CAAC,KAAc,EAAkC,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { transformIframeHtml } from './transform-iframe-html';\nimport { generateIframeScriptCode } from './codegen-iframe-script';\nimport { generateModernIframeScriptCode } from './codegen-modern-iframe-script';\nimport { generateImportFnScriptCode } from './codegen-importfn-script';\nimport { generateVirtualStoryEntryCode, generatePreviewEntryCode } from './codegen-entries';\nimport { generateAddonSetupCode } from './codegen-set-addon-channel';\n\nimport type { Plugin } from 'vite';\nimport type { ExtendedOptions } from './types';\n\nimport { virtualAddonSetupFile, virtualFileId, virtualPreviewFile, virtualStoriesFile } from './virtual-file-names';\n\nexport function codeGeneratorPlugin(options: ExtendedOptions): Plugin {\n const iframePath = path.resolve(__dirname, '..', 'input', 'iframe.html');\n let iframeId: string;\n\n // noinspection JSUnusedGlobalSymbols\n return {\n name: 'storybook-vite-code-generator-plugin',\n enforce: 'pre',\n configureServer(server) {\n // invalidate the whole vite-app.js script on every file change.\n // (this might be a little too aggressive?)\n server.watcher.on('change', () => {\n const appModule = server.moduleGraph.getModuleById(virtualFileId);\n if (appModule) {\n server.moduleGraph.invalidateModule(appModule);\n }\n const storiesModule = server.moduleGraph.getModuleById(virtualStoriesFile);\n if (storiesModule) {\n server.moduleGraph.invalidateModule(storiesModule);\n }\n });\n\n // Adding new story files is not covered by the change event above. So we need to detect this and trigger\n // HMR to update the importFn.\n server.watcher.on('add', (path) => {\n // TODO maybe use the stories declaration in main\n if (/\\.stories\\.([tj])sx?$/.test(path) || /\\.(story|stories).mdx$/.test(path)) {\n // We need to emit a change event to trigger HMR\n server.watcher.emit('change', virtualStoriesFile);\n }\n });\n },\n config(config, { command }) {\n // If we are building the static distribution, add iframe.html as an entry.\n // In development mode, it's not an entry - instead, we use an express middleware\n // to serve iframe.html. The reason is that Vite's dev server (at the time of writing)\n // does not support virtual files as entry points.\n if (command === 'build') {\n if (!config.build) {\n config.build = {};\n }\n config.build.rollupOptions = {\n ...config.build.rollupOptions,\n input: iframePath,\n };\n }\n\n // Detect if react 18 is installed. If not, alias it to a virtual placeholder file.\n try {\n require.resolve('react-dom/client', { paths: [config.root || process.cwd()] });\n } catch (e) {\n if (isNodeError(e) && e.code === 'MODULE_NOT_FOUND') {\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n 'react-dom/client': path.resolve(__dirname, '..', 'input', 'react-dom-client-placeholder.js'),\n },\n };\n }\n }\n },\n configResolved(config) {\n iframeId = `${config.root}/iframe.html`;\n },\n resolveId(source) {\n if (source === virtualFileId) {\n return virtualFileId;\n } else if (source === iframePath) {\n return iframeId;\n } else if (source === virtualStoriesFile) {\n return virtualStoriesFile;\n } else if (source === virtualPreviewFile) {\n return virtualPreviewFile;\n } else if (source === virtualAddonSetupFile) {\n return virtualAddonSetupFile;\n }\n },\n async load(id) {\n const storyStoreV7 = options.features?.storyStoreV7;\n if (id === virtualStoriesFile) {\n if (storyStoreV7) {\n return generateImportFnScriptCode(options);\n } else {\n return generateVirtualStoryEntryCode(options);\n }\n }\n\n if (id === virtualAddonSetupFile) {\n return generateAddonSetupCode();\n }\n\n if (id === virtualPreviewFile && !storyStoreV7) {\n return generatePreviewEntryCode(options);\n }\n\n if (id === virtualFileId) {\n if (storyStoreV7) {\n return generateModernIframeScriptCode(options);\n } else {\n return generateIframeScriptCode(options);\n }\n }\n\n if (id === iframeId) {\n return fs.readFileSync(path.resolve(__dirname, '..', 'input', 'iframe.html'), 'utf-8');\n }\n },\n async transformIndexHtml(html, ctx) {\n if (ctx.path !== '/iframe.html') {\n return;\n }\n return transformIframeHtml(html, options);\n },\n };\n}\n\n// Refines an error received from 'catch' to be a NodeJS exception\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException => error instanceof Error;\n"]}
1
+ {"version":3,"file":"code-generator-plugin.js","sourceRoot":"","sources":["../code-generator-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,+BAAmC;AACnC,mEAA8D;AAC9D,mEAAmE;AACnE,iFAAgF;AAChF,uEAAuE;AACvE,uDAA4F;AAC5F,2EAAqE;AAKrE,6DAAoH;AAEpH,SAAgB,mBAAmB,CAAC,OAAwB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;IACzE,IAAI,QAAgB,CAAC;IAErB,qCAAqC;IACrC,OAAO;QACL,IAAI,EAAE,sCAAsC;QAC5C,OAAO,EAAE,KAAK;QACd,eAAe,CAAC,MAAM;YACpB,gEAAgE;YAChE,2CAA2C;YAC3C,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;gBAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,kCAAa,CAAC,CAAC;gBAClE,IAAI,SAAS,EAAE;oBACb,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;iBAChD;gBACD,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,uCAAkB,CAAC,CAAC;gBAC3E,IAAI,aAAa,EAAE;oBACjB,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;iBACpD;YACH,CAAC,CAAC,CAAC;YAEH,yGAAyG;YACzG,8BAA8B;YAC9B,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC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AAC,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,OAAO,CAAC,CAAC;aACxF;QACH,CAAC;QACD,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,GAAG;YAChC,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE;gBAC/B,OAAO;aACR;YACD,OAAO,IAAA,2CAAmB,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC5C,CAAC;KACF,CAAC;AACJ,CAAC;AAjHD,kDAiHC;AAED,kEAAkE;AAClE,MAAM,WAAW,GAAG,CAAC,KAAc,EAAkC,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { mergeConfig } from 'vite';\nimport { transformIframeHtml } from './transform-iframe-html';\nimport { generateIframeScriptCode } from './codegen-iframe-script';\nimport { generateModernIframeScriptCode } from './codegen-modern-iframe-script';\nimport { generateImportFnScriptCode } from './codegen-importfn-script';\nimport { generateVirtualStoryEntryCode, generatePreviewEntryCode } from './codegen-entries';\nimport { generateAddonSetupCode } from './codegen-set-addon-channel';\n\nimport type { Plugin } from 'vite';\nimport type { ExtendedOptions } from './types';\n\nimport { virtualAddonSetupFile, virtualFileId, virtualPreviewFile, virtualStoriesFile } from './virtual-file-names';\n\nexport function codeGeneratorPlugin(options: ExtendedOptions): Plugin {\n const iframePath = path.resolve(__dirname, '..', 'input', 'iframe.html');\n let iframeId: string;\n\n // noinspection JSUnusedGlobalSymbols\n return {\n name: 'storybook-vite-code-generator-plugin',\n enforce: 'pre',\n configureServer(server) {\n // invalidate the whole vite-app.js script on every file change.\n // (this might be a little too aggressive?)\n server.watcher.on('change', () => {\n const appModule = server.moduleGraph.getModuleById(virtualFileId);\n if (appModule) {\n server.moduleGraph.invalidateModule(appModule);\n }\n const storiesModule = server.moduleGraph.getModuleById(virtualStoriesFile);\n if (storiesModule) {\n server.moduleGraph.invalidateModule(storiesModule);\n }\n });\n\n // Adding new story files is not covered by the change event above. So we need to detect this and trigger\n // HMR to update the importFn.\n server.watcher.on('add', (path) => {\n // TODO maybe use the stories declaration in main\n if (/\\.stories\\.([tj])sx?$/.test(path) || /\\.(story|stories).mdx$/.test(path)) {\n // We need to emit a change event to trigger HMR\n server.watcher.emit('change', virtualStoriesFile);\n }\n });\n },\n config(config, { command }) {\n // If we are building the static distribution, add iframe.html as an entry.\n // In development mode, it's not an entry - instead, we use an express middleware\n // to serve iframe.html. The reason is that Vite's dev server (at the time of writing)\n // does not support virtual files as entry points.\n if (command === 'build') {\n if (!config.build) {\n config.build = {};\n }\n config.build.rollupOptions = {\n ...config.build.rollupOptions,\n input: iframePath,\n };\n }\n\n // Detect if react 18 is installed. If not, alias it to a virtual placeholder file.\n try {\n require.resolve('react-dom/client', { paths: [config.root || process.cwd()] });\n } catch (e) {\n if (isNodeError(e) && e.code === 'MODULE_NOT_FOUND') {\n config.resolve = mergeConfig(config.resolve ?? {}, {\n alias: {\n 'react-dom/client': path.resolve(__dirname, '..', 'input', 'react-dom-client-placeholder.js'),\n },\n });\n }\n }\n },\n configResolved(config) {\n iframeId = `${config.root}/iframe.html`;\n },\n resolveId(source) {\n if (source === virtualFileId) {\n return virtualFileId;\n } else if (source === iframePath) {\n return iframeId;\n } else if (source === virtualStoriesFile) {\n return virtualStoriesFile;\n } else if (source === virtualPreviewFile) {\n return virtualPreviewFile;\n } else if (source === virtualAddonSetupFile) {\n return virtualAddonSetupFile;\n }\n },\n async load(id) {\n const storyStoreV7 = options.features?.storyStoreV7;\n if (id === virtualStoriesFile) {\n if (storyStoreV7) {\n return generateImportFnScriptCode(options);\n } else {\n return generateVirtualStoryEntryCode(options);\n }\n }\n\n if (id === virtualAddonSetupFile) {\n return generateAddonSetupCode();\n }\n\n if (id === virtualPreviewFile && !storyStoreV7) {\n return generatePreviewEntryCode(options);\n }\n\n if (id === virtualFileId) {\n if (storyStoreV7) {\n return generateModernIframeScriptCode(options);\n } else {\n return generateIframeScriptCode(options);\n }\n }\n\n if (id === iframeId) {\n return fs.readFileSync(path.resolve(__dirname, '..', 'input', 'iframe.html'), 'utf-8');\n }\n },\n async transformIndexHtml(html, ctx) {\n if (ctx.path !== '/iframe.html') {\n return;\n }\n return transformIframeHtml(html, options);\n },\n };\n}\n\n// Refines an error received from 'catch' to be a NodeJS exception\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException => error instanceof Error;\n"]}
@@ -3,6 +3,6 @@ export declare const injectExportOrderPlugin: {
3
3
  enforce: string;
4
4
  transform(code: string, id: string): Promise<{
5
5
  code: string;
6
- map: null;
6
+ map: import("magic-string").SourceMap;
7
7
  } | undefined>;
8
8
  };
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.injectExportOrderPlugin = void 0;
4
7
  const es_module_lexer_1 = require("es-module-lexer");
8
+ const magic_string_1 = __importDefault(require("magic-string"));
5
9
  exports.injectExportOrderPlugin = {
6
10
  name: 'storybook-vite-inject-export-order-plugin',
7
11
  // This should only run after the typescript has been transpiled
@@ -18,10 +22,12 @@ exports.injectExportOrderPlugin = {
18
22
  // user has defined named exports already
19
23
  return;
20
24
  }
25
+ const s = new magic_string_1.default(code);
21
26
  const orderedExports = exports.filter((e) => e !== 'default');
27
+ s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`);
22
28
  return {
23
- code: `${code};\nexport const __namedExportsOrder = ${JSON.stringify(orderedExports)};`,
24
- map: null,
29
+ code: s.toString(),
30
+ map: s.generateMap({ hires: true, source: id }),
25
31
  };
26
32
  },
27
33
  };
@@ -1 +1 @@
1
- {"version":3,"file":"inject-export-order-plugin.js","sourceRoot":"","sources":["../inject-export-order-plugin.ts"],"names":[],"mappings":";;;AAAA,qDAAwC;AAE3B,QAAA,uBAAuB,GAAG;IACrC,IAAI,EAAE,2CAA2C;IACjD,gEAAgE;IAChE,OAAO,EAAE,MAAM;IACf,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,EAAU;QACtC,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;YACzE,OAAO;SACR;QACD,iFAAiF;QACjF,uEAAuE;QACvE,kDAAkD;QAClD,MAAM,CAAC,EAAE,OAAO,CAAC,GAAG,MAAM,IAAA,uBAAK,EAAC,IAAI,CAAC,CAAC;QAEtC,IAAI,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE;YAC3C,yCAAyC;YACzC,OAAO;SACR;QAED,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;QAE9D,OAAO;YACL,IAAI,EAAE,GAAG,IAAI,yCAAyC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,GAAG;YACvF,GAAG,EAAE,IAAI;SACV,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import { parse } from 'es-module-lexer';\n\nexport const injectExportOrderPlugin = {\n name: 'storybook-vite-inject-export-order-plugin',\n // This should only run after the typescript has been transpiled\n enforce: 'post',\n async transform(code: string, id: string) {\n if (!/\\.stories\\.([tj])sx?$/.test(id) && !/(stories|story).mdx$/.test(id)) {\n return;\n }\n // TODO: Maybe convert `injectExportOrderPlugin` to function that returns object,\n // and run `await init;` once and then call `parse()` without `await`,\n // instead of calling `await parse()` every time.\n const [, exports] = await parse(code);\n\n if (exports.includes('__namedExportsOrder')) {\n // user has defined named exports already\n return;\n }\n\n const orderedExports = exports.filter((e) => e !== 'default');\n\n return {\n code: `${code};\\nexport const __namedExportsOrder = ${JSON.stringify(orderedExports)};`,\n map: null,\n };\n },\n};\n"]}
1
+ {"version":3,"file":"inject-export-order-plugin.js","sourceRoot":"","sources":["../inject-export-order-plugin.ts"],"names":[],"mappings":";;;;;;AAAA,qDAAwC;AACxC,gEAAuC;AAE1B,QAAA,uBAAuB,GAAG;IACrC,IAAI,EAAE,2CAA2C;IACjD,gEAAgE;IAChE,OAAO,EAAE,MAAM;IACf,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,EAAU;QACtC,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;YACzE,OAAO;SACR;QACD,iFAAiF;QACjF,uEAAuE;QACvE,kDAAkD;QAClD,MAAM,CAAC,EAAE,OAAO,CAAC,GAAG,MAAM,IAAA,uBAAK,EAAC,IAAI,CAAC,CAAC;QAEtC,IAAI,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE;YAC3C,yCAAyC;YACzC,OAAO;SACR;QACD,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,IAAI,CAAC,CAAC;QAChC,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;QAC9D,CAAC,CAAC,MAAM,CAAC,uCAAuC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QACnF,OAAO;YACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;YAClB,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;SAChD,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import { parse } from 'es-module-lexer';\nimport MagicString from 'magic-string';\n\nexport const injectExportOrderPlugin = {\n name: 'storybook-vite-inject-export-order-plugin',\n // This should only run after the typescript has been transpiled\n enforce: 'post',\n async transform(code: string, id: string) {\n if (!/\\.stories\\.([tj])sx?$/.test(id) && !/(stories|story).mdx$/.test(id)) {\n return;\n }\n // TODO: Maybe convert `injectExportOrderPlugin` to function that returns object,\n // and run `await init;` once and then call `parse()` without `await`,\n // instead of calling `await parse()` every time.\n const [, exports] = await parse(code);\n\n if (exports.includes('__namedExportsOrder')) {\n // user has defined named exports already\n return;\n }\n const s = new MagicString(code);\n const orderedExports = exports.filter((e) => e !== 'default');\n s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`);\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n },\n};\n"]}
@@ -64,15 +64,21 @@ function mdxPlugin(options) {
64
64
  p.name === 'vite:react-jsx');
65
65
  reactRefresh = reactRefreshPlugins.find((p) => p.transform);
66
66
  },
67
- async transform(code, id, options) {
68
- if (id.endsWith('.mdx')) {
67
+ async transform(src, id, options) {
68
+ if (id.match(/\.mdx?$/)) {
69
69
  // @ts-ignore
70
70
  const { compile } = (features === null || features === void 0 ? void 0 : features.previewMdx2)
71
71
  ? await Promise.resolve().then(() => __importStar(require('@storybook/mdx2-csf')))
72
72
  : await Promise.resolve().then(() => __importStar(require('@storybook/mdx1-csf')));
73
- const mdxCode = String(await compile(code, { skipCsf: !isStorybookMdx(id) }));
73
+ const mdxCode = String(await compile(src, { skipCsf: !isStorybookMdx(id) }));
74
74
  const modifiedCode = injectRenderer(mdxCode, Boolean(features === null || features === void 0 ? void 0 : features.previewMdx2));
75
- return reactRefresh === null || reactRefresh === void 0 ? void 0 : reactRefresh.transform.call(this, modifiedCode, `${id}.jsx`, options);
75
+ const result = await (reactRefresh === null || reactRefresh === void 0 ? void 0 : reactRefresh.transform.call(this, modifiedCode, `${id}.jsx`, options));
76
+ if (!result)
77
+ return modifiedCode;
78
+ if (typeof result === 'string')
79
+ return result;
80
+ const { code, map: resultMap } = result;
81
+ return { code, map: !resultMap || typeof resultMap === 'string' ? resultMap : { ...resultMap, sources: [id] } };
76
82
  }
77
83
  },
78
84
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mdx-plugin.js","sourceRoot":"","sources":["../../plugins/mdx-plugin.ts"],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AqB,GAAC;oBACrC,CAAC,CAAC,wDAAa,qBAAqB,GAAC,CAAC;gBAExC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,OAAO,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBAE9E,MAAM,YAAY,GAAG,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,WAAW,CAAC,CAAC,CAAC;gBAE7E,OAAO,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,SAAS,CAAE,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;aAChF;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AArCD,8BAqCC","sourcesContent":["import type { Options } from '@storybook/core-common';\nimport { Plugin } from 'vite';\n\nconst isStorybookMdx = (id: string) => id.endsWith('stories.mdx') || id.endsWith('story.mdx');\n\nfunction injectRenderer(code: string, mdx2: boolean) {\n if (mdx2) {\n return `\n import React from 'react';\n ${code}\n `;\n }\n\n return `\n /* @jsx mdx */\n import React from 'react';\n import { mdx } from '@mdx-js/react';\n ${code}\n `;\n}\n\n/**\n * Storybook uses two different loaders when dealing with MDX:\n *\n * - *stories.mdx and *story.mdx are compiled with the CSF compiler\n * - *.mdx are compiled with the MDX compiler directly\n *\n * @see https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/recipes.md#csf-stories-with-arbitrary-mdx\n */\nexport function mdxPlugin(options: Options): Plugin {\n const { features } = options;\n\n let reactRefresh: Plugin | undefined;\n\n return {\n name: 'storybook-vite-mdx-plugin',\n enforce: 'pre',\n configResolved({ plugins }) {\n // @vitejs/plugin-react-refresh has been upgraded to @vitejs/plugin-react,\n // and the name of the plugin performing `transform` has been changed from 'react-refresh' to 'vite:react-babel',\n // to be compatible, we need to look for both plugin name.\n // We should also look for the other plugins names exported from @vitejs/plugin-react in case there are some internal refactors.\n const reactRefreshPlugins = plugins.filter(\n (p) =>\n p.name === 'react-refresh' ||\n p.name === 'vite:react-babel' ||\n p.name === 'vite:react-refresh' ||\n p.name === 'vite:react-jsx'\n );\n reactRefresh = reactRefreshPlugins.find((p) => p.transform);\n },\n async transform(code, id, options) {\n if (id.endsWith('.mdx')) {\n // @ts-ignore\n const { compile } = features?.previewMdx2\n ? await import('@storybook/mdx2-csf')\n : await import('@storybook/mdx1-csf');\n\n const mdxCode = String(await compile(code, { skipCsf: !isStorybookMdx(id) }));\n\n const modifiedCode = injectRenderer(mdxCode, Boolean(features?.previewMdx2));\n\n return reactRefresh?.transform!.call(this, modifiedCode, `${id}.jsx`, options);\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"mdx-plugin.js","sourceRoot":"","sources":["../../plugins/mdx-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAM,cAAc,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAE9F,SAAS,cAAc,CAAC,IAAY,EAAE,IAAa;IACjD,IAAI,IAAI,EAAE;QACR,OAAO;;aAEE,IAAI;YACL,CAAC;KACV;IAED,OAAO;;;;UAIC,IAAI;SACL,CAAC;AACV,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,SAAS,CAAC,OAAgB;IACxC,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAE7B,IAAI,YAAgC,CAAC;IAErC,OAAO;QACL,IAAI,EAAE,2BAA2B;QACjC,OAAO,EAAE,KAAK;QACd,cAAc,CAAC,EAAE,OAAO,EAAE;YACxB,0EAA0E;YAC1E,iHAAiH;YACjH,0DAA0D;YAC1D,gIAAgI;YAChI,MAAM,mBAAmB,GAAG,OAAO,CAAC,MAAM,CACxC,CAAC,CAAC,EAAE,EAAE,CACJ,CA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AAE,IAAI,EAAE,GAAG,EAAE,CAAC,SAAS,IAAI,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;aACjH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AA7CD,8BA6CC","sourcesContent":["import type { Options } from '@storybook/core-common';\nimport { Plugin } from 'vite';\n\nconst isStorybookMdx = (id: string) => id.endsWith('stories.mdx') || id.endsWith('story.mdx');\n\nfunction injectRenderer(code: string, mdx2: boolean) {\n if (mdx2) {\n return `\n import React from 'react';\n ${code}\n `;\n }\n\n return `\n /* @jsx mdx */\n import React from 'react';\n import { mdx } from '@mdx-js/react';\n ${code}\n `;\n}\n\n/**\n * Storybook uses two different loaders when dealing with MDX:\n *\n * - *stories.mdx and *story.mdx are compiled with the CSF compiler\n * - *.mdx are compiled with the MDX compiler directly\n *\n * @see https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/recipes.md#csf-stories-with-arbitrary-mdx\n */\nexport function mdxPlugin(options: Options): Plugin {\n const { features } = options;\n\n let reactRefresh: Plugin | undefined;\n\n return {\n name: 'storybook-vite-mdx-plugin',\n enforce: 'pre',\n configResolved({ plugins }) {\n // @vitejs/plugin-react-refresh has been upgraded to @vitejs/plugin-react,\n // and the name of the plugin performing `transform` has been changed from 'react-refresh' to 'vite:react-babel',\n // to be compatible, we need to look for both plugin name.\n // We should also look for the other plugins names exported from @vitejs/plugin-react in case there are some internal refactors.\n const reactRefreshPlugins = plugins.filter(\n (p) =>\n p.name === 'react-refresh' ||\n p.name === 'vite:react-babel' ||\n p.name === 'vite:react-refresh' ||\n p.name === 'vite:react-jsx'\n );\n reactRefresh = reactRefreshPlugins.find((p) => p.transform);\n },\n async transform(src, id, options) {\n if (id.match(/\\.mdx?$/)) {\n // @ts-ignore\n const { compile } = features?.previewMdx2\n ? await import('@storybook/mdx2-csf')\n : await import('@storybook/mdx1-csf');\n\n const mdxCode = String(await compile(src, { skipCsf: !isStorybookMdx(id) }));\n\n const modifiedCode = injectRenderer(mdxCode, Boolean(features?.previewMdx2));\n\n const result = await reactRefresh?.transform!.call(this, modifiedCode, `${id}.jsx`, options);\n\n if (!result) return modifiedCode;\n\n if (typeof result === 'string') return result;\n\n const { code, map: resultMap } = result;\n\n return { code, map: !resultMap || typeof resultMap === 'string' ? resultMap : { ...resultMap, sources: [id] } };\n }\n },\n };\n}\n"]}
@@ -37,7 +37,7 @@ function reactDocgen({ include = /\.(mjs|tsx?|jsx?)$/, exclude = [/node_modules\
37
37
  });
38
38
  return {
39
39
  code: s.toString(),
40
- map: s.generateMap(),
40
+ map: s.generateMap({ hires: true, source: id }),
41
41
  };
42
42
  }
43
43
  catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"react-docgen.js","sourceRoot":"","sources":["../../plugins/react-docgen.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,qDAAmD;AACnD,+CAKsB;AAEtB,gEAAuC;AAEvC,4FAAoE;AAIpE,oFAAoF;AACpF,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,uBAAc,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC;AAChF,MAAM,eAAe,GAAG,uBAAc,CAAC,mCAAmC,CAAC;AAC3E,MAAM,eAAe,GAAG,wBAAe,CAAC,cAAc,EAAE,CAAC;AACzD,MAAM,QAAQ,GAAG,CAAC,GAAG,eAAe,EAAE,2BAAiB,CAAC,CAAC;AAOzD,SAAgB,WAAW,CAAC,EAAE,OAAO,GAAG,oBAAoB,EAAE,OAAO,GAAG,CAAC,kBAAkB,CAAC,KAAc,EAAE;IAC1G,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1B,MAAM,MAAM,GAAG,IAAA,0BAAY,EAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAE9C,OAAO;QACL,IAAI,EAAE,cAAc;QACpB,OAAO,EAAE,KAAK;QACd,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,EAAU;YACrC,MAAM,OAAO,GAAG,cAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YACvC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;gBAAE,OAAO;YAE7B,IAAI;gBACF,yFAAyF;gBACzF,MAAM,aAAa,GAAG,IAAA,oBAAK,EAAC,GAAG,EAAE,eAAe,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAE,EAAE,EAAE,CAC3F,CAAC;gBACb,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,GAAG,CAAC,CAAC;gBAE/B,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;oBAC7B,MAAM,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,GAAG,IAAI,CAAC;oBAC3C,IAAI,UAAU,EAAE;wBACd,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;wBAC3C,CAAC,CAAC,MAAM,CAAC,IAAI,UAAU,iBAAiB,OAAO,EAAE,CAAC,CAAC;qBACpD;gBACH,CAAC,CAAC,CAAC;gBAEH,OAAO;oBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,EAAE;iBACrB,CAAC;aACH;YAAC,OAAO,CAAC,EAAE;gBACV,oFAAoF;gBACpF,qCAAqC;gBACrC,oBAAoB;aACrB;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AApCD,kCAoCC","sourcesContent":["import path from 'path';\nimport { createFilter } from '@rollup/pluginutils';\nimport {\n parse,\n handlers as docgenHandlers,\n resolver as docgenResolver,\n importers as docgenImporters,\n} from 'react-docgen';\nimport type { DocumentationObject } from 'react-docgen/lib/Documentation';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\nimport actualNameHandler from './docgen-handlers/actualNameHandler';\n\ntype DocObj = DocumentationObject & { actualName: string };\n\n// TODO: None of these are able to be overridden, so `default` is aspirational here.\nconst defaultHandlers = Object.values(docgenHandlers).map((handler) => handler);\nconst defaultResolver = docgenResolver.findAllExportedComponentDefinitions;\nconst defaultImporter = docgenImporters.makeFsImporter();\nconst handlers = [...defaultHandlers, actualNameHandler];\n\ntype Options = {\n include?: string | RegExp | (string | RegExp)[];\n exclude?: string | RegExp | (string | RegExp)[];\n};\n\nexport function reactDocgen({ include = /\\.(mjs|tsx?|jsx?)$/, exclude = [/node_modules\\/.*/] }: Options = {}): Plugin {\n const cwd = process.cwd();\n const filter = createFilter(include, exclude);\n\n return {\n name: 'react-docgen',\n enforce: 'pre',\n async transform(src: string, id: string) {\n const relPath = path.relative(cwd, id);\n if (!filter(relPath)) return;\n\n try {\n // Since we're using `findAllExportedComponentDefinitions`, this will always be an array.\n const docgenResults = parse(src, defaultResolver, handlers, { importer: defaultImporter, filename: id }) as\n | DocObj[];\n const s = new MagicString(src);\n\n docgenResults.forEach((info) => {\n const { actualName, ...docgenInfo } = info;\n if (actualName) {\n const docNode = JSON.stringify(docgenInfo);\n s.append(`;${actualName}.__docgenInfo=${docNode}`);\n }\n });\n\n return {\n code: s.toString(),\n map: s.generateMap(),\n };\n } catch (e) {\n // Usually this is just an error from react-docgen that it couldn't find a component\n // Only uncomment for troubleshooting\n // console.error(e);\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"react-docgen.js","sourceRoot":"","sources":["../../plugins/react-docgen.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,qDAAmD;AACnD,+CAKsB;AAEtB,gEAAuC;AAEvC,4FAAoE;AAIpE,oFAAoF;AACpF,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,uBAAc,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC;AAChF,MAAM,eAAe,GA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AAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;iBAChD,CAAC;aACH;YAAC,OAAO,CAAC,EAAE;gBACV,oFAAoF;gBACpF,qCAAqC;gBACrC,oBAAoB;aACrB;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AApCD,kCAoCC","sourcesContent":["import path from 'path';\nimport { createFilter } from '@rollup/pluginutils';\nimport {\n parse,\n handlers as docgenHandlers,\n resolver as docgenResolver,\n importers as docgenImporters,\n} from 'react-docgen';\nimport type { DocumentationObject } from 'react-docgen/lib/Documentation';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\nimport actualNameHandler from './docgen-handlers/actualNameHandler';\n\ntype DocObj = DocumentationObject & { actualName: string };\n\n// TODO: None of these are able to be overridden, so `default` is aspirational here.\nconst defaultHandlers = Object.values(docgenHandlers).map((handler) => handler);\nconst defaultResolver = docgenResolver.findAllExportedComponentDefinitions;\nconst defaultImporter = docgenImporters.makeFsImporter();\nconst handlers = [...defaultHandlers, actualNameHandler];\n\ntype Options = {\n include?: string | RegExp | (string | RegExp)[];\n exclude?: string | RegExp | (string | RegExp)[];\n};\n\nexport function reactDocgen({ include = /\\.(mjs|tsx?|jsx?)$/, exclude = [/node_modules\\/.*/] }: Options = {}): Plugin {\n const cwd = process.cwd();\n const filter = createFilter(include, exclude);\n\n return {\n name: 'react-docgen',\n enforce: 'pre',\n async transform(src: string, id: string) {\n const relPath = path.relative(cwd, id);\n if (!filter(relPath)) return;\n\n try {\n // Since we're using `findAllExportedComponentDefinitions`, this will always be an array.\n const docgenResults = parse(src, defaultResolver, handlers, { importer: defaultImporter, filename: id }) as\n | DocObj[];\n const s = new MagicString(src);\n\n docgenResults.forEach((info) => {\n const { actualName, ...docgenInfo } = info;\n if (actualName) {\n const docNode = JSON.stringify(docgenInfo);\n s.append(`;${actualName}.__docgenInfo=${docNode}`);\n }\n });\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n } catch (e) {\n // Usually this is just an error from react-docgen that it couldn't find a component\n // Only uncomment for troubleshooting\n // console.error(e);\n }\n },\n };\n}\n"]}
@@ -73,7 +73,7 @@ function svelteDocgen(svelteOptions) {
73
73
  }
74
74
  return {
75
75
  code: s.toString(),
76
- map: s.generateMap(),
76
+ map: s.generateMap({ hires: true, source: id }),
77
77
  };
78
78
  }
79
79
  },
@@ -1 +1 @@
1
- {"version":3,"file":"svelte-docgen.js","sourceRoot":"","sources":["../../plugins/svelte-docgen.ts"],"names":[],"mappings":";;;;;;AACA,gEAAuC;AACvC,gDAAwB;AACxB,4CAAoB;AACpB,wEAAyC;AAEzC,wDAAgD;AAChD,8CAA6C;AAE7C,0FAA0F;AAC1F,wGAAwG;AAExG,6IAA6I;AAC7I,sDAAsD;AACtD,SAAS,mBAAmB,CAAC,QAAgB;;IAC3C,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAE3B,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAErD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;QACpB,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACnE,IAAI,WAAW,EAAE;YACf,KAAK,CAAC,GAAG,EAAE,CAAC;YACZ,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;SAC3C;KACF;IAED,MAAM,IAAI,GAAG,MAAA,KAAK;SACf,GAAG,EAAE,0CACJ,OAAO,CAAC,IAAI,EAAE,GAAG,EAClB,OAAO,CAAC,UAAU,EAAE,EAAE,EACtB,OAAO,CAAC,kBAAkB,EAAE,GAAG,EAC/B,OAAO,CAA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M,CAAC,GAAG,IAAI,sBAAW,CAAC,GAAG,CAAC,CAAC;gBAE/B,IAAI;oBACF,MAAM,YAAY,GAAG,MAAM,0BAAS,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;oBACpD,kCAAkC;oBAClC,MAAM,IAAI,GAAG,cAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;oBAErC,YAAY,CAAC,IAAI,GAAG,cAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;oBAExC,MAAM,aAAa,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;oBACpD,CAAC,CAAC,MAAM,CAAC,IAAI,aAAa,eAAe,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;iBAC1E;gBAAC,OAAO,KAAU,EAAE;oBACnB,IAAI,SAAS,EAAE;wBACb,oBAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;qBACrB;iBACF;gBAED,OAAO;oBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,EAAE;iBACrB,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AArDD,oCAqDC","sourcesContent":["import type { Plugin } from 'vite';\nimport MagicString from 'magic-string';\nimport path from 'path';\nimport fs from 'fs';\nimport svelteDoc from 'sveltedoc-parser';\nimport type { SvelteParserOptions } from 'sveltedoc-parser';\nimport { logger } from '@storybook/node-logger';\nimport { preprocess } from 'svelte/compiler';\n\n// Most of the code here should probably be exported by @storybook/svelte and reused here.\n// See: https://github.com/storybookjs/storybook/blob/next/app/svelte/src/server/svelte-docgen-loader.ts\n\n// From https://github.com/sveltejs/svelte/blob/8db3e8d0297e052556f0b6dde310ef6e197b8d18/src/compiler/compile/utils/get_name_from_filename.ts\n// Copied because it is not exported from the compiler\nfunction getNameFromFilename(filename: string) {\n if (!filename) return null;\n\n const parts = filename.split(/[/\\\\]/).map(encodeURI);\n\n if (parts.length > 1) {\n const index_match = parts[parts.length - 1].match(/^index(\\.\\w+)/);\n if (index_match) {\n parts.pop();\n parts[parts.length - 1] += index_match[1];\n }\n }\n\n const base = parts\n .pop()\n ?.replace(/%/g, 'u')\n .replace(/\\.[^.]+$/, '')\n .replace(/[^a-zA-Z_$0-9]+/g, '_')\n .replace(/^_/, '')\n .replace(/_$/, '')\n .replace(/^(\\d)/, '_$1');\n\n if (!base) {\n throw new Error(`Could not derive component name from file ${filename}`);\n }\n\n return base[0].toUpperCase() + base.slice(1);\n}\n\nexport function svelteDocgen(svelteOptions: Record<string, any>): Plugin {\n const cwd = process.cwd();\n const { preprocess: preprocessOptions, logDocgen = false } = svelteOptions;\n\n return {\n name: 'svelte-docgen',\n async transform(src: string, id: string) {\n if (/\\.(svelte)$/.test(id)) {\n const resource = path.relative(cwd, id);\n\n let docOptions;\n if (preprocessOptions) {\n const src = fs.readFileSync(resource).toString();\n\n const { code: fileContent } = await preprocess(src, preprocessOptions, { filename: resource });\n\n docOptions = {\n fileContent,\n };\n } else {\n docOptions = { filename: resource };\n }\n\n // set SvelteDoc options\n const options: SvelteParserOptions = {\n ...docOptions,\n version: 3,\n };\n\n const s = new MagicString(src);\n\n try {\n const componentDoc = await svelteDoc.parse(options);\n // get filename for source content\n const file = path.basename(resource);\n\n componentDoc.name = path.basename(file);\n\n const componentName = getNameFromFilename(resource);\n s.append(`;${componentName}.__docgen = ${JSON.stringify(componentDoc)}`);\n } catch (error: any) {\n if (logDocgen) {\n logger.error(error);\n }\n }\n\n return {\n code: s.toString(),\n map: s.generateMap(),\n };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"svelte-docgen.js","sourceRoot":"","sources":["../../plugins/svelte-docgen.ts"],"names":[],"mappings":";;;;;;AACA,gEAAuC;AACvC,gDAAwB;AACxB,4CAAoB;AACpB,wEAAyC;AAEzC,wDAAgD;AAChD,8CAA6C;AAE7C,0FAA0F;AAC1F,wGAAwG;AAExG,6IAA6I;AAC7I,sDAAsD;AACtD,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K,CAAC,CAAC;qBACrB;iBACF;gBAED,OAAO;oBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;iBAChD,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AArDD,oCAqDC","sourcesContent":["import type { Plugin } from 'vite';\nimport MagicString from 'magic-string';\nimport path from 'path';\nimport fs from 'fs';\nimport svelteDoc from 'sveltedoc-parser';\nimport type { SvelteParserOptions } from 'sveltedoc-parser';\nimport { logger } from '@storybook/node-logger';\nimport { preprocess } from 'svelte/compiler';\n\n// Most of the code here should probably be exported by @storybook/svelte and reused here.\n// See: https://github.com/storybookjs/storybook/blob/next/app/svelte/src/server/svelte-docgen-loader.ts\n\n// From https://github.com/sveltejs/svelte/blob/8db3e8d0297e052556f0b6dde310ef6e197b8d18/src/compiler/compile/utils/get_name_from_filename.ts\n// Copied because it is not exported from the compiler\nfunction getNameFromFilename(filename: string) {\n if (!filename) return null;\n\n const parts = filename.split(/[/\\\\]/).map(encodeURI);\n\n if (parts.length > 1) {\n const index_match = parts[parts.length - 1].match(/^index(\\.\\w+)/);\n if (index_match) {\n parts.pop();\n parts[parts.length - 1] += index_match[1];\n }\n }\n\n const base = parts\n .pop()\n ?.replace(/%/g, 'u')\n .replace(/\\.[^.]+$/, '')\n .replace(/[^a-zA-Z_$0-9]+/g, '_')\n .replace(/^_/, '')\n .replace(/_$/, '')\n .replace(/^(\\d)/, '_$1');\n\n if (!base) {\n throw new Error(`Could not derive component name from file ${filename}`);\n }\n\n return base[0].toUpperCase() + base.slice(1);\n}\n\nexport function svelteDocgen(svelteOptions: Record<string, any>): Plugin {\n const cwd = process.cwd();\n const { preprocess: preprocessOptions, logDocgen = false } = svelteOptions;\n\n return {\n name: 'svelte-docgen',\n async transform(src: string, id: string) {\n if (/\\.(svelte)$/.test(id)) {\n const resource = path.relative(cwd, id);\n\n let docOptions;\n if (preprocessOptions) {\n const src = fs.readFileSync(resource).toString();\n\n const { code: fileContent } = await preprocess(src, preprocessOptions, { filename: resource });\n\n docOptions = {\n fileContent,\n };\n } else {\n docOptions = { filename: resource };\n }\n\n // set SvelteDoc options\n const options: SvelteParserOptions = {\n ...docOptions,\n version: 3,\n };\n\n const s = new MagicString(src);\n\n try {\n const componentDoc = await svelteDoc.parse(options);\n // get filename for source content\n const file = path.basename(resource);\n\n componentDoc.name = path.basename(file);\n\n const componentName = getNameFromFilename(resource);\n s.append(`;${componentName}.__docgen = ${JSON.stringify(componentDoc)}`);\n } catch (error: any) {\n if (logDocgen) {\n logger.error(error);\n }\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n }\n },\n };\n}\n"]}
@@ -17,7 +17,7 @@ function vueDocgen() {
17
17
  s.append(`;_sfc_main.__docgenInfo = ${metaSource}`);
18
18
  return {
19
19
  code: s.toString(),
20
- map: s.generateMap(),
20
+ map: s.generateMap({ hires: true, source: id }),
21
21
  };
22
22
  }
23
23
  },
@@ -1 +1 @@
1
- {"version":3,"file":"vue-docgen.js","sourceRoot":"","sources":["../../plugins/vue-docgen.ts"],"names":[],"mappings":";;;;;;AAAA,mDAAuC;AAEvC,gEAAuC;AAEvC,SAAgB,SAAS;IACvB,OAAO;QACL,IAAI,EAAE,YAAY;QAElB,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,EAAU;YACrC,IAAI,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;gBACvB,MAAM,QAAQ,GAAG,MAAM,IAAA,sBAAK,EAAC,EAAE,CAAC,CAAC;gBACjC,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;gBAC5C,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,GAAG,CAAC,CAAC;gBAC/B,CAAC,CAAC,MAAM,CAAC,6BAA6B,UAAU,EAAE,CAAC,CAAC;gBAEpD,OAAO;oBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,EAAE;iBACrB,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAlBD,8BAkBC","sourcesContent":["import { parse } from 'vue-docgen-api';\nimport type { Plugin } from 'vite';\nimport MagicString from 'magic-string';\n\nexport function vueDocgen(): Plugin {\n return {\n name: 'vue-docgen',\n\n async transform(src: string, id: string) {\n if (/\\.(vue)$/.test(id)) {\n const metaData = await parse(id);\n const metaSource = JSON.stringify(metaData);\n const s = new MagicString(src);\n s.append(`;_sfc_main.__docgenInfo = ${metaSource}`);\n\n return {\n code: s.toString(),\n map: s.generateMap(),\n };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"vue-docgen.js","sourceRoot":"","sources":["../../plugins/vue-docgen.ts"],"names":[],"mappings":";;;;;;AAAA,mDAAuC;AAEvC,gEAAuC;AAEvC,SAAgB,SAAS;IACvB,OAAO;QACL,IAAI,EAAE,YAAY;QAElB,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,EAAU;YACrC,IAAI,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;gBACvB,MAAM,QAAQ,GAAG,MAAM,IAAA,sBAAK,EAAC,EAAE,CAAC,CAAC;gBACjC,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;gBAC5C,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,GAAG,CAAC,CAAC;gBAC/B,CAAC,CAAC,MAAM,CAAC,6BAA6B,UAAU,EAAE,CAAC,CAAC;gBAEpD,OAAO;oBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;oBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;iBAChD,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAlBD,8BAkBC","sourcesContent":["import { parse } from 'vue-docgen-api';\nimport type { Plugin } from 'vite';\nimport MagicString from 'magic-string';\n\nexport function vueDocgen(): Plugin {\n return {\n name: 'vue-docgen',\n\n async transform(src: string, id: string) {\n if (/\\.(vue)$/.test(id)) {\n const metaData = await parse(id);\n const metaSource = JSON.stringify(metaData);\n const s = new MagicString(src);\n s.append(`;_sfc_main.__docgenInfo = ${metaSource}`);\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n }\n },\n };\n}\n"]}
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.sourceLoaderPlugin = void 0;
7
7
  const source_loader_1 = __importDefault(require("@storybook/source-loader"));
8
+ const magic_string_1 = __importDefault(require("magic-string"));
8
9
  const storyPattern = /\.stories\.[jt]sx?$/;
9
10
  const storySourcePattern = /var __STORY__ = "(.*)"/;
10
11
  const storySourceReplacement = '--STORY_SOURCE_REPLACEMENT--';
@@ -21,9 +22,12 @@ function sourceLoaderPlugin(config) {
21
22
  async transform(src, id) {
22
23
  if (id.match(storyPattern)) {
23
24
  const code = await source_loader_1.default.call(mockClassLoader(id), src);
25
+ const s = new magic_string_1.default(src);
26
+ // Entirely replace with new code
27
+ s.overwrite(0, src.length, code);
24
28
  return {
25
- code,
26
- map: { mappings: '' },
29
+ code: s.toString(),
30
+ map: s.generateMap({ hires: true, source: id }),
27
31
  };
28
32
  }
29
33
  },
@@ -49,9 +53,12 @@ function sourceLoaderPlugin(config) {
49
53
  // Remove story source so that it is not processed by vite:define plugin
50
54
  code = replaceAll(code, sourceString, storySourceReplacement);
51
55
  }
56
+ const s = new magic_string_1.default(src);
57
+ // Entirely replace with new code
58
+ s.overwrite(0, src.length, code);
52
59
  return {
53
- code,
54
- map: { mappings: '' },
60
+ code: s.toString(),
61
+ map: s.generateMap(),
55
62
  };
56
63
  }
57
64
  },
@@ -64,19 +71,17 @@ function sourceLoaderPlugin(config) {
64
71
  },
65
72
  async transform(src, id) {
66
73
  if (id.match(storyPattern)) {
67
- let code;
74
+ const s = new magic_string_1.default(src);
68
75
  const map = storySources.get(config);
69
76
  const storySourceStatement = map === null || map === void 0 ? void 0 : map.get(id);
70
77
  // Put the previously-extracted source back in
71
78
  if (storySourceStatement) {
72
- code = replaceAll(src, storySourceReplacement, storySourceStatement);
73
- }
74
- else {
75
- code = src;
79
+ const newCode = replaceAll(src, storySourceReplacement, storySourceStatement);
80
+ s.overwrite(0, src.length, newCode);
76
81
  }
77
82
  return {
78
- code,
79
- map: { mappings: '' },
83
+ code: s.toString(),
84
+ map: s.generateMap(),
80
85
  };
81
86
  }
82
87
  },
@@ -1 +1 @@
1
- {"version":3,"file":"source-loader-plugin.js","sourceRoot":"","sources":["../source-loader-plugin.ts"],"names":[],"mappings":";;;;;;AACA,6EAA6D;AAG7D,MAAM,YAAY,GAAG,qBAAqB,CAAC;AAC3C,MAAM,kBAAkB,GAAG,wBAAwB,CAAC;AACpD,MAAM,sBAAsB,GAAG,8BAA8B,CAAC;AAE9D,MAAM,eAAe,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,OAAe,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC,CAAC;AAExH,+EAA+E;AAC/E,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,MAAc,EAAE,WAAmB,EAAE,EAAE;IACtE,OAAO,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC7C,CAAC,CAAC;AAEF,SAAgB,kBAAkB,CAAC,MAAuB;IACxD,IAAI,MAAM,CAAC,UAAU,KAAK,aAAa,EAAE;QACvC,OAAO;YACL,IAAI,EAAE,qCAAqC;YAC3C,OAAO,EAAE,KAAK;YACd,KAAK,CAAC,SAAS,CA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AAE;qBACtB,CAAC;iBACH;YACH,CAAC;SACF;QACD;YACE,IAAI,EAAE,0CAA0C;YAChD,OAAO,EAAE,MAAM;YACf,UAAU;gBACR,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;YACtC,CAAC;YACD,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,EAAU;gBACrC,IAAI,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE;oBAC1B,IAAI,IAAI,CAAC;oBACT,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;oBACrC,MAAM,oBAAoB,GAAG,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,GAAG,CAAC,EAAE,CAAC,CAAC;oBAC1C,8CAA8C;oBAC9C,IAAI,oBAAoB,EAAE;wBACxB,IAAI,GAAG,UAAU,CAAC,GAAG,EAAE,sBAAsB,EAAE,oBAAoB,CAAC,CAAC;qBACtE;yBAAM;wBACL,IAAI,GAAG,GAAG,CAAC;qBACZ;oBAED,OAAO;wBACL,IAAI;wBACJ,GAAG,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE;qBACtB,CAAC;iBACH;YACH,CAAC;SACF;KACF,CAAC;AACJ,CAAC;AAzED,gDAyEC","sourcesContent":["import type { Plugin } from 'vite';\nimport sourceLoaderTransform from '@storybook/source-loader';\nimport type { ExtendedOptions } from './types';\n\nconst storyPattern = /\\.stories\\.[jt]sx?$/;\nconst storySourcePattern = /var __STORY__ = \"(.*)\"/;\nconst storySourceReplacement = '--STORY_SOURCE_REPLACEMENT--';\n\nconst mockClassLoader = (id: string) => ({ emitWarning: (message: string) => console.warn(message), resourcePath: id });\n\n// HACK: Until we can support only node 15+ and use string.prototype.replaceAll\nconst replaceAll = (str: string, search: string, replacement: string) => {\n return str.split(search).join(replacement);\n};\n\nexport function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {\n if (config.configType === 'DEVELOPMENT') {\n return {\n name: 'storybook-vite-source-loader-plugin',\n enforce: 'pre',\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n const code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);\n\n return {\n code,\n map: { mappings: '' },\n };\n }\n },\n };\n }\n\n // In production, we need to be fancier, to avoid vite:define plugin from replacing values inside the `__STORY__` string\n const storySources = new WeakMap<ExtendedOptions, Map<string, string>>();\n\n return [\n {\n name: 'storybook-vite-source-loader-plugin',\n enforce: 'pre',\n buildStart() {\n storySources.set(config, new Map());\n },\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n let code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);\n const [_, sourceString] = code.match(storySourcePattern) ?? [null, null];\n if (sourceString) {\n const map = storySources.get(config);\n map?.set(id, sourceString);\n\n // Remove story source so that it is not processed by vite:define plugin\n code = replaceAll(code, sourceString, storySourceReplacement);\n }\n\n return {\n code,\n map: { mappings: '' },\n };\n }\n },\n },\n {\n name: 'storybook-vite-source-loader-plugin-post',\n enforce: 'post',\n buildStart() {\n storySources.set(config, new Map());\n },\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n let code;\n const map = storySources.get(config);\n const storySourceStatement = map?.get(id);\n // Put the previously-extracted source back in\n if (storySourceStatement) {\n code = replaceAll(src, storySourceReplacement, storySourceStatement);\n } else {\n code = src;\n }\n\n return {\n code,\n map: { mappings: '' },\n };\n }\n },\n },\n ];\n}\n"]}
1
+ {"version":3,"file":"source-loader-plugin.js","sourceRoot":"","sources":["../source-loader-plugin.ts"],"names":[],"mappings":";;;;;;AACA,6EAA6D;AAE7D,gEAAuC;AAEvC,MAAM,YAAY,GAAG,qBAAqB,CAAC;AAC3C,MAAM,kBAAkB,GAAG,wBAAwB,CAAC;AACpD,MAAM,sBAAsB,GAAG,8BAA8B,CAAC;AAE9D,MAAM,eAAe,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,OAAe,EAAE,EAA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CAAC,CAAC;oBAC/B,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;oBACrC,MAAM,oBAAoB,GAAG,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,GAAG,CAAC,EAAE,CAAC,CAAC;oBAC1C,8CAA8C;oBAC9C,IAAI,oBAAoB,EAAE;wBACxB,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,sBAAsB,EAAE,oBAAoB,CAAC,CAAC;wBAC9E,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;qBACrC;oBAED,OAAO;wBACL,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE;wBAClB,GAAG,EAAE,CAAC,CAAC,WAAW,EAAE;qBACrB,CAAC;iBACH;YACH,CAAC;SACF;KACF,CAAC;AACJ,CAAC;AA/ED,gDA+EC","sourcesContent":["import type { Plugin } from 'vite';\nimport sourceLoaderTransform from '@storybook/source-loader';\nimport type { ExtendedOptions } from './types';\nimport MagicString from 'magic-string';\n\nconst storyPattern = /\\.stories\\.[jt]sx?$/;\nconst storySourcePattern = /var __STORY__ = \"(.*)\"/;\nconst storySourceReplacement = '--STORY_SOURCE_REPLACEMENT--';\n\nconst mockClassLoader = (id: string) => ({ emitWarning: (message: string) => console.warn(message), resourcePath: id });\n\n// HACK: Until we can support only node 15+ and use string.prototype.replaceAll\nconst replaceAll = (str: string, search: string, replacement: string) => {\n return str.split(search).join(replacement);\n};\n\nexport function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {\n if (config.configType === 'DEVELOPMENT') {\n return {\n name: 'storybook-vite-source-loader-plugin',\n enforce: 'pre',\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n const code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);\n const s = new MagicString(src);\n // Entirely replace with new code\n s.overwrite(0, src.length, code);\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n }\n },\n };\n }\n\n // In production, we need to be fancier, to avoid vite:define plugin from replacing values inside the `__STORY__` string\n const storySources = new WeakMap<ExtendedOptions, Map<string, string>>();\n\n return [\n {\n name: 'storybook-vite-source-loader-plugin',\n enforce: 'pre',\n buildStart() {\n storySources.set(config, new Map());\n },\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n let code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);\n const [_, sourceString] = code.match(storySourcePattern) ?? [null, null];\n if (sourceString) {\n const map = storySources.get(config);\n map?.set(id, sourceString);\n\n // Remove story source so that it is not processed by vite:define plugin\n code = replaceAll(code, sourceString, storySourceReplacement);\n }\n\n const s = new MagicString(src);\n // Entirely replace with new code\n s.overwrite(0, src.length, code);\n\n return {\n code: s.toString(),\n map: s.generateMap(),\n };\n }\n },\n },\n {\n name: 'storybook-vite-source-loader-plugin-post',\n enforce: 'post',\n buildStart() {\n storySources.set(config, new Map());\n },\n async transform(src: string, id: string) {\n if (id.match(storyPattern)) {\n const s = new MagicString(src);\n const map = storySources.get(config);\n const storySourceStatement = map?.get(id);\n // Put the previously-extracted source back in\n if (storySourceStatement) {\n const newCode = replaceAll(src, storySourceReplacement, storySourceStatement);\n s.overwrite(0, src.length, newCode);\n }\n\n return {\n code: s.toString(),\n map: s.generateMap(),\n };\n }\n },\n },\n ];\n}\n"]}
@@ -4,5 +4,6 @@ export default function csfPlugin(svelteOptions?: Options): {
4
4
  enforce: string;
5
5
  transform(code: string, id: string): Promise<{
6
6
  code: string;
7
+ map: import("magic-string").SourceMap;
7
8
  } | undefined>;
8
9
  };
@@ -22,18 +22,23 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
25
28
  Object.defineProperty(exports, "__esModule", { value: true });
26
29
  const svelte_stories_loader_1 = require("@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader");
27
30
  const fs_1 = require("fs");
28
31
  const extract_stories_1 = require("@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories");
29
32
  const parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\]/g, '/');
30
33
  const svelte = __importStar(require("svelte/compiler"));
34
+ const magic_string_1 = __importDefault(require("magic-string"));
31
35
  function csfPlugin(svelteOptions) {
32
36
  return {
33
37
  name: 'storybook-addon-svelte-csf',
34
38
  enforce: 'post',
35
39
  async transform(code, id) {
36
40
  if (/\.stories\.svelte$/.test(id)) {
41
+ const s = new magic_string_1.default(code);
37
42
  const component = (0, svelte_stories_loader_1.getNameFromFilename)(id);
38
43
  let source = (0, fs_1.readFileSync)(id).toString();
39
44
  if (svelteOptions && svelteOptions.preprocess) {
@@ -45,20 +50,22 @@ function csfPlugin(svelteOptions) {
45
50
  .filter(([, def]) => !def.template)
46
51
  .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}];`)
47
52
  .join('\n');
48
- const codeWithoutDefaultExport = code.replace('export default ', '// export default ');
53
+ s.replace('export default', '// export default');
49
54
  const namedExportsOrder = Object.entries(stories)
50
55
  .filter(([, def]) => !def.template)
51
56
  .map(([id]) => id);
52
57
  const output = [
53
- codeWithoutDefaultExport,
58
+ '',
54
59
  `import parser from '${parser}';`,
55
60
  `const __storiesMetaData = parser(${component}, ${JSON.stringify(all)});`,
56
61
  'export default __storiesMetaData.meta;',
57
62
  `export const __namedExportsOrder = ${JSON.stringify(namedExportsOrder)};`,
58
63
  storyDef,
59
64
  ].join('\n');
65
+ s.append(output);
60
66
  return {
61
- code: output,
67
+ code: s.toString(),
68
+ map: s.generateMap({ hires: true, source: id }),
62
69
  };
63
70
  }
64
71
  },
@@ -1 +1 @@
1
- {"version":3,"file":"csf-plugin.js","sourceRoot":"","sources":["../../svelte/csf-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;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AiB,EAAE,oBAAoB,CAAC,CAAC;gBAEvF,MAAM,iBAAiB,GAAG,MAAM,CAAC,OAAO,CAAM,OAAO,CAAC;qBACnD,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC;qBAClC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;gBAErB,MAAM,MAAM,GAAG;oBACb,wBAAwB;oBACxB,uBAAuB,MAAM,IAAI;oBACjC,oCAAoC,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI;oBACzE,wCAAwC;oBACxC,sCAAsC,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,GAAG;oBAC1E,QAAQ;iBACT,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACb,OAAO;oBACL,IAAI,EAAE,MAAM;iBACb,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAtCD,4BAsCC","sourcesContent":["import { getNameFromFilename } from '@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader';\nimport { readFileSync } from 'fs';\nimport { extractStories } from '@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories';\nconst parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\\\]/g, '/');\nimport type { Options } from '@sveltejs/vite-plugin-svelte';\nimport * as svelte from 'svelte/compiler';\n\nexport default function csfPlugin(svelteOptions?: Options) {\n return {\n name: 'storybook-addon-svelte-csf',\n enforce: 'post',\n async transform(code: string, id: string) {\n if (/\\.stories\\.svelte$/.test(id)) {\n const component = getNameFromFilename(id);\n let source = readFileSync(id).toString();\n if (svelteOptions && svelteOptions.preprocess) {\n source = (await svelte.preprocess(source, svelteOptions.preprocess, { filename: id })).code;\n }\n const all = extractStories(source);\n const { stories } = all;\n const storyDef = Object.entries<any>(stories)\n .filter(([, def]) => !def.template)\n .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}];`)\n .join('\\n');\n\n const codeWithoutDefaultExport = code.replace('export default ', '// export default ');\n\n const namedExportsOrder = Object.entries<any>(stories)\n .filter(([, def]) => !def.template)\n .map(([id]) => id);\n\n const output = [\n codeWithoutDefaultExport,\n `import parser from '${parser}';`,\n `const __storiesMetaData = parser(${component}, ${JSON.stringify(all)});`,\n 'export default __storiesMetaData.meta;',\n `export const __namedExportsOrder = ${JSON.stringify(namedExportsOrder)};`,\n storyDef,\n ].join('\\n');\n return {\n code: output,\n };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"csf-plugin.js","sourceRoot":"","sources":["../../svelte/csf-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6GAAwG;AACxG,2BAAkC;AAClC,iGAA6F;AAC7F,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,6DAA6D,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAErH,wDAA0C;AAC1C,gEAAuC;AAEvC,SAAwB,SAAS,CAAC,aAAuB;IACvD,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,OAAO,EAAE,MAAM;QACf,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,EAAU;YACtC,IAAI,oBAAoB,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;gBACjC,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,IAAI,CAAC,CAAC;gBAChC,MAAM,SAAS,GAAG,IAAA,2CAAmB,EAAC,EAAE,CAAC,CAAC;gBAC1C,IAAI,MAAM,GAAG,IAAA,iBAAY,EAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;gBACzC,IAAI,aAAa,IAAI,aAAa,CAAC,UAAU,EAAE;oBAC7C,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,UAAU,EAAE,EAAE,Q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EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;iBAChD,CAAC;aACH;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AA3CD,4BA2CC","sourcesContent":["import { getNameFromFilename } from '@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader';\nimport { readFileSync } from 'fs';\nimport { extractStories } from '@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories';\nconst parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\\\]/g, '/');\nimport type { Options } from '@sveltejs/vite-plugin-svelte';\nimport * as svelte from 'svelte/compiler';\nimport MagicString from 'magic-string';\n\nexport default function csfPlugin(svelteOptions?: Options) {\n return {\n name: 'storybook-addon-svelte-csf',\n enforce: 'post',\n async transform(code: string, id: string) {\n if (/\\.stories\\.svelte$/.test(id)) {\n const s = new MagicString(code);\n const component = getNameFromFilename(id);\n let source = readFileSync(id).toString();\n if (svelteOptions && svelteOptions.preprocess) {\n source = (await svelte.preprocess(source, svelteOptions.preprocess, { filename: id })).code;\n }\n const all = extractStories(source);\n const { stories } = all;\n const storyDef = Object.entries<any>(stories)\n .filter(([, def]) => !def.template)\n .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}];`)\n .join('\\n');\n\n s.replace('export default', '// export default');\n\n const namedExportsOrder = Object.entries<any>(stories)\n .filter(([, def]) => !def.template)\n .map(([id]) => id);\n\n const output = [\n '',\n `import parser from '${parser}';`,\n `const __storiesMetaData = parser(${component}, ${JSON.stringify(all)});`,\n 'export default __storiesMetaData.meta;',\n `export const __namedExportsOrder = ${JSON.stringify(namedExportsOrder)};`,\n storyDef,\n ].join('\\n');\n\n s.append(output);\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true, source: id }),\n };\n }\n },\n };\n}\n"]}
@@ -82,6 +82,20 @@ async function pluginConfig(options, _type) {
82
82
  // Do not treat story files as HMR boundaries, storybook itself needs to handle them.
83
83
  exclude: [/\.stories\.([tj])sx?$/, /node_modules/].concat(framework === 'react' ? [] : [/\.([tj])sx?$/]),
84
84
  }),
85
+ {
86
+ name: 'vite-plugin-storybook-allow',
87
+ enforce: 'post',
88
+ config(config) {
89
+ var _a, _b;
90
+ // if there is no allow list then Vite allows anything in the root directory
91
+ // if there is an allow list then Vite allows anything in the listed directories
92
+ // add the .storybook directory only if there's an allow list so that we don't end up
93
+ // disallowing the root directory unless it's already disallowed
94
+ if ((_b = (_a = config === null || config === void 0 ? void 0 : config.server) === null || _a === void 0 ? void 0 : _a.fs) === null || _b === void 0 ? void 0 : _b.allow) {
95
+ config.server.fs.allow.push('.storybook');
96
+ }
97
+ },
98
+ },
85
99
  ];
86
100
  if (framework === 'vue' || framework === 'vue3') {
87
101
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"vite-config.js","sourceRoot":"","sources":["../vite-config.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,4CAAoB;AAGpB,wEAA6C;AAE7C,iCAAuD;AACvD,iDAA4C;AAC5C,mEAA8D;AAC9D,6EAAuE;AACvE,qDAAiD;AACjD,+CAA2C;AAC3C,iEAA4D;AAO5D,SAAgB,eAAe;IAC7B,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IACrD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE;QACnC,OAAO,KAAK,CAAC;KACd;IAED,MAAM,WAAW,GAAG,YAAE,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;IAC7D,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AACjC,CAAC;AARD,0CAQC;AAED,gEAAgE;AACzD,KAAK,UAAU,YAAY,CAChC,OAAwB,EACxB,KAAuB;IAEvB,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,OAAO;QACL,UAAU,EAAE,KAAK;QACjB,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ACF,MAAM,OAAO,GAAG,eAAe,EAAE,CAAC;YAClC,iBAAiB,GAAG,OAAO,IAAI,CAAC,CAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,0CAAE,UAAU,MAAI,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,0CAAE,UAAU,CAAA,CAAC,CAAC;SAC5G;QAAC,OAAO,CAAC,EAAE;YACV,iBAAiB,GAAG,KAAK,CAAC;SAC3B;QAED,IAAI,WAAW,KAAK,yBAAyB,IAAI,iBAAiB,EAAE;YAClE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,kDAAkD,CAAC,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC,CAAC;SACjH;aAAM,IAAI,WAAW,EAAE;YACtB,MAAM,EAAE,WAAW,EAAE,GAAG,wDAAa,wBAAwB,GAAC,CAAC;YAC/D,4DAA4D;YAC5D,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;SAChC;KACF;IAED,IAAI,SAAS,KAAK,UAAU,EAAE;QAC5B,MAAM,MAAM,GAAG,OAAO,CAAC,gCAAgC,CAAC,CAAC;QACzD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;KAChC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AA7HD,oCA6HC","sourcesContent":["import * as path from 'path';\nimport fs from 'fs';\nimport { Plugin } from 'vite';\nimport { TypescriptConfig } from '@storybook/core-common';\nimport viteReact from '@vitejs/plugin-react';\n\nimport { allowedEnvPrefix as envPrefix } from './envs';\nimport { mockCoreJs } from './mock-core-js';\nimport { codeGeneratorPlugin } from './code-generator-plugin';\nimport { injectExportOrderPlugin } from './inject-export-order-plugin';\nimport { mdxPlugin } from './plugins/mdx-plugin';\nimport { noFouc } from './plugins/no-fouc';\nimport { sourceLoaderPlugin } from './source-loader-plugin';\n\nimport type { UserConfig } from 'vite';\nimport type { ExtendedOptions } from './types';\n\nexport type PluginConfigType = 'build' | 'development';\n\nexport function readPackageJson(): Record<string, any> | false {\n const packageJsonPath = path.resolve('package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const jsonContent = fs.readFileSync(packageJsonPath, 'utf8');\n return JSON.parse(jsonContent);\n}\n\n// Vite config that is common to development and production mode\nexport async function commonConfig(\n options: ExtendedOptions,\n _type: PluginConfigType\n): Promise<UserConfig & { configFile: false; root: string }> {\n const { framework } = options;\n\n return {\n configFile: false,\n root: path.resolve(options.configDir, '..'),\n cacheDir: 'node_modules/.vite-storybook',\n envPrefix,\n define: {},\n resolve:\n framework === 'vue3'\n ? {\n alias: {\n vue: 'vue/dist/vue.esm-bundler.js',\n },\n }\n : {},\n plugins: await pluginConfig(options, _type),\n };\n}\n\nexport async function pluginConfig(options: ExtendedOptions, _type: PluginConfigType) {\n const { framework, presets } = options;\n const svelteOptions: Record<string, any> = await presets.apply('svelteOptions', {}, options);\n\n const plugins = [\n codeGeneratorPlugin(options),\n mockCoreJs(),\n sourceLoaderPlugin(options),\n mdxPlugin(options),\n noFouc(),\n injectExportOrderPlugin,\n // We need the react plugin here to support MDX.\n viteReact({\n // Do not treat story files as HMR boundaries, storybook itself needs to handle them.\n exclude: [/\\.stories\\.([tj])sx?$/, /node_modules/].concat(framework === 'react' ? [] : [/\\.([tj])sx?$/]),\n }),\n ] as Plugin[];\n if (framework === 'vue' || framework === 'vue3') {\n try {\n const vuePlugin = require('@vitejs/plugin-vue');\n plugins.push(vuePlugin());\n const { vueDocgen } = await import('./plugins/vue-docgen');\n plugins.push(vueDocgen());\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n throw new Error(\n '@storybook/builder-vite requires @vitejs/plugin-vue to be installed ' +\n 'when using @storybook/vue or @storybook/vue3.' +\n ' Please install it and start storybook again.'\n );\n }\n throw err;\n }\n }\n if (framework === 'svelte') {\n try {\n const sveltePlugin = require('@sveltejs/vite-plugin-svelte').svelte;\n\n // We need to create two separate svelte plugins, one for stories, and one for other svelte files\n // because stories.svelte files cannot be hot-module-reloaded.\n // Suggested in: https://github.com/sveltejs/vite-plugin-svelte/issues/321#issuecomment-1113205509\n\n // First, create an array containing user exclude patterns, to combine with ours.\n const userExclude = Array.isArray(svelteOptions?.exclude)\n ? svelteOptions?.exclude\n : svelteOptions?.exclude\n ? [svelteOptions?.exclude]\n : [];\n\n // These are the svelte stories we need to exclude from HMR\n const storyPatterns = ['**/*.story.svelte', '**/*.stories.svelte'];\n // Non-story svelte files\n // Starting in 1.0.0-next.42, svelte.config.js is included by default.\n // We disable that, but allow it to be overridden in svelteOptions\n plugins.push(sveltePlugin({ configFile: false, ...svelteOptions, exclude: [...userExclude, ...storyPatterns] }));\n // Svelte stories without HMR\n const storySveltePlugin = sveltePlugin({\n configFile: false,\n ...svelteOptions,\n exclude: userExclude,\n include: storyPatterns,\n hot: false,\n });\n plugins.push({\n // Starting in 1.0.0-next.43, the plugin function returns an array of plugins. We only want the first one here.\n ...(Array.isArray(storySveltePlugin) ? storySveltePlugin[0] : storySveltePlugin),\n name: 'vite-plugin-svelte-stories',\n });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n throw new Error(\n '@storybook/builder-vite requires @sveltejs/vite-plugin-svelte to be installed' +\n ' when using @storybook/svelte.' +\n ' Please install it and start storybook again.'\n );\n }\n throw err;\n }\n\n try {\n const csfPlugin = require('./svelte/csf-plugin').default;\n plugins.push(csfPlugin(svelteOptions));\n } catch (err) {\n // Not all projects use `.stories.svelte` for stories, and by default 6.5+ does not auto-install @storybook/addon-svelte-csf.\n // If it's any other kind of error, re-throw.\n if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {\n throw err;\n }\n }\n\n const { svelteDocgen } = await import('./plugins/svelte-docgen');\n plugins.push(svelteDocgen(svelteOptions));\n }\n\n if (framework === 'preact') {\n plugins.push(require('@preact/preset-vite').default());\n }\n\n if (framework === 'react') {\n const { reactDocgen, reactDocgenTypescriptOptions } = await presets.apply('typescript', {} as TypescriptConfig);\n\n let typescriptPresent;\n\n try {\n const pkgJson = readPackageJson();\n typescriptPresent = pkgJson && (pkgJson?.devDependencies?.typescript || pkgJson?.dependencies?.typescript);\n } catch (e) {\n typescriptPresent = false;\n }\n\n if (reactDocgen === 'react-docgen-typescript' && typescriptPresent) {\n plugins.push(require('@joshwooding/vite-plugin-react-docgen-typescript').default(reactDocgenTypescriptOptions));\n } else if (reactDocgen) {\n const { reactDocgen } = await import('./plugins/react-docgen');\n // Needs to run before the react plugin, so add to the front\n plugins.unshift(reactDocgen());\n }\n }\n\n if (framework === 'glimmerx') {\n const plugin = require('vite-plugin-glimmerx/index.cjs');\n plugins.push(plugin.default());\n }\n\n return plugins;\n}\n"]}
1
+ {"version":3,"file":"vite-config.js","sourceRoot":"","sources":["../vite-config.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,4CAAoB;AAGpB,wEAA6C;AAE7C,iCAAuD;AACvD,iDAA4C;AAC5C,mEAA8D;AAC9D,6EAAuE;AACvE,qDAAiD;AACjD,+CAA2C;AAC3C,iEAA4D;AAO5D,SAAgB,eAAe;IAC7B,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IACrD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE;QACnC,OAAO,KAAK,CAAC;KACd;IAED,MAAM,WAAW,GAAG,YAAE,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;IAC7D,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AACjC,CAAC;AARD,0CAQC;AAED,gEAAgE;AACzD,KAAK,UAAU,YAAY,CAChC,OAAwB,EACxB,KAAuB;IAEvB,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,OAAO;QACL,UAAU,EAAE,KAAK;QACjB,I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';\nimport { Plugin } from 'vite';\nimport { TypescriptConfig } from '@storybook/core-common';\nimport viteReact from '@vitejs/plugin-react';\n\nimport { allowedEnvPrefix as envPrefix } from './envs';\nimport { mockCoreJs } from './mock-core-js';\nimport { codeGeneratorPlugin } from './code-generator-plugin';\nimport { injectExportOrderPlugin } from './inject-export-order-plugin';\nimport { mdxPlugin } from './plugins/mdx-plugin';\nimport { noFouc } from './plugins/no-fouc';\nimport { sourceLoaderPlugin } from './source-loader-plugin';\n\nimport type { UserConfig } from 'vite';\nimport type { ExtendedOptions } from './types';\n\nexport type PluginConfigType = 'build' | 'development';\n\nexport function readPackageJson(): Record<string, any> | false {\n const packageJsonPath = path.resolve('package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const jsonContent = fs.readFileSync(packageJsonPath, 'utf8');\n return JSON.parse(jsonContent);\n}\n\n// Vite config that is common to development and production mode\nexport async function commonConfig(\n options: ExtendedOptions,\n _type: PluginConfigType\n): Promise<UserConfig & { configFile: false; root: string }> {\n const { framework } = options;\n\n return {\n configFile: false,\n root: path.resolve(options.configDir, '..'),\n cacheDir: 'node_modules/.vite-storybook',\n envPrefix,\n define: {},\n resolve:\n framework === 'vue3'\n ? {\n alias: {\n vue: 'vue/dist/vue.esm-bundler.js',\n },\n }\n : {},\n plugins: await pluginConfig(options, _type),\n };\n}\n\nexport async function pluginConfig(options: ExtendedOptions, _type: PluginConfigType) {\n const { framework, presets } = options;\n const svelteOptions: Record<string, any> = await presets.apply('svelteOptions', {}, options);\n\n const plugins = [\n codeGeneratorPlugin(options),\n mockCoreJs(),\n sourceLoaderPlugin(options),\n mdxPlugin(options),\n noFouc(),\n injectExportOrderPlugin,\n // We need the react plugin here to support MDX.\n viteReact({\n // Do not treat story files as HMR boundaries, storybook itself needs to handle them.\n exclude: [/\\.stories\\.([tj])sx?$/, /node_modules/].concat(framework === 'react' ? [] : [/\\.([tj])sx?$/]),\n }),\n {\n name: 'vite-plugin-storybook-allow',\n enforce: 'post',\n config(config) {\n // if there is no allow list then Vite allows anything in the root directory\n // if there is an allow list then Vite allows anything in the listed directories\n // add the .storybook directory only if there's an allow list so that we don't end up\n // disallowing the root directory unless it's already disallowed\n if (config?.server?.fs?.allow) {\n config.server.fs.allow.push('.storybook');\n }\n },\n },\n ] as Plugin[];\n if (framework === 'vue' || framework === 'vue3') {\n try {\n const vuePlugin = require('@vitejs/plugin-vue');\n plugins.push(vuePlugin());\n const { vueDocgen } = await import('./plugins/vue-docgen');\n plugins.push(vueDocgen());\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n throw new Error(\n '@storybook/builder-vite requires @vitejs/plugin-vue to be installed ' +\n 'when using @storybook/vue or @storybook/vue3.' +\n ' Please install it and start storybook again.'\n );\n }\n throw err;\n }\n }\n if (framework === 'svelte') {\n try {\n const sveltePlugin = require('@sveltejs/vite-plugin-svelte').svelte;\n\n // We need to create two separate svelte plugins, one for stories, and one for other svelte files\n // because stories.svelte files cannot be hot-module-reloaded.\n // Suggested in: https://github.com/sveltejs/vite-plugin-svelte/issues/321#issuecomment-1113205509\n\n // First, create an array containing user exclude patterns, to combine with ours.\n const userExclude = Array.isArray(svelteOptions?.exclude)\n ? svelteOptions?.exclude\n : svelteOptions?.exclude\n ? [svelteOptions?.exclude]\n : [];\n\n // These are the svelte stories we need to exclude from HMR\n const storyPatterns = ['**/*.story.svelte', '**/*.stories.svelte'];\n // Non-story svelte files\n // Starting in 1.0.0-next.42, svelte.config.js is included by default.\n // We disable that, but allow it to be overridden in svelteOptions\n plugins.push(sveltePlugin({ configFile: false, ...svelteOptions, exclude: [...userExclude, ...storyPatterns] }));\n // Svelte stories without HMR\n const storySveltePlugin = sveltePlugin({\n configFile: false,\n ...svelteOptions,\n exclude: userExclude,\n include: storyPatterns,\n hot: false,\n });\n plugins.push({\n // Starting in 1.0.0-next.43, the plugin function returns an array of plugins. We only want the first one here.\n ...(Array.isArray(storySveltePlugin) ? storySveltePlugin[0] : storySveltePlugin),\n name: 'vite-plugin-svelte-stories',\n });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n throw new Error(\n '@storybook/builder-vite requires @sveltejs/vite-plugin-svelte to be installed' +\n ' when using @storybook/svelte.' +\n ' Please install it and start storybook again.'\n );\n }\n throw err;\n }\n\n try {\n const csfPlugin = require('./svelte/csf-plugin').default;\n plugins.push(csfPlugin(svelteOptions));\n } catch (err) {\n // Not all projects use `.stories.svelte` for stories, and by default 6.5+ does not auto-install @storybook/addon-svelte-csf.\n // If it's any other kind of error, re-throw.\n if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {\n throw err;\n }\n }\n\n const { svelteDocgen } = await import('./plugins/svelte-docgen');\n plugins.push(svelteDocgen(svelteOptions));\n }\n\n if (framework === 'preact') {\n plugins.push(require('@preact/preset-vite').default());\n }\n\n if (framework === 'react') {\n const { reactDocgen, reactDocgenTypescriptOptions } = await presets.apply('typescript', {} as TypescriptConfig);\n\n let typescriptPresent;\n\n try {\n const pkgJson = readPackageJson();\n typescriptPresent = pkgJson && (pkgJson?.devDependencies?.typescript || pkgJson?.dependencies?.typescript);\n } catch (e) {\n typescriptPresent = false;\n }\n\n if (reactDocgen === 'react-docgen-typescript' && typescriptPresent) {\n plugins.push(require('@joshwooding/vite-plugin-react-docgen-typescript').default(reactDocgenTypescriptOptions));\n } else if (reactDocgen) {\n const { reactDocgen } = await import('./plugins/react-docgen');\n // Needs to run before the react plugin, so add to the front\n plugins.unshift(reactDocgen());\n }\n }\n\n if (framework === 'glimmerx') {\n const plugin = require('vite-plugin-glimmerx/index.cjs');\n plugins.push(plugin.default());\n }\n\n return plugins;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { parse } from 'es-module-lexer';
2
+ import MagicString from 'magic-string';
2
3
 
3
4
  export const injectExportOrderPlugin = {
4
5
  name: 'storybook-vite-inject-export-order-plugin',
@@ -17,12 +18,12 @@ export const injectExportOrderPlugin = {
17
18
  // user has defined named exports already
18
19
  return;
19
20
  }
20
-
21
+ const s = new MagicString(code);
21
22
  const orderedExports = exports.filter((e) => e !== 'default');
22
-
23
+ s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`);
23
24
  return {
24
- code: `${code};\nexport const __namedExportsOrder = ${JSON.stringify(orderedExports)};`,
25
- map: null,
25
+ code: s.toString(),
26
+ map: s.generateMap({ hires: true, source: id }),
26
27
  };
27
28
  },
28
29
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/builder-vite",
3
- "version": "0.1.38",
3
+ "version": "0.1.41",
4
4
  "description": "A plugin to run and build Storybooks with Vite",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -49,18 +49,26 @@ export function mdxPlugin(options: Options): Plugin {
49
49
  );
50
50
  reactRefresh = reactRefreshPlugins.find((p) => p.transform);
51
51
  },
52
- async transform(code, id, options) {
53
- if (id.endsWith('.mdx')) {
52
+ async transform(src, id, options) {
53
+ if (id.match(/\.mdx?$/)) {
54
54
  // @ts-ignore
55
55
  const { compile } = features?.previewMdx2
56
56
  ? await import('@storybook/mdx2-csf')
57
57
  : await import('@storybook/mdx1-csf');
58
58
 
59
- const mdxCode = String(await compile(code, { skipCsf: !isStorybookMdx(id) }));
59
+ const mdxCode = String(await compile(src, { skipCsf: !isStorybookMdx(id) }));
60
60
 
61
61
  const modifiedCode = injectRenderer(mdxCode, Boolean(features?.previewMdx2));
62
62
 
63
- return reactRefresh?.transform!.call(this, modifiedCode, `${id}.jsx`, options);
63
+ const result = await reactRefresh?.transform!.call(this, modifiedCode, `${id}.jsx`, options);
64
+
65
+ if (!result) return modifiedCode;
66
+
67
+ if (typeof result === 'string') return result;
68
+
69
+ const { code, map: resultMap } = result;
70
+
71
+ return { code, map: !resultMap || typeof resultMap === 'string' ? resultMap : { ...resultMap, sources: [id] } };
64
72
  }
65
73
  },
66
74
  };
@@ -51,7 +51,7 @@ export function reactDocgen({ include = /\.(mjs|tsx?|jsx?)$/, exclude = [/node_m
51
51
 
52
52
  return {
53
53
  code: s.toString(),
54
- map: s.generateMap(),
54
+ map: s.generateMap({ hires: true, source: id }),
55
55
  };
56
56
  } catch (e) {
57
57
  // Usually this is just an error from react-docgen that it couldn't find a component
@@ -89,7 +89,7 @@ export function svelteDocgen(svelteOptions: Record<string, any>): Plugin {
89
89
 
90
90
  return {
91
91
  code: s.toString(),
92
- map: s.generateMap(),
92
+ map: s.generateMap({ hires: true, source: id }),
93
93
  };
94
94
  }
95
95
  },
@@ -15,7 +15,7 @@ export function vueDocgen(): Plugin {
15
15
 
16
16
  return {
17
17
  code: s.toString(),
18
- map: s.generateMap(),
18
+ map: s.generateMap({ hires: true, source: id }),
19
19
  };
20
20
  }
21
21
  },
@@ -1,6 +1,7 @@
1
1
  import type { Plugin } from 'vite';
2
2
  import sourceLoaderTransform from '@storybook/source-loader';
3
3
  import type { ExtendedOptions } from './types';
4
+ import MagicString from 'magic-string';
4
5
 
5
6
  const storyPattern = /\.stories\.[jt]sx?$/;
6
7
  const storySourcePattern = /var __STORY__ = "(.*)"/;
@@ -21,10 +22,13 @@ export function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {
21
22
  async transform(src: string, id: string) {
22
23
  if (id.match(storyPattern)) {
23
24
  const code: string = await sourceLoaderTransform.call(mockClassLoader(id), src);
25
+ const s = new MagicString(src);
26
+ // Entirely replace with new code
27
+ s.overwrite(0, src.length, code);
24
28
 
25
29
  return {
26
- code,
27
- map: { mappings: '' },
30
+ code: s.toString(),
31
+ map: s.generateMap({ hires: true, source: id }),
28
32
  };
29
33
  }
30
34
  },
@@ -53,9 +57,13 @@ export function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {
53
57
  code = replaceAll(code, sourceString, storySourceReplacement);
54
58
  }
55
59
 
60
+ const s = new MagicString(src);
61
+ // Entirely replace with new code
62
+ s.overwrite(0, src.length, code);
63
+
56
64
  return {
57
- code,
58
- map: { mappings: '' },
65
+ code: s.toString(),
66
+ map: s.generateMap(),
59
67
  };
60
68
  }
61
69
  },
@@ -68,19 +76,18 @@ export function sourceLoaderPlugin(config: ExtendedOptions): Plugin | Plugin[] {
68
76
  },
69
77
  async transform(src: string, id: string) {
70
78
  if (id.match(storyPattern)) {
71
- let code;
79
+ const s = new MagicString(src);
72
80
  const map = storySources.get(config);
73
81
  const storySourceStatement = map?.get(id);
74
82
  // Put the previously-extracted source back in
75
83
  if (storySourceStatement) {
76
- code = replaceAll(src, storySourceReplacement, storySourceStatement);
77
- } else {
78
- code = src;
84
+ const newCode = replaceAll(src, storySourceReplacement, storySourceStatement);
85
+ s.overwrite(0, src.length, newCode);
79
86
  }
80
87
 
81
88
  return {
82
- code,
83
- map: { mappings: '' },
89
+ code: s.toString(),
90
+ map: s.generateMap(),
84
91
  };
85
92
  }
86
93
  },
@@ -4,6 +4,7 @@ import { extractStories } from '@storybook/addon-svelte-csf/dist/cjs/parser/extr
4
4
  const parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\]/g, '/');
5
5
  import type { Options } from '@sveltejs/vite-plugin-svelte';
6
6
  import * as svelte from 'svelte/compiler';
7
+ import MagicString from 'magic-string';
7
8
 
8
9
  export default function csfPlugin(svelteOptions?: Options) {
9
10
  return {
@@ -11,6 +12,7 @@ export default function csfPlugin(svelteOptions?: Options) {
11
12
  enforce: 'post',
12
13
  async transform(code: string, id: string) {
13
14
  if (/\.stories\.svelte$/.test(id)) {
15
+ const s = new MagicString(code);
14
16
  const component = getNameFromFilename(id);
15
17
  let source = readFileSync(id).toString();
16
18
  if (svelteOptions && svelteOptions.preprocess) {
@@ -23,22 +25,26 @@ export default function csfPlugin(svelteOptions?: Options) {
23
25
  .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}];`)
24
26
  .join('\n');
25
27
 
26
- const codeWithoutDefaultExport = code.replace('export default ', '// export default ');
28
+ s.replace('export default', '// export default');
27
29
 
28
30
  const namedExportsOrder = Object.entries<any>(stories)
29
31
  .filter(([, def]) => !def.template)
30
32
  .map(([id]) => id);
31
33
 
32
34
  const output = [
33
- codeWithoutDefaultExport,
35
+ '',
34
36
  `import parser from '${parser}';`,
35
37
  `const __storiesMetaData = parser(${component}, ${JSON.stringify(all)});`,
36
38
  'export default __storiesMetaData.meta;',
37
39
  `export const __namedExportsOrder = ${JSON.stringify(namedExportsOrder)};`,
38
40
  storyDef,
39
41
  ].join('\n');
42
+
43
+ s.append(output);
44
+
40
45
  return {
41
- code: output,
46
+ code: s.toString(),
47
+ map: s.generateMap({ hires: true, source: id }),
42
48
  };
43
49
  }
44
50
  },
package/vite-config.ts CHANGED
@@ -68,6 +68,19 @@ export async function pluginConfig(options: ExtendedOptions, _type: PluginConfig
68
68
  // Do not treat story files as HMR boundaries, storybook itself needs to handle them.
69
69
  exclude: [/\.stories\.([tj])sx?$/, /node_modules/].concat(framework === 'react' ? [] : [/\.([tj])sx?$/]),
70
70
  }),
71
+ {
72
+ name: 'vite-plugin-storybook-allow',
73
+ enforce: 'post',
74
+ config(config) {
75
+ // if there is no allow list then Vite allows anything in the root directory
76
+ // if there is an allow list then Vite allows anything in the listed directories
77
+ // add the .storybook directory only if there's an allow list so that we don't end up
78
+ // disallowing the root directory unless it's already disallowed
79
+ if (config?.server?.fs?.allow) {
80
+ config.server.fs.allow.push('.storybook');
81
+ }
82
+ },
83
+ },
71
84
  ] as Plugin[];
72
85
  if (framework === 'vue' || framework === 'vue3') {
73
86
  try {
package/mdx-plugin.ts DELETED
File without changes