From ac7ea8f81283502bc9f6a3bead7b428673b093a5 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 03:41:07 +0300 Subject: [PATCH 01/29] Created `tsconfig.json` for Node.js 16 --- tsconfig.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 tsconfig.json diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..01e7052f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "module": "CommonJS", + "target": "ES2021" + } +} From 59113e6b95ea32400bce2d97ea2dd77cc716d765 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 04:54:51 +0300 Subject: [PATCH 02/29] Created `tsconfig.json` in `packages/storybook-builder-vite` directory --- packages/storybook-builder-vite/tsconfig.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 packages/storybook-builder-vite/tsconfig.json diff --git a/packages/storybook-builder-vite/tsconfig.json b/packages/storybook-builder-vite/tsconfig.json new file mode 100644 index 00000000..d2e9a528 --- /dev/null +++ b/packages/storybook-builder-vite/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist" + } +} From 4089a745a29901dccba14521d8e46dabf522e86a Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Thu, 6 Jan 2022 23:02:28 +0300 Subject: [PATCH 03/29] Renamed `*.js` files to `*.ts` files in `packages/storybook-builder-vite` directory --- packages/storybook-builder-vite/{build.js => build.ts} | 0 .../{code-generator-plugin.js => code-generator-plugin.ts} | 0 .../{codegen-iframe-script.js => codegen-iframe-script.ts} | 0 .../{codegen-importfn-script.js => codegen-importfn-script.ts} | 0 ...en-modern-iframe-script.js => codegen-modern-iframe-script.ts} | 0 packages/storybook-builder-vite/{envs.js => envs.ts} | 0 packages/storybook-builder-vite/{index.js => index.ts} | 0 ...nject-export-order-plugin.js => inject-export-order-plugin.ts} | 0 packages/storybook-builder-vite/{mdx-plugin.js => mdx-plugin.ts} | 0 .../storybook-builder-vite/{mock-core-js.js => mock-core-js.ts} | 0 .../storybook-builder-vite/{optimizeDeps.js => optimizeDeps.ts} | 0 .../plugins/{vue-docgen.js => vue-docgen.ts} | 0 .../{source-loader-plugin.js => source-loader-plugin.ts} | 0 .../svelte/{csf-plugin.js => csf-plugin.ts} | 0 .../{transform-iframe-html.js => transform-iframe-html.ts} | 0 .../storybook-builder-vite/{vite-config.js => vite-config.ts} | 0 .../storybook-builder-vite/{vite-server.js => vite-server.ts} | 0 17 files changed, 0 insertions(+), 0 deletions(-) rename packages/storybook-builder-vite/{build.js => build.ts} (100%) rename packages/storybook-builder-vite/{code-generator-plugin.js => code-generator-plugin.ts} (100%) rename packages/storybook-builder-vite/{codegen-iframe-script.js => codegen-iframe-script.ts} (100%) rename packages/storybook-builder-vite/{codegen-importfn-script.js => codegen-importfn-script.ts} (100%) rename packages/storybook-builder-vite/{codegen-modern-iframe-script.js => codegen-modern-iframe-script.ts} (100%) rename packages/storybook-builder-vite/{envs.js => envs.ts} (100%) rename packages/storybook-builder-vite/{index.js => index.ts} (100%) rename packages/storybook-builder-vite/{inject-export-order-plugin.js => inject-export-order-plugin.ts} (100%) rename packages/storybook-builder-vite/{mdx-plugin.js => mdx-plugin.ts} (100%) rename packages/storybook-builder-vite/{mock-core-js.js => mock-core-js.ts} (100%) rename packages/storybook-builder-vite/{optimizeDeps.js => optimizeDeps.ts} (100%) rename packages/storybook-builder-vite/plugins/{vue-docgen.js => vue-docgen.ts} (100%) rename packages/storybook-builder-vite/{source-loader-plugin.js => source-loader-plugin.ts} (100%) rename packages/storybook-builder-vite/svelte/{csf-plugin.js => csf-plugin.ts} (100%) rename packages/storybook-builder-vite/{transform-iframe-html.js => transform-iframe-html.ts} (100%) rename packages/storybook-builder-vite/{vite-config.js => vite-config.ts} (100%) rename packages/storybook-builder-vite/{vite-server.js => vite-server.ts} (100%) diff --git a/packages/storybook-builder-vite/build.js b/packages/storybook-builder-vite/build.ts similarity index 100% rename from packages/storybook-builder-vite/build.js rename to packages/storybook-builder-vite/build.ts diff --git a/packages/storybook-builder-vite/code-generator-plugin.js b/packages/storybook-builder-vite/code-generator-plugin.ts similarity index 100% rename from packages/storybook-builder-vite/code-generator-plugin.js rename to packages/storybook-builder-vite/code-generator-plugin.ts diff --git a/packages/storybook-builder-vite/codegen-iframe-script.js b/packages/storybook-builder-vite/codegen-iframe-script.ts similarity index 100% rename from packages/storybook-builder-vite/codegen-iframe-script.js rename to packages/storybook-builder-vite/codegen-iframe-script.ts diff --git a/packages/storybook-builder-vite/codegen-importfn-script.js b/packages/storybook-builder-vite/codegen-importfn-script.ts similarity index 100% rename from packages/storybook-builder-vite/codegen-importfn-script.js rename to packages/storybook-builder-vite/codegen-importfn-script.ts diff --git a/packages/storybook-builder-vite/codegen-modern-iframe-script.js b/packages/storybook-builder-vite/codegen-modern-iframe-script.ts similarity index 100% rename from packages/storybook-builder-vite/codegen-modern-iframe-script.js rename to packages/storybook-builder-vite/codegen-modern-iframe-script.ts diff --git a/packages/storybook-builder-vite/envs.js b/packages/storybook-builder-vite/envs.ts similarity index 100% rename from packages/storybook-builder-vite/envs.js rename to packages/storybook-builder-vite/envs.ts diff --git a/packages/storybook-builder-vite/index.js b/packages/storybook-builder-vite/index.ts similarity index 100% rename from packages/storybook-builder-vite/index.js rename to packages/storybook-builder-vite/index.ts diff --git a/packages/storybook-builder-vite/inject-export-order-plugin.js b/packages/storybook-builder-vite/inject-export-order-plugin.ts similarity index 100% rename from packages/storybook-builder-vite/inject-export-order-plugin.js rename to packages/storybook-builder-vite/inject-export-order-plugin.ts diff --git a/packages/storybook-builder-vite/mdx-plugin.js b/packages/storybook-builder-vite/mdx-plugin.ts similarity index 100% rename from packages/storybook-builder-vite/mdx-plugin.js rename to packages/storybook-builder-vite/mdx-plugin.ts diff --git a/packages/storybook-builder-vite/mock-core-js.js b/packages/storybook-builder-vite/mock-core-js.ts similarity index 100% rename from packages/storybook-builder-vite/mock-core-js.js rename to packages/storybook-builder-vite/mock-core-js.ts diff --git a/packages/storybook-builder-vite/optimizeDeps.js b/packages/storybook-builder-vite/optimizeDeps.ts similarity index 100% rename from packages/storybook-builder-vite/optimizeDeps.js rename to packages/storybook-builder-vite/optimizeDeps.ts diff --git a/packages/storybook-builder-vite/plugins/vue-docgen.js b/packages/storybook-builder-vite/plugins/vue-docgen.ts similarity index 100% rename from packages/storybook-builder-vite/plugins/vue-docgen.js rename to packages/storybook-builder-vite/plugins/vue-docgen.ts diff --git a/packages/storybook-builder-vite/source-loader-plugin.js b/packages/storybook-builder-vite/source-loader-plugin.ts similarity index 100% rename from packages/storybook-builder-vite/source-loader-plugin.js rename to packages/storybook-builder-vite/source-loader-plugin.ts diff --git a/packages/storybook-builder-vite/svelte/csf-plugin.js b/packages/storybook-builder-vite/svelte/csf-plugin.ts similarity index 100% rename from packages/storybook-builder-vite/svelte/csf-plugin.js rename to packages/storybook-builder-vite/svelte/csf-plugin.ts diff --git a/packages/storybook-builder-vite/transform-iframe-html.js b/packages/storybook-builder-vite/transform-iframe-html.ts similarity index 100% rename from packages/storybook-builder-vite/transform-iframe-html.js rename to packages/storybook-builder-vite/transform-iframe-html.ts diff --git a/packages/storybook-builder-vite/vite-config.js b/packages/storybook-builder-vite/vite-config.ts similarity index 100% rename from packages/storybook-builder-vite/vite-config.js rename to packages/storybook-builder-vite/vite-config.ts diff --git a/packages/storybook-builder-vite/vite-server.js b/packages/storybook-builder-vite/vite-server.ts similarity index 100% rename from packages/storybook-builder-vite/vite-server.js rename to packages/storybook-builder-vite/vite-server.ts From b0c59b67b4b6fe4525ef2414555d531c185661db Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 05:26:22 +0300 Subject: [PATCH 04/29] Converted from `require()` and `module.exports` to `import` and `export` # Conflicts: # packages/storybook-builder-vite/index.ts # packages/storybook-builder-vite/vite-config.ts --- packages/storybook-builder-vite/build.ts | 12 +++++----- .../code-generator-plugin.ts | 16 +++++++------- .../codegen-iframe-script.ts | 12 +++++----- .../codegen-importfn-script.ts | 10 ++++----- .../codegen-modern-iframe-script.ts | 11 ++++------ packages/storybook-builder-vite/envs.ts | 8 +++---- packages/storybook-builder-vite/index.ts | 22 +++++++++---------- .../inject-export-order-plugin.ts | 4 ++-- packages/storybook-builder-vite/mdx-plugin.ts | 8 +++---- .../storybook-builder-vite/mock-core-js.ts | 4 ++-- .../storybook-builder-vite/optimizeDeps.ts | 7 +++--- .../plugins/vue-docgen.ts | 6 ++--- .../source-loader-plugin.ts | 6 ++--- .../svelte/csf-plugin.ts | 8 +++---- .../transform-iframe-html.ts | 7 ++---- .../storybook-builder-vite/vite-config.ts | 14 ++++++------ .../storybook-builder-vite/vite-server.ts | 14 ++++++------ 17 files changed, 82 insertions(+), 87 deletions(-) diff --git a/packages/storybook-builder-vite/build.ts b/packages/storybook-builder-vite/build.ts index 4228e581..dc038089 100644 --- a/packages/storybook-builder-vite/build.ts +++ b/packages/storybook-builder-vite/build.ts @@ -1,9 +1,9 @@ -const path = require('path'); -const { stringifyProcessEnvs, allowedEnvPrefix: envPrefix } = require('./envs'); -const { pluginConfig } = require('./vite-config'); -const { build: viteBuild } = require('vite'); +import * as path from 'path'; +import { allowedEnvPrefix as envPrefix, stringifyProcessEnvs } from './envs'; +import { pluginConfig } from './vite-config'; +import { build as viteBuild } from 'vite'; -module.exports.build = async function build(options) { +export async function build(options) { const { presets } = options; const config = { @@ -36,4 +36,4 @@ module.exports.build = async function build(options) { }; await viteBuild(finalConfig); -}; +} diff --git a/packages/storybook-builder-vite/code-generator-plugin.ts b/packages/storybook-builder-vite/code-generator-plugin.ts index 5d55db99..e31e8a37 100644 --- a/packages/storybook-builder-vite/code-generator-plugin.ts +++ b/packages/storybook-builder-vite/code-generator-plugin.ts @@ -1,11 +1,11 @@ -const fs = require('fs'); -const path = require('path'); -const { transformIframeHtml } = require('./transform-iframe-html'); -const { generateIframeScriptCode } = require('./codegen-iframe-script'); -const { generateModernIframeScriptCode } = require('./codegen-modern-iframe-script'); -const { generateImportFnScriptCode } = require('./codegen-importfn-script'); +import * as fs from 'fs'; +import * as path from 'path'; +import { transformIframeHtml } from './transform-iframe-html'; +import { generateIframeScriptCode } from './codegen-iframe-script'; +import { generateModernIframeScriptCode } from './codegen-modern-iframe-script'; +import { generateImportFnScriptCode } from './codegen-importfn-script'; -module.exports.codeGeneratorPlugin = function codeGeneratorPlugin(options) { +export function codeGeneratorPlugin(options) { const virtualFileId = '/virtual:/@storybook/builder-vite/vite-app.js'; const virtualStoriesFile = '/virtual:/@storybook/builder-vite/storybook-stories.js'; const iframePath = path.resolve(__dirname, 'input', 'iframe.html'); @@ -77,4 +77,4 @@ module.exports.codeGeneratorPlugin = function codeGeneratorPlugin(options) { return transformIframeHtml(html, options); }, }; -}; +} diff --git a/packages/storybook-builder-vite/codegen-iframe-script.ts b/packages/storybook-builder-vite/codegen-iframe-script.ts index d3710db4..a7d8b1a6 100644 --- a/packages/storybook-builder-vite/codegen-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-iframe-script.ts @@ -1,7 +1,7 @@ -const path = require('path'); -const glob = require('glob-promise'); -const { normalizePath } = require('vite'); -const { loadPreviewOrConfigFile } = require('@storybook/core-common'); +import * as path from 'path'; +import * as glob from 'glob-promise'; +import { normalizePath } from 'vite'; +import { loadPreviewOrConfigFile } from '@storybook/core-common'; // This is somewhat of a hack; the problem is that previewEntries resolves to // the CommonJS imports, probably because require.resolve in Node.js land leads @@ -10,7 +10,7 @@ function replaceCJStoESMPath(entryPath) { return entryPath.replace('/cjs/', '/esm/'); } -module.exports.generateIframeScriptCode = async function generateIframeScriptCode(options) { +export async function generateIframeScriptCode(options) { const { presets, configDir, framework, frameworkPath } = options; const previewEntries = (await presets.apply('previewEntries', [], options)).map(replaceCJStoESMPath); @@ -109,4 +109,4 @@ module.exports.generateIframeScriptCode = async function generateIframeScriptCod )}.filter(el => el.default), { hot: import.meta.hot }, false); // not sure if the import.meta.hot thing is correct `.trim(); return code; -}; +} diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index 9cd67a8d..9db94e1a 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -1,6 +1,6 @@ -const glob = require('glob-promise'); -const path = require('path'); -const { normalizePath } = require('vite'); +import * as glob from 'glob-promise'; +import * as path from 'path'; +import { normalizePath } from 'vite'; /** * This file is largely based on https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/core-common/src/utils/to-importFn.ts @@ -42,7 +42,7 @@ async function toImportFn(stories) { `; } -module.exports.generateImportFnScriptCode = async function generateImportFnScriptCode(options) { +export async function generateImportFnScriptCode(options) { // First we need to get an array of stories and their absolute paths. const stories = ( await Promise.all( @@ -54,4 +54,4 @@ module.exports.generateImportFnScriptCode = async function generateImportFnScrip // We can then call toImportFn to create a function that can be used to load each story dynamically. return (await toImportFn(stories)).trim(); -}; +} diff --git a/packages/storybook-builder-vite/codegen-modern-iframe-script.ts b/packages/storybook-builder-vite/codegen-modern-iframe-script.ts index b4b16391..a767c2f6 100644 --- a/packages/storybook-builder-vite/codegen-modern-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-modern-iframe-script.ts @@ -1,10 +1,7 @@ -const { loadPreviewOrConfigFile } = require('@storybook/core-common'); -const { normalizePath } = require('vite'); +import { loadPreviewOrConfigFile } from '@storybook/core-common'; +import { normalizePath } from 'vite'; -module.exports.generateModernIframeScriptCode = async function generateModernIframeScriptCode( - options, - { storiesFilename } -) { +export async function generateModernIframeScriptCode(options, { storiesFilename }) { const { presets, configDir } = options; const previewOrConfigFile = loadPreviewOrConfigFile({ configDir }); @@ -76,4 +73,4 @@ module.exports.generateModernIframeScriptCode = async function generateModernIfr } `.trim(); return code; -}; +} diff --git a/packages/storybook-builder-vite/envs.ts b/packages/storybook-builder-vite/envs.ts index f5564fa1..db0de584 100644 --- a/packages/storybook-builder-vite/envs.ts +++ b/packages/storybook-builder-vite/envs.ts @@ -1,4 +1,4 @@ -const { stringifyEnvs } = require('@storybook/core-common'); +import { stringifyEnvs } from '@storybook/core-common'; // Allowed env variables on the client const allowedEnvVariables = [ @@ -13,7 +13,7 @@ const allowedEnvVariables = [ ]; // Env variables starts with env prefix will be exposed to your client source code via `import.meta.env` -module.exports.allowedEnvPrefix = ['VITE_', 'STORYBOOK_']; +export const allowedEnvPrefix = ['VITE_', 'STORYBOOK_']; /** * Customized version of stringifyProcessEnvs from @storybook/core-common which @@ -21,7 +21,7 @@ module.exports.allowedEnvPrefix = ['VITE_', 'STORYBOOK_']; * @param {Object} raw * @param {string[]|string} envPrefix */ -module.exports.stringifyProcessEnvs = function stringifyProcessEnvs(raw, envPrefix) { +export function stringifyProcessEnvs(raw, envPrefix) { const updatedRaw = {}; const envs = Object.entries(raw).reduce( (acc, [key, value]) => { @@ -46,4 +46,4 @@ module.exports.stringifyProcessEnvs = function stringifyProcessEnvs(raw, envPref envs['import.meta.env'] = JSON.stringify(stringifyEnvs(updatedRaw)); return envs; -}; +} diff --git a/packages/storybook-builder-vite/index.ts b/packages/storybook-builder-vite/index.ts index 86f01486..154dbaaa 100644 --- a/packages/storybook-builder-vite/index.ts +++ b/packages/storybook-builder-vite/index.ts @@ -1,10 +1,10 @@ // noinspection JSUnusedGlobalSymbols -const fs = require('fs'); -const path = require('path'); -const { transformIframeHtml } = require('./transform-iframe-html'); -const { createViteServer } = require('./vite-server.js'); -const { build: viteBuild } = require('./build'); +import * as fs from 'fs'; +import * as path from 'path'; +import { transformIframeHtml } from './transform-iframe-html'; +import { createViteServer } from './vite-server.js'; +import { build as viteBuild } from './build'; function iframeMiddleware(options, server) { return async (req, res, next) => { @@ -20,7 +20,7 @@ function iframeMiddleware(options, server) { }; } -module.exports.start = async function start({ startTime, options, router, server: devServer }) { +export async function start({ startTime, options, router, server: devServer }) { const server = await createViteServer(options, devServer); // Just mock this endpoint (which is really Webpack-specific) so we don't get spammed with 404 in browser devtools @@ -47,11 +47,11 @@ module.exports.start = async function start({ startTime, options, router, server bail, totalTime: process.hrtime(startTime), }; -}; +} -module.exports.build = async function build({ options }) { +export async function build({ options }) { return viteBuild(options); -}; +} -module.exports.corePresets = []; -module.exports.previewPresets = []; +export const corePresets = []; +export const previewPresets = []; diff --git a/packages/storybook-builder-vite/inject-export-order-plugin.ts b/packages/storybook-builder-vite/inject-export-order-plugin.ts index bdf25831..cbea45de 100644 --- a/packages/storybook-builder-vite/inject-export-order-plugin.ts +++ b/packages/storybook-builder-vite/inject-export-order-plugin.ts @@ -1,6 +1,6 @@ -const { parse } = require('es-module-lexer'); +import { parse } from 'es-module-lexer'; -module.exports.injectExportOrderPlugin = { +export const injectExportOrderPlugin = { name: 'storybook-vite-inject-export-order-plugin', // This should only run after the typescript has been transpiled enforce: 'post', diff --git a/packages/storybook-builder-vite/mdx-plugin.ts b/packages/storybook-builder-vite/mdx-plugin.ts index bbdd0578..bcaf52e8 100644 --- a/packages/storybook-builder-vite/mdx-plugin.ts +++ b/packages/storybook-builder-vite/mdx-plugin.ts @@ -1,5 +1,5 @@ -const mdx = require('vite-plugin-mdx').default; -const { createCompiler } = require('@storybook/csf-tools/mdx'); +import mdx from 'vite-plugin-mdx'; +import { createCompiler } from '@storybook/csf-tools/mdx'; /** * Storybook uses two different loaders when dealing with MDX: @@ -9,7 +9,7 @@ const { createCompiler } = require('@storybook/csf-tools/mdx'); * * @see https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/recipes.md#csf-stories-with-arbitrary-mdx */ -module.exports.mdxPlugin = function () { +export function mdxPlugin() { return mdx((filename) => { const compilers = []; @@ -21,4 +21,4 @@ module.exports.mdxPlugin = function () { compilers, }; }); -}; +} diff --git a/packages/storybook-builder-vite/mock-core-js.ts b/packages/storybook-builder-vite/mock-core-js.ts index 19789f14..5fa9ba1c 100644 --- a/packages/storybook-builder-vite/mock-core-js.ts +++ b/packages/storybook-builder-vite/mock-core-js.ts @@ -1,4 +1,4 @@ -module.exports.mockCoreJs = function mockCoreJs() { +export function mockCoreJs() { return { name: 'mock-core-js', resolveId(id) { @@ -14,4 +14,4 @@ module.exports.mockCoreJs = function mockCoreJs() { return undefined; }, }; -}; +} diff --git a/packages/storybook-builder-vite/optimizeDeps.ts b/packages/storybook-builder-vite/optimizeDeps.ts index 86856b3c..1d9038c5 100644 --- a/packages/storybook-builder-vite/optimizeDeps.ts +++ b/packages/storybook-builder-vite/optimizeDeps.ts @@ -1,5 +1,6 @@ -const path = require('path'); -module.exports.getOptimizeDeps = async (root, options) => { +import * as path from 'path'; + +export async function getOptimizeDeps(root, options) { const stories = await Promise.all( ( await options.presets.apply('stories', [], options) @@ -105,4 +106,4 @@ module.exports.getOptimizeDeps = async (root, options) => { } }), }; -}; +} diff --git a/packages/storybook-builder-vite/plugins/vue-docgen.ts b/packages/storybook-builder-vite/plugins/vue-docgen.ts index 25c318de..2c0d206d 100644 --- a/packages/storybook-builder-vite/plugins/vue-docgen.ts +++ b/packages/storybook-builder-vite/plugins/vue-docgen.ts @@ -1,6 +1,6 @@ -const { parse } = require('vue-docgen-api'); +import { parse } from 'vue-docgen-api'; -module.exports = function () { +export default function () { return { name: 'vue-docgen', @@ -13,4 +13,4 @@ module.exports = function () { } }, }; -}; +} diff --git a/packages/storybook-builder-vite/source-loader-plugin.ts b/packages/storybook-builder-vite/source-loader-plugin.ts index 64e64ab8..cdcfb515 100644 --- a/packages/storybook-builder-vite/source-loader-plugin.ts +++ b/packages/storybook-builder-vite/source-loader-plugin.ts @@ -1,6 +1,6 @@ -const sourceLoaderTransform = require('@storybook/source-loader').default; +import sourceLoaderTransform from '@storybook/source-loader'; -module.exports.sourceLoaderPlugin = function () { +export function sourceLoaderPlugin() { return { name: 'storybook-vite-source-loader-plugin', enforce: 'pre', @@ -18,4 +18,4 @@ module.exports.sourceLoaderPlugin = function () { } }, }; -}; +} diff --git a/packages/storybook-builder-vite/svelte/csf-plugin.ts b/packages/storybook-builder-vite/svelte/csf-plugin.ts index cdc1d46a..bf00b2cb 100644 --- a/packages/storybook-builder-vite/svelte/csf-plugin.ts +++ b/packages/storybook-builder-vite/svelte/csf-plugin.ts @@ -1,9 +1,9 @@ -const { getNameFromFilename } = require('@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader'); -const { readFileSync } = require('fs'); -const { extractStories } = require('@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories'); +import { getNameFromFilename } from '@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader'; +import { readFileSync } from 'fs'; +import { extractStories } from '@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories'; const parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\]/g, '/'); -module.exports = { +export default { name: 'storybook-addon-svelte-csf', enforce: 'post', transform(code, id) { diff --git a/packages/storybook-builder-vite/transform-iframe-html.ts b/packages/storybook-builder-vite/transform-iframe-html.ts index 6a9c1c0d..c0717258 100644 --- a/packages/storybook-builder-vite/transform-iframe-html.ts +++ b/packages/storybook-builder-vite/transform-iframe-html.ts @@ -1,7 +1,4 @@ -module.exports.transformIframeHtml = async function transformIframeHtml( - html, - { configType, features, framework, presets, serverChannelUrl, title } -) { +export async function transformIframeHtml(html, { configType, features, framework, presets, serverChannelUrl, title }) { const headHtmlSnippet = await presets.apply('previewHead'); const bodyHtmlSnippet = await presets.apply('previewBody'); const logLevel = await presets.apply('logLevel', undefined); @@ -21,4 +18,4 @@ module.exports.transformIframeHtml = async function transformIframeHtml( .replace(`'[SERVER_CHANNEL_URL HERE]'`, JSON.stringify(serverChannelUrl)) .replace('', headHtmlSnippet || '') .replace('', bodyHtmlSnippet || ''); -}; +} diff --git a/packages/storybook-builder-vite/vite-config.ts b/packages/storybook-builder-vite/vite-config.ts index cea00d63..eb14e812 100644 --- a/packages/storybook-builder-vite/vite-config.ts +++ b/packages/storybook-builder-vite/vite-config.ts @@ -1,10 +1,10 @@ -const { mockCoreJs } = require('./mock-core-js'); -const { codeGeneratorPlugin } = require('./code-generator-plugin'); -const { injectExportOrderPlugin } = require('./inject-export-order-plugin'); -const { mdxPlugin } = require('./mdx-plugin'); -const { sourceLoaderPlugin } = require('./source-loader-plugin'); +import { mockCoreJs } from './mock-core-js'; +import { codeGeneratorPlugin } from './code-generator-plugin'; +import { injectExportOrderPlugin } from './inject-export-order-plugin'; +import { mdxPlugin } from './mdx-plugin'; +import { sourceLoaderPlugin } from './source-loader-plugin'; -module.exports.pluginConfig = async function pluginConfig(options) { +export async function pluginConfig(options) { const { framework } = options; const svelteOptions = await options.presets.apply('svelteOptions', {}, options); @@ -74,4 +74,4 @@ module.exports.pluginConfig = async function pluginConfig(options) { } return plugins; -}; +} diff --git a/packages/storybook-builder-vite/vite-server.ts b/packages/storybook-builder-vite/vite-server.ts index c47a26af..e6cee3af 100644 --- a/packages/storybook-builder-vite/vite-server.ts +++ b/packages/storybook-builder-vite/vite-server.ts @@ -1,10 +1,10 @@ -const path = require('path'); -const { stringifyProcessEnvs, allowedEnvPrefix: envPrefix } = require('./envs'); -const { getOptimizeDeps } = require('./optimizeDeps'); -const { createServer } = require('vite'); -const { pluginConfig } = require('./vite-config'); +import * as path from 'path'; +import { allowedEnvPrefix as envPrefix, stringifyProcessEnvs } from './envs'; +import { getOptimizeDeps } from './optimizeDeps'; +import { createServer } from 'vite'; +import { pluginConfig } from './vite-config'; -module.exports.createViteServer = async function createViteServer(options, devServer) { +export async function createViteServer(options, devServer) { const { port, presets } = options; const root = path.resolve(options.configDir, '..'); @@ -44,4 +44,4 @@ module.exports.createViteServer = async function createViteServer(options, devSe }; return createServer(finalConfig); -}; +} From f74da306404a7087ba58fe350ced557fa9af3950 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 05:28:39 +0300 Subject: [PATCH 05/29] Temporary fix types for `.filter()` of stories in `svelte/csf-plugin.ts` --- packages/storybook-builder-vite/svelte/csf-plugin.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/storybook-builder-vite/svelte/csf-plugin.ts b/packages/storybook-builder-vite/svelte/csf-plugin.ts index bf00b2cb..029557d7 100644 --- a/packages/storybook-builder-vite/svelte/csf-plugin.ts +++ b/packages/storybook-builder-vite/svelte/csf-plugin.ts @@ -12,14 +12,14 @@ export default { const source = readFileSync(id).toString(); const all = extractStories(source); const { stories } = all; - const storyDef = Object.entries(stories) + const storyDef = Object.entries(stories) .filter(([, def]) => !def.template) .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}];`) .join('\n'); const codeWithoutDefaultExport = code.replace('export default ', '// export default '); - const namedExportsOrder = Object.entries(stories) + const namedExportsOrder = Object.entries(stories) .filter(([, def]) => !def.template) .map(([id]) => id); From 1d08a3ccd89bbe783a4bd7af1af451fbf3f043da Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 05:30:06 +0300 Subject: [PATCH 06/29] Provided empty object to `createCompiler()` function in `mdx-plugin.ts` file --- packages/storybook-builder-vite/mdx-plugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/storybook-builder-vite/mdx-plugin.ts b/packages/storybook-builder-vite/mdx-plugin.ts index bcaf52e8..1f2e3e46 100644 --- a/packages/storybook-builder-vite/mdx-plugin.ts +++ b/packages/storybook-builder-vite/mdx-plugin.ts @@ -14,7 +14,7 @@ export function mdxPlugin() { const compilers = []; if (filename.includes('.stories.')) { - compilers.push(createCompiler()); + compilers.push(createCompiler({})); } return { From 34ec205dc0a1090cca84ba55a38092e4391a1718 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 16:52:17 +0300 Subject: [PATCH 07/29] Importing promisified version of the `glob` from `glob-promise` package --- packages/storybook-builder-vite/codegen-iframe-script.ts | 2 +- packages/storybook-builder-vite/codegen-importfn-script.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/storybook-builder-vite/codegen-iframe-script.ts b/packages/storybook-builder-vite/codegen-iframe-script.ts index a7d8b1a6..37a96a4f 100644 --- a/packages/storybook-builder-vite/codegen-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-iframe-script.ts @@ -1,5 +1,5 @@ import * as path from 'path'; -import * as glob from 'glob-promise'; +import { promise as glob } from 'glob-promise'; import { normalizePath } from 'vite'; import { loadPreviewOrConfigFile } from '@storybook/core-common'; diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index 9db94e1a..b7c8ccf9 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -1,4 +1,4 @@ -import * as glob from 'glob-promise'; +import { promise as glob } from 'glob-promise'; import * as path from 'path'; import { normalizePath } from 'vite'; From c4e51e9104473244200b2a916a5b56862fef7e59 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 16:53:20 +0300 Subject: [PATCH 08/29] Removed wrong extension from import of `createViteServer()` function --- packages/storybook-builder-vite/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/storybook-builder-vite/index.ts b/packages/storybook-builder-vite/index.ts index 154dbaaa..adb4ddd0 100644 --- a/packages/storybook-builder-vite/index.ts +++ b/packages/storybook-builder-vite/index.ts @@ -3,7 +3,7 @@ import * as fs from 'fs'; import * as path from 'path'; import { transformIframeHtml } from './transform-iframe-html'; -import { createViteServer } from './vite-server.js'; +import { createViteServer } from './vite-server'; import { build as viteBuild } from './build'; function iframeMiddleware(options, server) { From df8f27f9de6777805235624ed9a98c37c84778c3 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 19:23:50 +0300 Subject: [PATCH 09/29] Ignoring the `dist` directory --- .eslintignore | 1 + .gitignore | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.eslintignore b/.eslintignore index f3e738f4..19b6425a 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ .github .yarn storybook-static +dist diff --git a/.gitignore b/.gitignore index 8ff1e82c..98a14e07 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ node_modules storybook-static .idea +# TypeScript +dist # Yarn stuff /**/.yarn/* From c7e1fe2824b689f09bd7d8515d59c35618171706 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 19:24:46 +0300 Subject: [PATCH 10/29] Using the `dist` directory: updated `main` field; created `types` field in `storybook-builder-vite/package.json` # Conflicts: # packages/storybook-builder-vite/package.json --- packages/storybook-builder-vite/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/storybook-builder-vite/package.json b/packages/storybook-builder-vite/package.json index 31c3c354..4934e835 100644 --- a/packages/storybook-builder-vite/package.json +++ b/packages/storybook-builder-vite/package.json @@ -2,7 +2,8 @@ "name": "storybook-builder-vite", "version": "0.1.13", "description": "An experimental plugin to run and build Storybooks with Vite", - "main": "index.js", + "main": "dist/index.js", + "types": "dist/index.d.ts", "author": "Eirik Sletteberg", "license": "MIT", "repository": { From ab5418f2262366db3d99c5845134e9e9b0ddfb6a Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 19:25:35 +0300 Subject: [PATCH 11/29] Created `start` and `prepublish` scripts in the root `package.json` --- package.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/package.json b/package.json index 6e22653d..e18361f4 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,8 @@ "node": ">=16.0.0" }, "scripts": { + "start": "cd packages/storybook-builder-vite && tsc -w", + "prepublish": "cd packages/storybook-builder-vite && tsc", "lint": "yarn lint:prettier && yarn lint:eslint", "lint:prettier": "prettier --write .", "lint:eslint": "eslint \"packages/*/**/*.{ts,tsx,js,jsx,mjs,cjs}\" --fix", From ca28bb2bf95dc14bf39b8a8375c05e03e0d8f0e5 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 19:28:14 +0300 Subject: [PATCH 12/29] Updated `tsconfig.json`: emit declarations, enabled source maps (with inlined sources) and skip libraries check --- tsconfig.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tsconfig.json b/tsconfig.json index 01e7052f..fb2b2b36 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,10 @@ { "compilerOptions": { "module": "CommonJS", - "target": "ES2021" + "target": "ES2021", + "declaration": true, + "sourceMap": true, + "inlineSources": true, + "skipLibCheck": true } } From b21561802dc5c4acd432ffbdae4b0eb728f630a2 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Wed, 5 Jan 2022 21:58:17 +0300 Subject: [PATCH 13/29] Start unused arguments with underscore in `pluginConfig()` function and the server watcher change callback in `configureServer()` function --- packages/storybook-builder-vite/code-generator-plugin.ts | 2 +- packages/storybook-builder-vite/vite-config.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/storybook-builder-vite/code-generator-plugin.ts b/packages/storybook-builder-vite/code-generator-plugin.ts index e31e8a37..35b33d02 100644 --- a/packages/storybook-builder-vite/code-generator-plugin.ts +++ b/packages/storybook-builder-vite/code-generator-plugin.ts @@ -18,7 +18,7 @@ export function codeGeneratorPlugin(options) { configureServer(server) { // invalidate the whole vite-app.js script on every file change. // (this might be a little too aggressive?) - server.watcher.on('change', () => { + server.watcher.on('change', (_e) => { const { moduleGraph } = server; const appModule = moduleGraph.getModuleById(virtualFileId); if (appModule) { diff --git a/packages/storybook-builder-vite/vite-config.ts b/packages/storybook-builder-vite/vite-config.ts index eb14e812..f77d14db 100644 --- a/packages/storybook-builder-vite/vite-config.ts +++ b/packages/storybook-builder-vite/vite-config.ts @@ -4,7 +4,7 @@ import { injectExportOrderPlugin } from './inject-export-order-plugin'; import { mdxPlugin } from './mdx-plugin'; import { sourceLoaderPlugin } from './source-loader-plugin'; -export async function pluginConfig(options) { +export async function pluginConfig(options, _type) { const { framework } = options; const svelteOptions = await options.presets.apply('svelteOptions', {}, options); From 9edc9d9406338a0e6d177d27c864588408ed5b31 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Thu, 6 Jan 2022 04:21:16 +0300 Subject: [PATCH 14/29] Ran `prepublish` script manually in GitHub Workflows. Fix: https://github.com/yarnpkg/yarn/issues/1671 See: https://yarnpkg.com/advanced/lifecycle-scripts --- .github/workflows/buildAndPublish.yml | 1 + .github/workflows/buildExamples.yml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/buildAndPublish.yml b/.github/workflows/buildAndPublish.yml index 2e583993..66e985c9 100644 --- a/.github/workflows/buildAndPublish.yml +++ b/.github/workflows/buildAndPublish.yml @@ -26,6 +26,7 @@ jobs: - name: install, build, and test run: | yarn install + yarn prepublish yarn workspaces foreach -p run build-storybook env: CI: true diff --git a/.github/workflows/buildExamples.yml b/.github/workflows/buildExamples.yml index 97b69247..5c5217b9 100644 --- a/.github/workflows/buildExamples.yml +++ b/.github/workflows/buildExamples.yml @@ -34,5 +34,8 @@ jobs: - name: Install dependencies run: yarn install + - name: Compile TypeScript + run: yarn prepublish + - name: Build examples run: yarn workspaces foreach -p run build-storybook From b6bcaba8e89851f6453600a068db742d582c75fa Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Thu, 6 Jan 2022 04:44:57 +0300 Subject: [PATCH 15/29] Fix: updated resolved path of the `iframe.html`, because we're serving from `dist` --- packages/storybook-builder-vite/code-generator-plugin.ts | 4 ++-- packages/storybook-builder-vite/index.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/storybook-builder-vite/code-generator-plugin.ts b/packages/storybook-builder-vite/code-generator-plugin.ts index 35b33d02..42bc5939 100644 --- a/packages/storybook-builder-vite/code-generator-plugin.ts +++ b/packages/storybook-builder-vite/code-generator-plugin.ts @@ -8,7 +8,7 @@ import { generateImportFnScriptCode } from './codegen-importfn-script'; export function codeGeneratorPlugin(options) { const virtualFileId = '/virtual:/@storybook/builder-vite/vite-app.js'; const virtualStoriesFile = '/virtual:/@storybook/builder-vite/storybook-stories.js'; - const iframePath = path.resolve(__dirname, 'input', 'iframe.html'); + const iframePath = path.resolve(__dirname, '..', 'input', 'iframe.html'); let iframeId; // noinspection JSUnusedGlobalSymbols @@ -67,7 +67,7 @@ export function codeGeneratorPlugin(options) { } if (id === iframeId) { - return fs.readFileSync(path.resolve(__dirname, 'input', 'iframe.html'), 'utf-8'); + return fs.readFileSync(path.resolve(__dirname, '..', 'input', 'iframe.html'), 'utf-8'); } }, async transformIndexHtml(html, ctx) { diff --git a/packages/storybook-builder-vite/index.ts b/packages/storybook-builder-vite/index.ts index adb4ddd0..5bbf2f20 100644 --- a/packages/storybook-builder-vite/index.ts +++ b/packages/storybook-builder-vite/index.ts @@ -12,7 +12,7 @@ function iframeMiddleware(options, server) { next(); return; } - const indexHtml = fs.readFileSync(path.resolve(__dirname, 'input', 'iframe.html'), 'utf-8'); + const indexHtml = fs.readFileSync(path.resolve(__dirname, '..', 'input', 'iframe.html'), 'utf-8'); const generated = await transformIframeHtml(indexHtml, options); const transformed = await server.transformIndexHtml('/iframe.html', generated); res.setHeader('Content-Type', 'text/html'); From 9dad5337cc71e91d621e2ddb9199f167a77b89ff Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Thu, 6 Jan 2022 08:07:46 +0300 Subject: [PATCH 16/29] Fix: async import of exported `vueDocgen()` function from local file instead of `require()` --- packages/storybook-builder-vite/plugins/vue-docgen.ts | 2 +- packages/storybook-builder-vite/vite-config.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/storybook-builder-vite/plugins/vue-docgen.ts b/packages/storybook-builder-vite/plugins/vue-docgen.ts index 2c0d206d..59f680a5 100644 --- a/packages/storybook-builder-vite/plugins/vue-docgen.ts +++ b/packages/storybook-builder-vite/plugins/vue-docgen.ts @@ -1,6 +1,6 @@ import { parse } from 'vue-docgen-api'; -export default function () { +export function vueDocgen() { return { name: 'vue-docgen', diff --git a/packages/storybook-builder-vite/vite-config.ts b/packages/storybook-builder-vite/vite-config.ts index f77d14db..a6f6ae57 100644 --- a/packages/storybook-builder-vite/vite-config.ts +++ b/packages/storybook-builder-vite/vite-config.ts @@ -1,3 +1,4 @@ +import { Plugin } from 'vite'; import { mockCoreJs } from './mock-core-js'; import { codeGeneratorPlugin } from './code-generator-plugin'; import { injectExportOrderPlugin } from './inject-export-order-plugin'; @@ -14,12 +15,13 @@ export async function pluginConfig(options, _type) { sourceLoaderPlugin(), mdxPlugin(), injectExportOrderPlugin, - ]; + ] as Plugin[]; if (framework === 'vue' || framework === 'vue3') { try { const vuePlugin = require('@vitejs/plugin-vue'); plugins.push(vuePlugin()); - plugins.push(require('./plugins/vue-docgen')()); + const { vueDocgen } = await import('./plugins/vue-docgen'); + plugins.push(vueDocgen()); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') { throw new Error( From e32a648b96ce729ba36de05b0670d22e3dffdb44 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:10:34 +0300 Subject: [PATCH 17/29] Added the `dist` directory to `.prettierignore` --- .prettierignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.prettierignore b/.prettierignore index c8d6ec8e..e954517e 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,4 @@ .yarn **/*/storybook-static/* *.yml +dist From d364211147bf4c7b224c61861629e4e8e212cd75 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:12:54 +0300 Subject: [PATCH 18/29] Installed packages: `@types/express` as dev dependency and `@storybook/core-common` as peer dependency. Version of `@storybook/core-common` package is based on nested installed dependency in `yarn.lock`. --- packages/storybook-builder-vite/package.json | 2 + yarn.lock | 75 ++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/packages/storybook-builder-vite/package.json b/packages/storybook-builder-vite/package.json index 4934e835..5fbdd70b 100644 --- a/packages/storybook-builder-vite/package.json +++ b/packages/storybook-builder-vite/package.json @@ -23,9 +23,11 @@ "vite-plugin-mdx": "^3.5.6" }, "devDependencies": { + "@types/express": "^4.17.13", "vue-docgen-api": "^4.40.0" }, "peerDependencies": { + "@storybook/core-common": "^6.4.3", "vite": ">=2.6.7" } } diff --git a/yarn.lock b/yarn.lock index f638d3e8..d3c4fe15 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3680,6 +3680,16 @@ __metadata: languageName: node linkType: hard +"@types/body-parser@npm:*": + version: 1.19.2 + resolution: "@types/body-parser@npm:1.19.2" + dependencies: + "@types/connect": "*" + "@types/node": "*" + checksum: e17840c7d747a549f00aebe72c89313d09fbc4b632b949b2470c5cb3b1cb73863901ae84d9335b567a79ec5efcfb8a28ff8e3f36bc8748a9686756b6d5681f40 + languageName: node + linkType: hard + "@types/color-convert@npm:^2.0.0": version: 2.0.0 resolution: "@types/color-convert@npm:2.0.0" @@ -3696,6 +3706,38 @@ __metadata: languageName: node linkType: hard +"@types/connect@npm:*": + version: 3.4.35 + resolution: "@types/connect@npm:3.4.35" + dependencies: + "@types/node": "*" + checksum: fe81351470f2d3165e8b12ce33542eef89ea893e36dd62e8f7d72566dfb7e448376ae962f9f3ea888547ce8b55a40020ca0e01d637fab5d99567673084542641 + languageName: node + linkType: hard + +"@types/express-serve-static-core@npm:^4.17.18": + version: 4.17.27 + resolution: "@types/express-serve-static-core@npm:4.17.27" + dependencies: + "@types/node": "*" + "@types/qs": "*" + "@types/range-parser": "*" + checksum: fef52b941f903011e31a5886369301d7765580a034cd011a2d3a7dbe6a6edf4f77537710a52e3e2258c6fc59c611f228594c213f984cda767654ab6c5c199e9e + languageName: node + linkType: hard + +"@types/express@npm:^4.17.13": + version: 4.17.13 + resolution: "@types/express@npm:4.17.13" + dependencies: + "@types/body-parser": "*" + "@types/express-serve-static-core": ^4.17.18 + "@types/qs": "*" + "@types/serve-static": "*" + checksum: 12a2a0e6c4b993fc0854bec665906788aea0d8ee4392389d7a98a5de1eefdd33c9e1e40a91f3afd274011119c506f7b4126acb97fae62ae20b654974d44cba12 + languageName: node + linkType: hard + "@types/glob@npm:*, @types/glob@npm:^7.1.1, @types/glob@npm:^7.1.3": version: 7.1.3 resolution: "@types/glob@npm:7.1.3" @@ -3786,6 +3828,13 @@ __metadata: languageName: node linkType: hard +"@types/mime@npm:^1": + version: 1.3.2 + resolution: "@types/mime@npm:1.3.2" + checksum: 0493368244cced1a69cb791b485a260a422e6fcc857782e1178d1e6f219f1b161793e9f87f5fae1b219af0f50bee24fcbe733a18b4be8fdd07a38a8fb91146fd + languageName: node + linkType: hard + "@types/minimatch@npm:*": version: 3.0.4 resolution: "@types/minimatch@npm:3.0.4" @@ -3873,6 +3922,13 @@ __metadata: languageName: node linkType: hard +"@types/qs@npm:*": + version: 6.9.7 + resolution: "@types/qs@npm:6.9.7" + checksum: 7fd6f9c25053e9b5bb6bc9f9f76c1d89e6c04f7707a7ba0e44cc01f17ef5284adb82f230f542c2d5557d69407c9a40f0f3515e8319afd14e1e16b5543ac6cdba + languageName: node + linkType: hard + "@types/qs@npm:^6.9.5": version: 6.9.6 resolution: "@types/qs@npm:6.9.6" @@ -3880,6 +3936,13 @@ __metadata: languageName: node linkType: hard +"@types/range-parser@npm:*": + version: 1.2.4 + resolution: "@types/range-parser@npm:1.2.4" + checksum: b7c0dfd5080a989d6c8bb0b6750fc0933d9acabeb476da6fe71d8bdf1ab65e37c136169d84148034802f48378ab94e3c37bb4ef7656b2bec2cb9c0f8d4146a95 + languageName: node + linkType: hard + "@types/reach__router@npm:^1.3.7": version: 1.3.9 resolution: "@types/reach__router@npm:1.3.9" @@ -3916,6 +3979,16 @@ __metadata: languageName: node linkType: hard +"@types/serve-static@npm:*": + version: 1.13.10 + resolution: "@types/serve-static@npm:1.13.10" + dependencies: + "@types/mime": ^1 + "@types/node": "*" + checksum: eaca858739483e3ded254cad7d7a679dc2c8b3f52c8bb0cd845b3b7eb1984bde0371fdcb0a5c83aa12e6daf61b6beb762545021f520f08a1fe882a3fa4ea5554 + languageName: node + linkType: hard + "@types/source-list-map@npm:*": version: 0.1.2 resolution: "@types/source-list-map@npm:0.1.2" @@ -14061,6 +14134,7 @@ fsevents@^1.2.7: "@mdx-js/mdx": ^1.6.22 "@storybook/csf-tools": ^6.3.3 "@storybook/source-loader": ^6.3.12 + "@types/express": ^4.17.13 "@vitejs/plugin-react": ^1.0.8 es-module-lexer: ^0.9.3 glob: ^7.2.0 @@ -14068,6 +14142,7 @@ fsevents@^1.2.7: vite-plugin-mdx: ^3.5.6 vue-docgen-api: ^4.40.0 peerDependencies: + "@storybook/core-common": ^6.4.3 vite: ">=2.6.7" languageName: unknown linkType: soft From b0fc21d4cd7b912331eefd48b0dbc97b9f01eeb1 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:14:19 +0300 Subject: [PATCH 19/29] Created declarations for `@storybook/addon-svelte-csf` files --- .../declarations/extract-stories.d.ts | 18 ++++++++++++++++++ .../declarations/svetle-stories-loader.d.ts | 7 +++++++ 2 files changed, 25 insertions(+) create mode 100644 packages/storybook-builder-vite/declarations/extract-stories.d.ts create mode 100644 packages/storybook-builder-vite/declarations/svetle-stories-loader.d.ts diff --git a/packages/storybook-builder-vite/declarations/extract-stories.d.ts b/packages/storybook-builder-vite/declarations/extract-stories.d.ts new file mode 100644 index 00000000..2731f657 --- /dev/null +++ b/packages/storybook-builder-vite/declarations/extract-stories.d.ts @@ -0,0 +1,18 @@ +/** + * @see https://github.com/storybookjs/addon-svelte-csf/blob/f72b8f28dabbb99c92e12d0170d3c1db4397ee7c/src/parser/extract-stories.ts + */ +declare module '@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories' { + interface StoryDef { + name: string; + template: boolean; + source: string; + hasArgs: boolean; + } + + interface StoriesDef { + stories: Record; + allocatedIds: string[]; + } + + function extractStories(component: string): { stories: StoriesDef; allocatedIds: string[] }; +} diff --git a/packages/storybook-builder-vite/declarations/svetle-stories-loader.d.ts b/packages/storybook-builder-vite/declarations/svetle-stories-loader.d.ts new file mode 100644 index 00000000..1ae04708 --- /dev/null +++ b/packages/storybook-builder-vite/declarations/svetle-stories-loader.d.ts @@ -0,0 +1,7 @@ +/** + * @see https://github.com/storybookjs/addon-svelte-csf/blob/f72b8f28dabbb99c92e12d0170d3c1db4397ee7c/src/parser/svelte-stories-loader.ts + * @see https://github.com/sveltejs/svelte/blob/deed340cf5d9c278f9a0605297ad6e4a3a1579d9/src/compiler/compile/utils/get_name_from_filename.ts + */ +declare module '@storybook/addon-svelte-csf/dist/cjs/parser/svelte-stories-loader' { + function getNameFromFilename(filename: string): string; +} From 822cf02c0774b99ca18c443d3e3995f9886bedc9 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:19:13 +0300 Subject: [PATCH 20/29] Created types: `EnvsRaw` and `ExtendedOptions` --- packages/storybook-builder-vite/types/envs-raw.type.ts | 1 + .../types/extended-options.type.ts | 9 +++++++++ packages/storybook-builder-vite/types/index.ts | 2 ++ 3 files changed, 12 insertions(+) create mode 100644 packages/storybook-builder-vite/types/envs-raw.type.ts create mode 100644 packages/storybook-builder-vite/types/extended-options.type.ts create mode 100644 packages/storybook-builder-vite/types/index.ts diff --git a/packages/storybook-builder-vite/types/envs-raw.type.ts b/packages/storybook-builder-vite/types/envs-raw.type.ts new file mode 100644 index 00000000..cb62e513 --- /dev/null +++ b/packages/storybook-builder-vite/types/envs-raw.type.ts @@ -0,0 +1 @@ +export type EnvsRaw = Record; diff --git a/packages/storybook-builder-vite/types/extended-options.type.ts b/packages/storybook-builder-vite/types/extended-options.type.ts new file mode 100644 index 00000000..b9867d36 --- /dev/null +++ b/packages/storybook-builder-vite/types/extended-options.type.ts @@ -0,0 +1,9 @@ +import type { Options } from '@storybook/core-common'; + +// Using instead of `Record` to provide better aware of used options +type IframeOptions = { + frameworkPath: string; + title: string; +}; + +export type ExtendedOptions = Options & IframeOptions; diff --git a/packages/storybook-builder-vite/types/index.ts b/packages/storybook-builder-vite/types/index.ts new file mode 100644 index 00000000..e50c278b --- /dev/null +++ b/packages/storybook-builder-vite/types/index.ts @@ -0,0 +1,2 @@ +export * from './envs-raw.type'; +export * from './extended-options.type'; From 43556013adad7688ccacd63dae97420074df840f Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:24:41 +0300 Subject: [PATCH 21/29] Enabled `strict` flag in `packages/storybook-builder-vite/tsconfig.json` file --- packages/storybook-builder-vite/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/storybook-builder-vite/tsconfig.json b/packages/storybook-builder-vite/tsconfig.json index d2e9a528..9caab3e9 100644 --- a/packages/storybook-builder-vite/tsconfig.json +++ b/packages/storybook-builder-vite/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { + "strict": true, "rootDir": ".", "outDir": "dist" } From b35cb275b589788af9332f66c46e50d635a0083f Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:42:46 +0300 Subject: [PATCH 22/29] Added types for variables and functions. Created additional types. --- packages/storybook-builder-vite/build.ts | 9 ++++-- .../code-generator-plugin.ts | 7 ++-- .../codegen-iframe-script.ts | 10 +++--- .../codegen-importfn-script.ts | 8 +++-- .../codegen-modern-iframe-script.ts | 11 ++++++- packages/storybook-builder-vite/envs.ts | 9 ++++-- packages/storybook-builder-vite/index.ts | 32 ++++++++++++------- .../inject-export-order-plugin.ts | 2 +- .../storybook-builder-vite/mock-core-js.ts | 4 +-- .../plugins/vue-docgen.ts | 2 +- .../source-loader-plugin.ts | 4 +-- .../svelte/csf-plugin.ts | 2 +- .../transform-iframe-html.ts | 20 ++++++++---- .../storybook-builder-vite/vite-config.ts | 12 ++++--- .../storybook-builder-vite/vite-server.ts | 10 ++++-- 15 files changed, 95 insertions(+), 47 deletions(-) diff --git a/packages/storybook-builder-vite/build.ts b/packages/storybook-builder-vite/build.ts index dc038089..9ba9919a 100644 --- a/packages/storybook-builder-vite/build.ts +++ b/packages/storybook-builder-vite/build.ts @@ -3,7 +3,10 @@ import { allowedEnvPrefix as envPrefix, stringifyProcessEnvs } from './envs'; import { pluginConfig } from './vite-config'; import { build as viteBuild } from 'vite'; -export async function build(options) { +import type { UserConfig } from 'vite'; +import type { EnvsRaw, ExtendedOptions } from './types'; + +export async function build(options: ExtendedOptions) { const { presets } = options; const config = { @@ -22,11 +25,11 @@ export async function build(options) { }, }, plugins: await pluginConfig(options, 'build'), - }; + } as UserConfig; const finalConfig = await presets.apply('viteFinal', config, options); - const envsRaw = await presets.apply('env'); + const envsRaw = await presets.apply>('env'); // Stringify env variables after getting `envPrefix` from the final config const envs = stringifyProcessEnvs(envsRaw, finalConfig.envPrefix); // Update `define` diff --git a/packages/storybook-builder-vite/code-generator-plugin.ts b/packages/storybook-builder-vite/code-generator-plugin.ts index 42bc5939..a98c7867 100644 --- a/packages/storybook-builder-vite/code-generator-plugin.ts +++ b/packages/storybook-builder-vite/code-generator-plugin.ts @@ -5,11 +5,14 @@ import { generateIframeScriptCode } from './codegen-iframe-script'; import { generateModernIframeScriptCode } from './codegen-modern-iframe-script'; import { generateImportFnScriptCode } from './codegen-importfn-script'; -export function codeGeneratorPlugin(options) { +import type { Plugin } from 'vite'; +import type { ExtendedOptions } from './types'; + +export function codeGeneratorPlugin(options: ExtendedOptions): Plugin { const virtualFileId = '/virtual:/@storybook/builder-vite/vite-app.js'; const virtualStoriesFile = '/virtual:/@storybook/builder-vite/storybook-stories.js'; const iframePath = path.resolve(__dirname, '..', 'input', 'iframe.html'); - let iframeId; + let iframeId: string; // noinspection JSUnusedGlobalSymbols return { diff --git a/packages/storybook-builder-vite/codegen-iframe-script.ts b/packages/storybook-builder-vite/codegen-iframe-script.ts index 37a96a4f..151dda10 100644 --- a/packages/storybook-builder-vite/codegen-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-iframe-script.ts @@ -3,14 +3,16 @@ import { promise as glob } from 'glob-promise'; import { normalizePath } from 'vite'; import { loadPreviewOrConfigFile } from '@storybook/core-common'; +import type { ExtendedOptions } from './types'; + // This is somewhat of a hack; the problem is that previewEntries resolves to // the CommonJS imports, probably because require.resolve in Node.js land leads // to that. For Vite, we need the ESM modules. -function replaceCJStoESMPath(entryPath) { +function replaceCJStoESMPath(entryPath: string) { return entryPath.replace('/cjs/', '/esm/'); } -export async function generateIframeScriptCode(options) { +export async function generateIframeScriptCode(options: ExtendedOptions) { const { presets, configDir, framework, frameworkPath } = options; const previewEntries = (await presets.apply('previewEntries', [], options)).map(replaceCJStoESMPath); @@ -28,10 +30,10 @@ export async function generateIframeScriptCode(options) { ) ).reduce((carry, stories) => carry.concat(stories), []); - const absoluteFilesToImport = (files, name) => + const absoluteFilesToImport = (files: string[], name: string) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'/@fs/${normalizePath(el)}'`).join('\n'); - const importArray = (name, length) => + const importArray = (name: string, length: number) => `[${new Array(length) .fill(0) .map((_, i) => `${name}_${i}`) diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index b7c8ccf9..01c90e5a 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -2,6 +2,8 @@ import { promise as glob } from 'glob-promise'; import * as path from 'path'; import { normalizePath } from 'vite'; +import type { Options } from '@storybook/core-common'; + /** * This file is largely based on https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/core-common/src/utils/to-importFn.ts */ @@ -14,7 +16,7 @@ import { normalizePath } from 'vite'; * @param {string} relativePath * @returns {string} */ -function toImportPath(relativePath) { +function toImportPath(relativePath: string) { return relativePath.startsWith('../') ? relativePath : `./${relativePath}`; } @@ -26,7 +28,7 @@ function toImportPath(relativePath) { * @param stories An array of absolute story paths. * @returns {Promise} */ -async function toImportFn(stories) { +async function toImportFn(stories: string[]) { const objectEntries = stories.map((file) => { return ` '${toImportPath(normalizePath(path.relative(process.cwd(), file)))}': async () => import('/@fs/${file}')`; }); @@ -42,7 +44,7 @@ async function toImportFn(stories) { `; } -export async function generateImportFnScriptCode(options) { +export async function generateImportFnScriptCode(options: Options) { // First we need to get an array of stories and their absolute paths. const stories = ( await Promise.all( diff --git a/packages/storybook-builder-vite/codegen-modern-iframe-script.ts b/packages/storybook-builder-vite/codegen-modern-iframe-script.ts index a767c2f6..4635bcd2 100644 --- a/packages/storybook-builder-vite/codegen-modern-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-modern-iframe-script.ts @@ -1,7 +1,16 @@ import { loadPreviewOrConfigFile } from '@storybook/core-common'; import { normalizePath } from 'vite'; -export async function generateModernIframeScriptCode(options, { storiesFilename }) { +import type { ExtendedOptions } from './types'; + +export interface GenerateModernIframeScriptCodeOptions { + storiesFilename: string; +} + +export async function generateModernIframeScriptCode( + options: ExtendedOptions, + { storiesFilename }: GenerateModernIframeScriptCodeOptions +) { const { presets, configDir } = options; const previewOrConfigFile = loadPreviewOrConfigFile({ configDir }); diff --git a/packages/storybook-builder-vite/envs.ts b/packages/storybook-builder-vite/envs.ts index db0de584..4674110c 100644 --- a/packages/storybook-builder-vite/envs.ts +++ b/packages/storybook-builder-vite/envs.ts @@ -1,5 +1,8 @@ import { stringifyEnvs } from '@storybook/core-common'; +import type { EnvsRaw } from './types'; +import type { UserConfig } from 'vite'; + // Allowed env variables on the client const allowedEnvVariables = [ 'STORYBOOK', @@ -21,10 +24,10 @@ export const allowedEnvPrefix = ['VITE_', 'STORYBOOK_']; * @param {Object} raw * @param {string[]|string} envPrefix */ -export function stringifyProcessEnvs(raw, envPrefix) { - const updatedRaw = {}; +export function stringifyProcessEnvs(raw: EnvsRaw, envPrefix: UserConfig['envPrefix']) { + const updatedRaw: EnvsRaw = {}; const envs = Object.entries(raw).reduce( - (acc, [key, value]) => { + (acc: EnvsRaw, [key, value]) => { // Only add allowed values OR values from array OR string started with allowed prefixes if ( allowedEnvVariables.includes(key) || diff --git a/packages/storybook-builder-vite/index.ts b/packages/storybook-builder-vite/index.ts index 5bbf2f20..854afa81 100644 --- a/packages/storybook-builder-vite/index.ts +++ b/packages/storybook-builder-vite/index.ts @@ -6,7 +6,16 @@ import { transformIframeHtml } from './transform-iframe-html'; import { createViteServer } from './vite-server'; import { build as viteBuild } from './build'; -function iframeMiddleware(options, server) { +import type { Builder } from '@storybook/core-common'; +import type { RequestHandler, Request, Response } from 'express'; +import type { UserConfig, ViteDevServer } from 'vite'; +import type { ExtendedOptions } from './types'; + +export interface ViteStats {} + +export type ViteBuilder = Builder; + +function iframeMiddleware(options: ExtendedOptions, server: ViteDevServer): RequestHandler { return async (req, res, next) => { if (!req.url.match(/^\/iframe.html($|\?)/)) { next(); @@ -20,22 +29,22 @@ function iframeMiddleware(options, server) { }; } -export async function start({ startTime, options, router, server: devServer }) { - const server = await createViteServer(options, devServer); +export const start: ViteBuilder['start'] = async ({ startTime, options, router, server: devServer }) => { + const server = await createViteServer(options as ExtendedOptions, devServer); // Just mock this endpoint (which is really Webpack-specific) so we don't get spammed with 404 in browser devtools // TODO: we should either show some sort of progress from Vite, or just try to disable the whole Loader in the Manager UI. - router.get('/progress', (req, res) => { + router.get('/progress', (req: Request, res: Response) => { res.header('Cache-Control', 'no-cache'); res.header('Content-Type', 'text/event-stream'); }); - router.use(await iframeMiddleware(options, server)); + router.use(await iframeMiddleware(options as ExtendedOptions, server)); router.use(server.middlewares); - function bail(e) { + function bail(e?: Error) { try { - server.close(); + return server.close(); } catch (err) { console.warn('unable to close vite server'); } @@ -45,13 +54,14 @@ export async function start({ startTime, options, router, server: devServer }) { return { bail, + stats: {} as ViteStats, totalTime: process.hrtime(startTime), }; -} +}; -export async function build({ options }) { - return viteBuild(options); -} +export const build: ViteBuilder['build'] = async ({ options }) => { + return viteBuild(options as ExtendedOptions); +}; export const corePresets = []; export const previewPresets = []; diff --git a/packages/storybook-builder-vite/inject-export-order-plugin.ts b/packages/storybook-builder-vite/inject-export-order-plugin.ts index cbea45de..8d7823dd 100644 --- a/packages/storybook-builder-vite/inject-export-order-plugin.ts +++ b/packages/storybook-builder-vite/inject-export-order-plugin.ts @@ -4,7 +4,7 @@ export const injectExportOrderPlugin = { name: 'storybook-vite-inject-export-order-plugin', // This should only run after the typescript has been transpiled enforce: 'post', - async transform(code, id) { + async transform(code: string, id: string) { if (!/\.stories\.([tj])sx?$/.test(id)) { return; } diff --git a/packages/storybook-builder-vite/mock-core-js.ts b/packages/storybook-builder-vite/mock-core-js.ts index 5fa9ba1c..59a041ea 100644 --- a/packages/storybook-builder-vite/mock-core-js.ts +++ b/packages/storybook-builder-vite/mock-core-js.ts @@ -1,13 +1,13 @@ export function mockCoreJs() { return { name: 'mock-core-js', - resolveId(id) { + resolveId(id: string) { if (id.includes('node_modules/core-js')) { return id; } return undefined; }, - load(id) { + load(id: string) { if (id.includes('node_modules/core-js')) { return ''; } diff --git a/packages/storybook-builder-vite/plugins/vue-docgen.ts b/packages/storybook-builder-vite/plugins/vue-docgen.ts index 59f680a5..65567e80 100644 --- a/packages/storybook-builder-vite/plugins/vue-docgen.ts +++ b/packages/storybook-builder-vite/plugins/vue-docgen.ts @@ -4,7 +4,7 @@ export function vueDocgen() { return { name: 'vue-docgen', - async transform(src, id) { + async transform(src: string, id: string) { if (/\.(vue)$/.test(id)) { const metaData = await parse(id); const metaSource = JSON.stringify(metaData); diff --git a/packages/storybook-builder-vite/source-loader-plugin.ts b/packages/storybook-builder-vite/source-loader-plugin.ts index cdcfb515..0144d313 100644 --- a/packages/storybook-builder-vite/source-loader-plugin.ts +++ b/packages/storybook-builder-vite/source-loader-plugin.ts @@ -4,11 +4,11 @@ export function sourceLoaderPlugin() { return { name: 'storybook-vite-source-loader-plugin', enforce: 'pre', - async transform(src, id) { + async transform(src: string, id: string) { if (id.match(/\.stories\.[jt]sx?$/)) { // We need to mock 'this' when calling transform from @storybook/source-loader // noinspection JSUnusedGlobalSymbols - const mockClassLoader = { emitWarning: (message) => console.warn(message), resourcePath: id }; + const mockClassLoader = { emitWarning: (message: string) => console.warn(message), resourcePath: id }; const code = await sourceLoaderTransform.call(mockClassLoader, src); return { diff --git a/packages/storybook-builder-vite/svelte/csf-plugin.ts b/packages/storybook-builder-vite/svelte/csf-plugin.ts index 029557d7..51c69c26 100644 --- a/packages/storybook-builder-vite/svelte/csf-plugin.ts +++ b/packages/storybook-builder-vite/svelte/csf-plugin.ts @@ -6,7 +6,7 @@ const parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/coll export default { name: 'storybook-addon-svelte-csf', enforce: 'post', - transform(code, id) { + transform(code: string, id: string) { if (/.stories.svelte/.test(id)) { const component = getNameFromFilename(id); const source = readFileSync(id).toString(); diff --git a/packages/storybook-builder-vite/transform-iframe-html.ts b/packages/storybook-builder-vite/transform-iframe-html.ts index c0717258..c5355aeb 100644 --- a/packages/storybook-builder-vite/transform-iframe-html.ts +++ b/packages/storybook-builder-vite/transform-iframe-html.ts @@ -1,14 +1,22 @@ -export async function transformIframeHtml(html, { configType, features, framework, presets, serverChannelUrl, title }) { - const headHtmlSnippet = await presets.apply('previewHead'); - const bodyHtmlSnippet = await presets.apply('previewBody'); +import type { CoreConfig } from '@storybook/core-common'; +import type { ExtendedOptions } from './types'; + +export type PreviewHtml = string | undefined; + +export async function transformIframeHtml( + html: string, + { configType, features, framework, presets, serverChannelUrl, title }: ExtendedOptions +) { + const headHtmlSnippet = await presets.apply('previewHead'); + const bodyHtmlSnippet = await presets.apply('previewBody'); const logLevel = await presets.apply('logLevel', undefined); const frameworkOptions = await presets.apply(`${framework}Options`, {}); - const coreOptions = await presets.apply('core'); + const coreOptions = await presets.apply('core'); return html .replace('', title || 'Storybook') - .replace('[CONFIG_TYPE HERE]', configType) - .replace('[LOGLEVEL HERE]', logLevel) + .replace('[CONFIG_TYPE HERE]', configType || '') + .replace('[LOGLEVEL HERE]', logLevel || '') .replace(`'[FRAMEWORK_OPTIONS HERE]'`, JSON.stringify(frameworkOptions || {})) .replace( `'[CHANNEL_OPTIONS HERE]'`, diff --git a/packages/storybook-builder-vite/vite-config.ts b/packages/storybook-builder-vite/vite-config.ts index a6f6ae57..fa10049e 100644 --- a/packages/storybook-builder-vite/vite-config.ts +++ b/packages/storybook-builder-vite/vite-config.ts @@ -5,7 +5,11 @@ import { injectExportOrderPlugin } from './inject-export-order-plugin'; import { mdxPlugin } from './mdx-plugin'; import { sourceLoaderPlugin } from './source-loader-plugin'; -export async function pluginConfig(options, _type) { +import type { ExtendedOptions } from './types'; + +export type PluginConfigType = 'build' | 'development'; + +export async function pluginConfig(options: ExtendedOptions, _type: PluginConfigType) { const { framework } = options; const svelteOptions = await options.presets.apply('svelteOptions', {}, options); @@ -23,7 +27,7 @@ export async function pluginConfig(options, _type) { const { vueDocgen } = await import('./plugins/vue-docgen'); plugins.push(vueDocgen()); } catch (err) { - if (err.code !== 'MODULE_NOT_FOUND') { + if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { throw new Error( 'storybook-builder-vite requires @vitejs/plugin-vue to be installed ' + 'when using @storybook/vue or @storybook/vue3.' + @@ -38,7 +42,7 @@ export async function pluginConfig(options, _type) { const sveltePlugin = require('@sveltejs/vite-plugin-svelte').svelte; plugins.push(sveltePlugin(svelteOptions)); } catch (err) { - if (err.code !== 'MODULE_NOT_FOUND') { + if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { throw new Error( 'storybook-builder-vite requires @sveltejs/vite-plugin-svelte to be installed when using @storybook/svelte.' + ' Please install it and start storybook again.' @@ -51,7 +55,7 @@ export async function pluginConfig(options, _type) { const csfPlugin = require('./svelte/csf-plugin'); plugins.push(csfPlugin); } catch (err) { - if (err.code !== 'MODULE_NOT_FOUND') { + if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { throw new Error( 'storybook-builder-vite requires @storybook/addon-svelte-csf to be installed when using @storybook/svelte.' + ' Please install it and start storybook again.' diff --git a/packages/storybook-builder-vite/vite-server.ts b/packages/storybook-builder-vite/vite-server.ts index e6cee3af..c57285ad 100644 --- a/packages/storybook-builder-vite/vite-server.ts +++ b/packages/storybook-builder-vite/vite-server.ts @@ -4,7 +4,11 @@ import { getOptimizeDeps } from './optimizeDeps'; import { createServer } from 'vite'; import { pluginConfig } from './vite-config'; -export async function createViteServer(options, devServer) { +import type { Server } from 'http'; +import type { UserConfig } from 'vite'; +import type { EnvsRaw, ExtendedOptions } from './types'; + +export async function createViteServer(options: ExtendedOptions, devServer: Server) { const { port, presets } = options; const root = path.resolve(options.configDir, '..'); @@ -30,11 +34,11 @@ export async function createViteServer(options, devServer) { }, plugins: await pluginConfig(options, 'development'), optimizeDeps: await getOptimizeDeps(root, options), - }; + } as UserConfig; const finalConfig = await presets.apply('viteFinal', defaultConfig, options); - const envsRaw = await presets.apply('env'); + const envsRaw = await presets.apply>('env'); // Stringify env variables after getting `envPrefix` from the final config const envs = stringifyProcessEnvs(envsRaw, finalConfig.envPrefix); // Update `define` From 47e5f24fd190548550644c6295503a58db6c94ff Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:48:17 +0300 Subject: [PATCH 23/29] Fixed: the `config.build` property may be undefined --- packages/storybook-builder-vite/code-generator-plugin.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/storybook-builder-vite/code-generator-plugin.ts b/packages/storybook-builder-vite/code-generator-plugin.ts index a98c7867..26c7ebd7 100644 --- a/packages/storybook-builder-vite/code-generator-plugin.ts +++ b/packages/storybook-builder-vite/code-generator-plugin.ts @@ -39,6 +39,9 @@ export function codeGeneratorPlugin(options: ExtendedOptions): Plugin { // to serve iframe.html. The reason is that Vite's dev server (at the time of writing) // does not support virtual files as entry points. if (command === 'build') { + if (!config.build) { + config.build = {}; + } config.build.rollupOptions = { input: iframePath, }; From ea5f950e52df6518f2e402d981e63c1cb32f61a4 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:53:33 +0300 Subject: [PATCH 24/29] Simplify JSDoc --- packages/storybook-builder-vite/codegen-importfn-script.ts | 4 ---- packages/storybook-builder-vite/envs.ts | 2 -- 2 files changed, 6 deletions(-) diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index 01c90e5a..0c9cece4 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -12,9 +12,6 @@ import type { Options } from '@storybook/core-common'; * Paths get passed either with no leading './' - e.g. `src/Foo.stories.js`, * or with a leading `../` (etc), e.g. `../src/Foo.stories.js`. * We want to deal in importPaths relative to the working dir, so we normalize - * - * @param {string} relativePath - * @returns {string} */ function toImportPath(relativePath: string) { return relativePath.startsWith('../') ? relativePath : `./${relativePath}`; @@ -26,7 +23,6 @@ function toImportPath(relativePath: string) { * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import * function and this is called by Storybook to fetch a story dynamically when needed. * @param stories An array of absolute story paths. - * @returns {Promise} */ async function toImportFn(stories: string[]) { const objectEntries = stories.map((file) => { diff --git a/packages/storybook-builder-vite/envs.ts b/packages/storybook-builder-vite/envs.ts index 4674110c..85b4f1cd 100644 --- a/packages/storybook-builder-vite/envs.ts +++ b/packages/storybook-builder-vite/envs.ts @@ -21,8 +21,6 @@ export const allowedEnvPrefix = ['VITE_', 'STORYBOOK_']; /** * Customized version of stringifyProcessEnvs from @storybook/core-common which * uses import.meta.env instead of process.env and checks for allowed variables. - * @param {Object} raw - * @param {string[]|string} envPrefix */ export function stringifyProcessEnvs(raw: EnvsRaw, envPrefix: UserConfig['envPrefix']) { const updatedRaw: EnvsRaw = {}; From ed88537302857fca3f9a087d613bdc9f6d537a1c Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:54:57 +0300 Subject: [PATCH 25/29] Created TODO: Maybe convert `injectExportOrderPlugin` to function that returns object, and run `await init;` once and then call `parse()` without `await`, instead of calling `await parse()` every time. --- packages/storybook-builder-vite/inject-export-order-plugin.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/storybook-builder-vite/inject-export-order-plugin.ts b/packages/storybook-builder-vite/inject-export-order-plugin.ts index 8d7823dd..39477126 100644 --- a/packages/storybook-builder-vite/inject-export-order-plugin.ts +++ b/packages/storybook-builder-vite/inject-export-order-plugin.ts @@ -8,6 +8,9 @@ export const injectExportOrderPlugin = { if (!/\.stories\.([tj])sx?$/.test(id)) { return; } + // TODO: Maybe convert `injectExportOrderPlugin` to function that returns object, + // and run `await init;` once and then call `parse()` without `await`, + // instead of calling `await parse()` every time. const [, exports] = await parse(code); if (exports.includes('__namedExportsOrder')) { From 020471cedf986bf6f63c96d549256151d8db40be Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:56:08 +0300 Subject: [PATCH 26/29] Fixed rare case if the `envPrefix` is undefined in `stringifyProcessEnvs()` function --- packages/storybook-builder-vite/envs.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/storybook-builder-vite/envs.ts b/packages/storybook-builder-vite/envs.ts index 85b4f1cd..e5ad6c50 100644 --- a/packages/storybook-builder-vite/envs.ts +++ b/packages/storybook-builder-vite/envs.ts @@ -30,7 +30,7 @@ export function stringifyProcessEnvs(raw: EnvsRaw, envPrefix: UserConfig['envPre if ( allowedEnvVariables.includes(key) || (Array.isArray(envPrefix) && !!envPrefix.find((prefix) => key.startsWith(prefix))) || - key.startsWith(envPrefix) + (typeof envPrefix === 'string' && key.startsWith(envPrefix)) ) { acc[`import.meta.env.${key}`] = JSON.stringify(value); updatedRaw[key] = value; From 13151cb8f3ff2abdde933da2ae1b8abea5d15a81 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 05:58:57 +0300 Subject: [PATCH 27/29] Reorder imports in `build.ts` and `vite-server.ts` --- packages/storybook-builder-vite/build.ts | 2 +- packages/storybook-builder-vite/vite-server.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/storybook-builder-vite/build.ts b/packages/storybook-builder-vite/build.ts index 9ba9919a..02ab0f6e 100644 --- a/packages/storybook-builder-vite/build.ts +++ b/packages/storybook-builder-vite/build.ts @@ -1,7 +1,7 @@ import * as path from 'path'; +import { build as viteBuild } from 'vite'; import { allowedEnvPrefix as envPrefix, stringifyProcessEnvs } from './envs'; import { pluginConfig } from './vite-config'; -import { build as viteBuild } from 'vite'; import type { UserConfig } from 'vite'; import type { EnvsRaw, ExtendedOptions } from './types'; diff --git a/packages/storybook-builder-vite/vite-server.ts b/packages/storybook-builder-vite/vite-server.ts index c57285ad..8cb61940 100644 --- a/packages/storybook-builder-vite/vite-server.ts +++ b/packages/storybook-builder-vite/vite-server.ts @@ -1,7 +1,7 @@ import * as path from 'path'; +import { createServer } from 'vite'; import { allowedEnvPrefix as envPrefix, stringifyProcessEnvs } from './envs'; import { getOptimizeDeps } from './optimizeDeps'; -import { createServer } from 'vite'; import { pluginConfig } from './vite-config'; import type { Server } from 'http'; From 23a09e2246f1a8ddf4c6c8e5f779f48e9e04e91b Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 06:27:16 +0300 Subject: [PATCH 28/29] Added check for a case if the `StoriesEntry` is object in functions: * `generateImportFnScriptCode()`; * `generateIframeScriptCode()`; * `getOptimizeDeps()`. --- .../codegen-iframe-script.ts | 11 ++++++++++- .../codegen-importfn-script.ts | 14 ++++++++++---- packages/storybook-builder-vite/optimizeDeps.ts | 17 +++++++++++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/packages/storybook-builder-vite/codegen-iframe-script.ts b/packages/storybook-builder-vite/codegen-iframe-script.ts index 151dda10..0fc0aa20 100644 --- a/packages/storybook-builder-vite/codegen-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-iframe-script.ts @@ -3,6 +3,7 @@ import { promise as glob } from 'glob-promise'; import { normalizePath } from 'vite'; import { loadPreviewOrConfigFile } from '@storybook/core-common'; +import type { StoriesEntry } from '@storybook/core-common'; import type { ExtendedOptions } from './types'; // This is somewhat of a hack; the problem is that previewEntries resolves to @@ -26,7 +27,15 @@ export async function generateIframeScriptCode(options: ExtendedOptions) { const storyEntries = ( await Promise.all( - (await presets.apply('stories')).map((g) => glob(path.isAbsolute(g) ? g : path.join(configDir, g))) + ( + await presets.apply>('stories') + ).map((storiesEntry) => { + const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; + if (!files) { + return [] as string[]; + } + return glob(path.isAbsolute(files) ? files : path.join(configDir, files)); + }) ) ).reduce((carry, stories) => carry.concat(stories), []); diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index 0c9cece4..e5047207 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -2,7 +2,7 @@ import { promise as glob } from 'glob-promise'; import * as path from 'path'; import { normalizePath } from 'vite'; -import type { Options } from '@storybook/core-common'; +import type { Options, StoriesEntry } from '@storybook/core-common'; /** * This file is largely based on https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/core-common/src/utils/to-importFn.ts @@ -40,13 +40,19 @@ async function toImportFn(stories: string[]) { `; } -export async function generateImportFnScriptCode(options: Options) { +export async function generateImportFnScriptCode({ configDir, presets }: Options) { // First we need to get an array of stories and their absolute paths. const stories = ( await Promise.all( ( - await options.presets.apply('stories', [], options) - ).map((storyEntry) => glob(path.isAbsolute(storyEntry) ? storyEntry : path.join(options.configDir, storyEntry))) + await presets.apply>('stories') + ).map((storiesEntry) => { + const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; + if (!files) { + return [] as string[]; + } + return glob(path.isAbsolute(files) ? files : path.join(configDir, files)); + }) ) ).reduce((carry, stories) => carry.concat(stories), []); diff --git a/packages/storybook-builder-vite/optimizeDeps.ts b/packages/storybook-builder-vite/optimizeDeps.ts index 1d9038c5..29a9c15c 100644 --- a/packages/storybook-builder-vite/optimizeDeps.ts +++ b/packages/storybook-builder-vite/optimizeDeps.ts @@ -1,12 +1,21 @@ import * as path from 'path'; -export async function getOptimizeDeps(root, options) { +import type { StoriesEntry } from '@storybook/core-common'; +import type { ExtendedOptions } from './types'; + +export async function getOptimizeDeps(root: string, { configDir, presets }: ExtendedOptions) { const stories = await Promise.all( ( - await options.presets.apply('stories', [], options) - ).map((storyEntry) => - path.relative(root, path.isAbsolute(storyEntry) ? storyEntry : path.join(options.configDir, storyEntry)) + await presets.apply>('stories') ) + .map((storiesEntry) => { + const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; + if (!files) { + return undefined; + } + return path.relative(root, path.isAbsolute(files) ? files : path.join(configDir, files)); + }) + .filter((path): path is string => typeof path !== 'undefined') ); return { From 1d1360ee5b9993f2ffa9d2bd6c6935c121f40195 Mon Sep 17 00:00:00 2001 From: Mrau Hu Date: Fri, 7 Jan 2022 06:33:33 +0300 Subject: [PATCH 29/29] Created `listStories()` function and removed duplicated code. TODO: Merge with #182 --- .../codegen-iframe-script.ts | 20 +++--------------- .../codegen-importfn-script.ts | 20 ++++-------------- .../storybook-builder-vite/list-stories.ts | 21 +++++++++++++++++++ .../storybook-builder-vite/optimizeDeps.ts | 20 +++++------------- 4 files changed, 33 insertions(+), 48 deletions(-) create mode 100644 packages/storybook-builder-vite/list-stories.ts diff --git a/packages/storybook-builder-vite/codegen-iframe-script.ts b/packages/storybook-builder-vite/codegen-iframe-script.ts index 0fc0aa20..607133d0 100644 --- a/packages/storybook-builder-vite/codegen-iframe-script.ts +++ b/packages/storybook-builder-vite/codegen-iframe-script.ts @@ -1,9 +1,7 @@ -import * as path from 'path'; -import { promise as glob } from 'glob-promise'; -import { normalizePath } from 'vite'; import { loadPreviewOrConfigFile } from '@storybook/core-common'; +import { normalizePath } from 'vite'; +import { listStories } from './list-stories'; -import type { StoriesEntry } from '@storybook/core-common'; import type { ExtendedOptions } from './types'; // This is somewhat of a hack; the problem is that previewEntries resolves to @@ -25,19 +23,7 @@ export async function generateIframeScriptCode(options: ExtendedOptions) { const presetEntries = await presets.apply('config', [], options); const configEntries = [...presetEntries, previewOrConfigFile].filter(Boolean); - const storyEntries = ( - await Promise.all( - ( - await presets.apply>('stories') - ).map((storiesEntry) => { - const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; - if (!files) { - return [] as string[]; - } - return glob(path.isAbsolute(files) ? files : path.join(configDir, files)); - }) - ) - ).reduce((carry, stories) => carry.concat(stories), []); + const storyEntries = await listStories(options); const absoluteFilesToImport = (files: string[], name: string) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'/@fs/${normalizePath(el)}'`).join('\n'); diff --git a/packages/storybook-builder-vite/codegen-importfn-script.ts b/packages/storybook-builder-vite/codegen-importfn-script.ts index e5047207..a0e3577a 100644 --- a/packages/storybook-builder-vite/codegen-importfn-script.ts +++ b/packages/storybook-builder-vite/codegen-importfn-script.ts @@ -1,8 +1,8 @@ -import { promise as glob } from 'glob-promise'; import * as path from 'path'; import { normalizePath } from 'vite'; +import { listStories } from './list-stories'; -import type { Options, StoriesEntry } from '@storybook/core-common'; +import type { Options } from '@storybook/core-common'; /** * This file is largely based on https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/core-common/src/utils/to-importFn.ts @@ -40,21 +40,9 @@ async function toImportFn(stories: string[]) { `; } -export async function generateImportFnScriptCode({ configDir, presets }: Options) { +export async function generateImportFnScriptCode(options: Options) { // First we need to get an array of stories and their absolute paths. - const stories = ( - await Promise.all( - ( - await presets.apply>('stories') - ).map((storiesEntry) => { - const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; - if (!files) { - return [] as string[]; - } - return glob(path.isAbsolute(files) ? files : path.join(configDir, files)); - }) - ) - ).reduce((carry, stories) => carry.concat(stories), []); + const stories = await listStories(options); // We can then call toImportFn to create a function that can be used to load each story dynamically. return (await toImportFn(stories)).trim(); diff --git a/packages/storybook-builder-vite/list-stories.ts b/packages/storybook-builder-vite/list-stories.ts new file mode 100644 index 00000000..f047431e --- /dev/null +++ b/packages/storybook-builder-vite/list-stories.ts @@ -0,0 +1,21 @@ +import * as path from 'path'; +import { promise as glob } from 'glob-promise'; + +import type { Options, StoriesEntry } from '@storybook/core-common'; + +// TODO: Merge with https://github.com/eirslett/storybook-builder-vite/pull/182 +export async function listStories({ presets, configDir }: Options) { + return ( + await Promise.all( + ( + await presets.apply>('stories') + ).map((storiesEntry) => { + const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; + if (!files) { + return [] as string[]; + } + return glob(path.isAbsolute(files) ? files : path.join(configDir, files)); + }) + ) + ).reduce((carry, stories) => carry.concat(stories), []); +} diff --git a/packages/storybook-builder-vite/optimizeDeps.ts b/packages/storybook-builder-vite/optimizeDeps.ts index 29a9c15c..7fffb166 100644 --- a/packages/storybook-builder-vite/optimizeDeps.ts +++ b/packages/storybook-builder-vite/optimizeDeps.ts @@ -1,22 +1,12 @@ import * as path from 'path'; +import { normalizePath } from 'vite'; +import { listStories } from './list-stories'; -import type { StoriesEntry } from '@storybook/core-common'; import type { ExtendedOptions } from './types'; -export async function getOptimizeDeps(root: string, { configDir, presets }: ExtendedOptions) { - const stories = await Promise.all( - ( - await presets.apply>('stories') - ) - .map((storiesEntry) => { - const files = typeof storiesEntry === 'string' ? storiesEntry : storiesEntry.files; - if (!files) { - return undefined; - } - return path.relative(root, path.isAbsolute(files) ? files : path.join(configDir, files)); - }) - .filter((path): path is string => typeof path !== 'undefined') - ); +export async function getOptimizeDeps(root: string, options: ExtendedOptions) { + const absoluteStories = await listStories(options); + const stories = absoluteStories.map((storyPath) => normalizePath(path.relative(root, storyPath))); return { // We don't need to resolve the glob since vite supports globs for entries.