Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] TypeError: previewBuilder.bail is not a function #485

Closed
1 task
FezVrasta opened this issue Aug 24, 2022 · 10 comments · Fixed by #510
Closed
1 task

[Bug] TypeError: previewBuilder.bail is not a function #485

FezVrasta opened this issue Aug 24, 2022 · 10 comments · Fixed by #510
Labels
bug Something isn't working

Comments

@FezVrasta
Copy link

FezVrasta commented Aug 24, 2022

What version of vite are you using?

3.0.9

System info and storybook versions

  System:
    OS: macOS 12.5.1
    CPU: (10) arm64 Apple M1 Max
  Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 3.1.0 - ~/.nvm/versions/node/v16.16.0/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
  Browsers:
    Chrome: 104.0.5112.101
    Firefox: 103.0.1
    Safari: 15.6.1
  npmPackages:
    @storybook/addon-actions: ^6.5.10 => 6.5.10 
    @storybook/addon-essentials: ^6.5.10 => 6.5.10 
    @storybook/addon-storyshots: ^6.5.10 => 6.5.10 
    @storybook/builder-vite: ^0.2.2 => 0.2.2 
    @storybook/node-logger: ^6.5.10 => 6.5.10 
    @storybook/preset-create-react-app: ^4.1.2 => 4.1.2 
    @storybook/react: ^6.5.10 => 6.5.10 

Describe the Bug

If I run start-storybook, it fails the first time, works the second, but with some errors about my Flow annotations, and works just fine the third time...

build-storybook always fails:

❯ build-storybook
info @storybook/react v6.5.10
info 
info => Cleaning outputDir: /Users/federicozivolo/Developer/frontend/storybook-static
info => Loading presets
info => Copying static files: /Users/federicozivolo/Developer/frontend/public at /Users/federicozivolo/Developer/frontend/storybook-static/
info => Compiling manager..
ERR! TypeError: previewBuilder.bail is not a function
ERR!     at /Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:219:26
ERR!     at async Promise.all (index 0)
ERR!     at async buildStaticStandalone (/Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:218:28)
ERR!     at async buildStatic (/Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:254:5)
ERR!  TypeError: previewBuilder.bail is not a function
ERR!     at /Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:219:26
ERR!     at async Promise.all (index 0)
ERR!     at async buildStaticStandalone (/Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:218:28)
ERR!     at async buildStatic (/Users/federicozivolo/Developer/frontend/node_modules/@storybook/core-server/dist/cjs/build-static.js:254:5)
info => Loading presets

Link to Minimal Reproducible Example

No response

Participation

  • I am willing to submit a pull request for this issue.
@FezVrasta FezVrasta added the bug Something isn't working label Aug 24, 2022
@FezVrasta FezVrasta changed the title [Bug] [Bug] TypeError: previewBuilder.bail is not a function Aug 24, 2022
@AnnikenYT
Copy link

Having a similar issue:
Package vite-plugin-pages

const Pages = require('vite-plugin-pages');
module.exports = {
/* ... */
  async viteFinal(config, { configType }) {
    return mergeConfig(config, {
        plugins: [
            Pages({
            extensions: ['vue']
        })]
    });
  }
}

=> ERR! TypeError: Pages is not a function

@FezVrasta
Copy link
Author

@AnnikenYT that seems a completely unrelated error.

@IanVS
Copy link
Member

IanVS commented Aug 24, 2022

That's very strange, @FezVrasta. It's definitely a function:

async function bail(e?: Error): Promise<void> {
try {
return await server.close();
} catch (err) {
console.warn('unable to close vite server');
}
throw e;
}

Can you share your .storybook/main.js?

@FezVrasta
Copy link
Author

FezVrasta commented Aug 24, 2022

Thanks for looking into it @IanVS , this is my main.js

const path = require('path');
const { mergeConfig } = require('vite');
const customConfig = require('../vite.config.js');

module.exports = {
  core: { builder: '@storybook/builder-vite' },
  stories: ['../src/**/*.stories.@(mdx|js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-essentials'],
  staticDirs: ['../public'],
  viteFinal(storybookConfig) {
    const config = mergeConfig(customConfig({}), storybookConfig);
    return config;
  },
};

And this is my vite.config.js if it helps:

// @noflow
const { defineConfig, loadEnv } = require('vite');
const react = require('@vitejs/plugin-react');
const svgr = require('vite-plugin-svgr');
const { VitePWA } = require('vite-plugin-pwa');
const {
  esbuildFlowPlugin: esbuildFlow,
  flowPlugin: flow,
} = require('@bunchtogether/vite-plugin-flow');
const { createHtmlPlugin } = require('vite-plugin-html');
const path = require('path');
const { readdirSync, readFileSync } = require('fs');
const hasha = require('hasha');
const { viteStaticCopy } = require('vite-plugin-static-copy');
const { itkImageIoVersion, itkVersion, writeConfigurationFile } = require('./scripts/itk-config');

const srcPath = path.resolve('./src/');
const srcRootContent = readdirSync(srcPath, { withFileTypes: true }).map((dirent) =>
  dirent.name.replace(/(\.js)/, '')
);
const absolutePathAliases = srcRootContent.reduce((acc, directory) => {
  acc[directory] = path.join(srcPath, directory);
  return acc;
}, {});

const itkModulePath = path.parse(path.resolve('./node_modules/itk-wasm/package.json')).dir;
const itkImageIoModulePath = path.parse(require.resolve('itk-image-io').replace(/\\/g, '/')).dir;
const publicPath = path.resolve(__dirname, './public');

writeConfigurationFile(publicPath);

// https://vitejs.dev/config/
module.exports = defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd()); // reuse vite's env parser to inject into our index.html

  return {
    server: {
      host: true,
      port: 3000,
    },
    optimizeDeps: {
      esbuildOptions: {
        plugins: [esbuildFlow()],
      },
    },
    resolve: {
      alias: {
        ...absolutePathAliases,
        './itkConfig.js': path.join(publicPath, 'itk/configuration.js'),
        '../itkConfig.js': path.join(publicPath, 'itk/configuration.js'),
        '../../itkConfig.js': path.join(publicPath, 'itk/configuration.js'),
      },
    },
    build: {
      outDir: './build',
    },
    define: {
      // The schema version is automatically generated starting from the GraphQL Flow types
      // anytime the schema changes, the hash will change, and the client will be forced to
      // flush the cache and start from scratch
      'import.meta.env.GRAPHQL_SCHEMA_VERSION': JSON.stringify(
        hasha(
          readFileSync(path.join(__dirname, 'src/generated/graphql.js'), {
            encoding: 'utf8',
          })
        )
      ),
    },
    plugins: [
      viteStaticCopy({
        targets: [
          {
            src: path.join(itkModulePath, 'dist', 'web-workers'),
            dest: path.join(publicPath, 'itk'),
            rename: `web-workers.${itkVersion}`,
          },
          {
            src: path.join(itkImageIoModulePath, '*'),
            dest: path.join(publicPath, 'itk', `image-io.${itkImageIoVersion}`),
            transform: (content, filePath) => {
              const fileName = path.basename(filePath);
              const imageIoModules = [
                'ReadImageDICOMFileSeries',
                'ReadDICOMTags',
                'MetaImageIOWriteImage',
                'MetaImageIOReadImage',
                'NrrdImageIOReadImage',
              ];
              const shouldCopy = imageIoModules.some((pattern) => fileName.startsWith(pattern));
              return shouldCopy ? content : null;
            },
          },
        ],
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: { ...env, MODE: mode },
        },
      }),
      flow(),
      react({
        babel: {
          plugins: ['babel-plugin-styled-components'],
        },
      }),
      svgr(),
      VitePWA({
        strategies: 'injectManifest',
        srcDir: 'src',
        filename: 'sw.js',
        injectManifest: {
          maximumFileSizeToCacheInBytes: 3000000, // 3 MiB
        },
      }),
    ],
  };
});

@FezVrasta
Copy link
Author

FezVrasta commented Aug 24, 2022

I tried to add a console.log right before bail is called and this is what I see:

{          
  start: [AsyncFunction: start],
  build: [AsyncFunction: build],
  corePresets: [],
  previewPresets: []
}

The builderPackage variable gets set to /Users/federicozivolo/Developer/frontend/node_modules/@storybook/builder-vite/dist/index.js

I may be wrong but bail is only returned as part of the start() payload? Not as part of the previewBuilder object itself.

In any case, it looks like bail is called right before an error is thrown, in my case if I mock bail with a noop the call works and I end up with this error:

ERR! TypeError: Cannot read properties of undefined (reading 'tap')
ERR!     at HtmlWebpackPlugin.apply (/Users/federicozivolo/Developer/frontend/node_modules/html-webpack-plugin/index.js:40:31)

I'm not sure why it's trying to use webpack though.

@FezVrasta
Copy link
Author

Oh my, I'm sorry, I noticed I had a custom resolution for "html-webpack-plugin": "^5.5.0", because in the past there was a problem with Storybook not picking the correct one, removing it fixes the issue of course 🤦

I think there's still a problem with that bail call though, but it's not an issue as long the build doesn't fail and needs to call it.

Also, now I get an out of memory error when I try to build my app :-(


<--- Last few GCs --->

[38226:0x158008000]    73516 ms: Mark-sweep 4026.5 (4141.2) -> 4023.6 (4140.3) MB, 1221.8 / 0.0 ms  (average mu = 0.334, current mu = 0.032) allocation failure scavenge might not succeed
[38226:0x158008000]    75659 ms: Mark-sweep 4039.3 (4140.3) -> 4038.1 (4169.0) MB, 2139.8 / 0.0 ms  (average mu = 0.141, current mu = 0.002) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
 1: 0x102a646e8 node::Abort() [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 2: 0x102a64870 node::errors::TryCatchScope::~TryCatchScope() [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 3: 0x102bb4000 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 4: 0x102bb3f94 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 5: 0x102d376ac v8::internal::Heap::GarbageCollectionReasonToString(v8::internal::GarbageCollectionReason) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 6: 0x102d361cc v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 7: 0x102d41514 v8::internal::Heap::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 8: 0x102d415a8 v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
 9: 0x102d1443c v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
10: 0x10304c540 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
11: 0x103360bcc Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
12: 0x10331d898 Builtins_ArrayPrototypePush [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
13: 0x1083d4a88 
14: 0x1088cccfc 
15: 0x109d2cac8 
16: 0x107c2e57c 
17: 0x108df6918 
18: 0x1032f4858 Builtins_InterpreterEntryTrampoline [/Users/federicozivolo/.nvm/versions/node/v16.16.0/bin/node]
19: 0x107e3b124 

@IanVS
Copy link
Member

IanVS commented Aug 24, 2022

Webpack is still used for the "manager" part of storybook (the sidebar, addons panel, toolbar, etc), at least until storybook 7 is released.

This looks like a bug in the vite-builder, but I'm not sure why we've never hit it before.

In the meantime, I think your config will also cause some problems. If you merge in your vite plugins to the storybook config, you will have duplicate react plugins.

I saw your latest comment, glad that was the issue. But yes, we should still fix the bail issue.

As for the memory, we find that vite requires a lot of memory to build, and storybook together with it adds even more. You can normally use --max-old-space-size to increase the memory available to node while building.

@ariaBennett
Copy link

ariaBennett commented Sep 7, 2022

For what it's worth I'm hitting this same issue. I've been on a long chain of dependency errors starting I think with upgrading react-scripts to v5 which led to updating all sorts of things, and I'm assuming updating typescript which ran me into webpack errors. I ran the storybook terminal migration and also added an override for webpack 5.74 in my package.json and now I'm here.

Update: Looks like removing webpack and the webpack override from my package json has things working again.

Looking forward to v7! ;)

@shadow7412
Copy link

shadow7412 commented Oct 27, 2022

@joshwooding I'm getting this issue too. Can this fix be released to NPM?

@joshwooding
Copy link
Member

@shadow7412 0.2.5 has now been released 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants