refactor(core): migrate utils to TS

This commit is contained in:
Gaëtan Maisse 2020-09-28 21:24:40 +02:00
parent 28eb52414f
commit e71835cb84
No known key found for this signature in database
GPG Key ID: D934C0EF3714A8A8
19 changed files with 77 additions and 36 deletions

View File

@ -134,6 +134,8 @@
"webpack-virtual-modules": "^0.2.2" "webpack-virtual-modules": "^0.2.2"
}, },
"devDependencies": { "devDependencies": {
"@types/mock-fs": "^4.10.0",
"@types/interpret": "^1.1.1",
"mock-fs": "^4.12.0" "mock-fs": "^4.12.0"
}, },
"peerDependencies": { "peerDependencies": {

View File

@ -14,13 +14,13 @@ function sortExtensions() {
const possibleExtensions = sortExtensions(); const possibleExtensions = sortExtensions();
export function getInterpretedFile(pathToFile) { export function getInterpretedFile(pathToFile: string) {
return possibleExtensions return possibleExtensions
.map((ext) => (pathToFile.endsWith(ext) ? pathToFile : `${pathToFile}${ext}`)) .map((ext) => (pathToFile.endsWith(ext) ? pathToFile : `${pathToFile}${ext}`))
.find((candidate) => fs.existsSync(candidate)); .find((candidate) => fs.existsSync(candidate));
} }
export function getInterpretedFileWithExt(pathToFile) { export function getInterpretedFileWithExt(pathToFile: string) {
return possibleExtensions return possibleExtensions
.map((ext) => ({ path: pathToFile.endsWith(ext) ? pathToFile : `${pathToFile}${ext}`, ext })) .map((ext) => ({ path: pathToFile.endsWith(ext) ? pathToFile : `${pathToFile}${ext}`, ext }))
.find((candidate) => fs.existsSync(candidate.path)); .find((candidate) => fs.existsSync(candidate.path));

View File

@ -4,7 +4,7 @@ import JSON5 from 'json5';
import { logger } from '@storybook/node-logger'; import { logger } from '@storybook/node-logger';
function removeReactHmre(presets) { function removeReactHmre(presets: string[]) {
const index = presets.indexOf('react-hmre'); const index = presets.indexOf('react-hmre');
if (index > -1) { if (index > -1) {
presets.splice(index, 1); presets.splice(index, 1);
@ -12,9 +12,12 @@ function removeReactHmre(presets) {
} }
// Tries to load a .babelrc and returns the parsed object if successful // Tries to load a .babelrc and returns the parsed object if successful
function loadFromPath(babelConfigPath) { function loadFromPath(babelConfigPath: string) {
let config; let config;
const error = {}; const error: {
js?: any;
json?: any;
} = {};
if (fs.existsSync(babelConfigPath)) { if (fs.existsSync(babelConfigPath)) {
const content = fs.readFileSync(babelConfigPath, 'utf-8'); const content = fs.readFileSync(babelConfigPath, 'utf-8');
@ -65,7 +68,7 @@ function loadFromPath(babelConfigPath) {
return config; return config;
} }
export default async function (configDir, getDefaultConfig) { export default async function (configDir: string, getDefaultConfig: () => unknown) {
// Between versions 5.1.0 - 5.1.9 this loaded babel.config.js from the project // Between versions 5.1.0 - 5.1.9 this loaded babel.config.js from the project
// root, which was an unintentional breaking change. We can add back project support // root, which was an unintentional breaking change. We can add back project support
// in 6.0. // in 6.0.

View File

@ -3,5 +3,5 @@ import { serverRequire } from './server-require';
const webpackConfigs = ['webpack.config', 'webpackfile']; const webpackConfigs = ['webpack.config', 'webpackfile'];
export default (configDir) => export default (configDir: string) =>
serverRequire(webpackConfigs.map((configName) => path.resolve(configDir, configName))); serverRequire(webpackConfigs.map((configName) => path.resolve(configDir, configName)));

View File

@ -4,9 +4,7 @@ import dedent from 'ts-dedent';
import { getInterpretedFile } from './interpret-files'; import { getInterpretedFile } from './interpret-files';
const toArray = (a) => (a ? [a] : a); export function loadManagerOrAddonsFile({ configDir }: { configDir: string }) {
export function loadManagerOrAddonsFile({ configDir }) {
const storybookCustomAddonsPath = getInterpretedFile(path.resolve(configDir, 'addons')); const storybookCustomAddonsPath = getInterpretedFile(path.resolve(configDir, 'addons'));
const storybookCustomManagerPath = getInterpretedFile(path.resolve(configDir, 'manager')); const storybookCustomManagerPath = getInterpretedFile(path.resolve(configDir, 'manager'));

View File

@ -3,7 +3,7 @@ import dedent from 'ts-dedent';
import { getInterpretedFile } from './interpret-files'; import { getInterpretedFile } from './interpret-files';
export function loadPreviewOrConfigFile({ configDir }) { export function loadPreviewOrConfigFile({ configDir }: { configDir: string }) {
const storybookConfigPath = getInterpretedFile(path.resolve(configDir, 'config')); const storybookConfigPath = getInterpretedFile(path.resolve(configDir, 'config'));
const storybookPreviewPath = getInterpretedFile(path.resolve(configDir, 'preview')); const storybookPreviewPath = getInterpretedFile(path.resolve(configDir, 'preview'));

View File

@ -1,23 +1,38 @@
function plugins({ plugins: defaultPlugins = [] }, { plugins: customPlugins = [] }) { function plugins<T>(
{ plugins: defaultPlugins = [] }: { plugins?: T[] },
{ plugins: customPlugins = [] }: { plugins?: T[] }
): T[] {
return [...defaultPlugins, ...customPlugins]; return [...defaultPlugins, ...customPlugins];
} }
function rules({ rules: defaultRules = [] }, { rules: customRules = [] }) { function rules<T>(
{ rules: defaultRules = [] }: { rules?: T[] },
{ rules: customRules = [] }: { rules?: T[] }
): T[] {
return [...defaultRules, ...customRules]; return [...defaultRules, ...customRules];
} }
function extensions({ extensions: defaultExtensions = [] }, { extensions: customExtensions = [] }) { function extensions<T>(
{ extensions: defaultExtensions = [] }: { extensions?: T[] },
{ extensions: customExtensions = [] }: { extensions?: T[] }
): T[] {
return [...defaultExtensions, ...customExtensions]; return [...defaultExtensions, ...customExtensions];
} }
function alias({ alias: defaultAlias = {} }, { alias: customAlias = {} }) { function alias(
{ alias: defaultAlias = {} }: { alias?: any },
{ alias: customAlias = {} }: { alias?: any }
) {
return { return {
...defaultAlias, ...defaultAlias,
...customAlias, ...customAlias,
}; };
} }
function module({ module: defaultModule = {} }, { module: customModule = {} }) { function module(
{ module: defaultModule = {} }: { module?: any },
{ module: customModule = {} }: { module?: any }
) {
return { return {
...defaultModule, ...defaultModule,
...customModule, ...customModule,
@ -25,7 +40,10 @@ function module({ module: defaultModule = {} }, { module: customModule = {} }) {
}; };
} }
function resolve({ resolve: defaultResolve = {} }, { resolve: customResolve = {} }) { function resolve(
{ resolve: defaultResolve = {} }: { resolve?: any },
{ resolve: customResolve = {} }: { resolve?: any }
) {
return { return {
...defaultResolve, ...defaultResolve,
...customResolve, ...customResolve,
@ -35,8 +53,8 @@ function resolve({ resolve: defaultResolve = {} }, { resolve: customResolve = {}
} }
function optimization( function optimization(
{ optimization: defaultOptimization = {} }, { optimization: defaultOptimization = {} }: { optimization?: any },
{ optimization: customOptimization = {} } { optimization: customOptimization = {} }: { optimization?: any }
) { ) {
return { return {
...defaultOptimization, ...defaultOptimization,
@ -44,7 +62,7 @@ function optimization(
}; };
} }
function mergeConfigs(config, customConfig) { function mergeConfigs(config: any, customConfig: any) {
return { return {
// We'll always load our configurations after the custom config. // We'll always load our configurations after the custom config.
// So, we'll always load the stuff we need. // So, we'll always load the stuff we need.

View File

@ -1,7 +1,7 @@
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
export function getMiddleware(configDir) { export function getMiddleware(configDir: string) {
const middlewarePath = path.resolve(configDir, 'middleware.js'); const middlewarePath = path.resolve(configDir, 'middleware.js');
if (fs.existsSync(middlewarePath)) { if (fs.existsSync(middlewarePath)) {
let middlewareModule = require(middlewarePath); // eslint-disable-line let middlewareModule = require(middlewarePath); // eslint-disable-line

View File

@ -17,7 +17,13 @@ export const IGNORED_ADDONS = [
...DEFAULT_ADDONS, ...DEFAULT_ADDONS,
]; ];
export const getPrebuiltDir = async ({ configDir, options }) => { export const getPrebuiltDir = async ({
configDir,
options,
}: {
configDir: string;
options: { managerCache?: boolean };
}) => {
if (options.managerCache === false) return false; if (options.managerCache === false) return false;
const prebuiltDir = path.join(__dirname, '../../../prebuilt'); const prebuiltDir = path.join(__dirname, '../../../prebuilt');
@ -33,7 +39,7 @@ export const getPrebuiltDir = async ({ configDir, options }) => {
const { addons, refs, managerBabel, managerWebpack } = serverRequire(mainConfigFile); const { addons, refs, managerBabel, managerWebpack } = serverRequire(mainConfigFile);
if (!addons || refs || managerBabel || managerWebpack) return false; if (!addons || refs || managerBabel || managerWebpack) return false;
if (DEFAULT_ADDONS.some((addon) => !addons.includes(addon))) return false; if (DEFAULT_ADDONS.some((addon) => !addons.includes(addon))) return false;
if (addons.some((addon) => !IGNORED_ADDONS.includes(addon))) return false; if (addons.some((addon: string) => !IGNORED_ADDONS.includes(addon))) return false;
// Auto refs will not be listed in the config, so we have to verify there aren't any // Auto refs will not be listed in the config, so we have to verify there aren't any
const autoRefs = await getAutoRefs({ configDir }); const autoRefs = await getAutoRefs({ configDir });

View File

@ -9,7 +9,7 @@ import pkgDir from 'pkg-dir';
* @param fileOrDirectoryName {string} Name of the file or directory * @param fileOrDirectoryName {string} Name of the file or directory
* @return {string} Absolute path to the file or directory * @return {string} Absolute path to the file or directory
*/ */
export function resolvePathInStorybookCache(fileOrDirectoryName) { export function resolvePathInStorybookCache(fileOrDirectoryName: string) {
const cwd = process.cwd(); const cwd = process.cwd();
const projectDir = pkgDir.sync(cwd); const projectDir = pkgDir.sync(cwd);

View File

@ -7,7 +7,7 @@ import { getInterpretedFileWithExt } from './interpret-files';
const compilersState = new Map(); const compilersState = new Map();
function registerCompiler(moduleDescriptor) { function registerCompiler(moduleDescriptor: any): number {
if (!moduleDescriptor) { if (!moduleDescriptor) {
return 0; return 0;
} }
@ -47,7 +47,7 @@ function registerCompiler(moduleDescriptor) {
return registered; return registered;
} }
function interopRequireDefault(filePath) { function interopRequireDefault(filePath: string) {
// eslint-disable-next-line import/no-dynamic-require,global-require // eslint-disable-next-line import/no-dynamic-require,global-require
const result = require(filePath); const result = require(filePath);
@ -57,7 +57,7 @@ function interopRequireDefault(filePath) {
return isES6DefaultExported ? result.default : result; return isES6DefaultExported ? result.default : result;
} }
function getCandidate(paths) { function getCandidate(paths: string[]) {
for (let i = 0; i < paths.length; i += 1) { for (let i = 0; i < paths.length; i += 1) {
const candidate = getInterpretedFileWithExt(paths[i]); const candidate = getInterpretedFileWithExt(paths[i]);
@ -69,7 +69,7 @@ function getCandidate(paths) {
return undefined; return undefined;
} }
export function serverRequire(filePath) { export function serverRequire(filePath: string | string[]) {
const candidatePath = serverResolve(filePath); const candidatePath = serverResolve(filePath);
if (!candidatePath) { if (!candidatePath) {
@ -90,7 +90,7 @@ export function serverRequire(filePath) {
return interopRequireDefault(candidatePath); return interopRequireDefault(candidatePath);
} }
export function serverResolve(filePath) { export function serverResolve(filePath: string | string[]) {
const paths = Array.isArray(filePath) ? filePath : [filePath]; const paths = Array.isArray(filePath) ? filePath : [filePath];
const existingCandidate = getCandidate(paths); const existingCandidate = getCandidate(paths);

View File

@ -1,10 +1,10 @@
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
const interpolate = (string, data = {}) => const interpolate = (string: string, data: Record<string, string> = {}) =>
Object.entries(data).reduce((acc, [k, v]) => acc.replace(new RegExp(`%${k}%`, 'g'), v), string); Object.entries(data).reduce((acc, [k, v]) => acc.replace(new RegExp(`%${k}%`, 'g'), v), string);
export function getPreviewBodyHtml(configDirPath, interpolations) { export function getPreviewBodyHtml(configDirPath: string, interpolations?: Record<string, string>) {
const base = fs.readFileSync( const base = fs.readFileSync(
path.resolve(__dirname, '../templates/base-preview-body.html'), path.resolve(__dirname, '../templates/base-preview-body.html'),
'utf8' 'utf8'
@ -20,7 +20,7 @@ export function getPreviewBodyHtml(configDirPath, interpolations) {
return interpolate(result, interpolations); return interpolate(result, interpolations);
} }
export function getPreviewHeadHtml(configDirPath, interpolations) { export function getPreviewHeadHtml(configDirPath: string, interpolations?: Record<string, string>) {
const base = fs.readFileSync( const base = fs.readFileSync(
path.resolve(__dirname, '../templates/base-preview-head.html'), path.resolve(__dirname, '../templates/base-preview-head.html'),
'utf8' 'utf8'
@ -36,7 +36,7 @@ export function getPreviewHeadHtml(configDirPath, interpolations) {
return interpolate(result, interpolations); return interpolate(result, interpolations);
} }
export function getManagerHeadHtml(configDirPath, interpolations) { export function getManagerHeadHtml(configDirPath: string, interpolations: Record<string, string>) {
const base = fs.readFileSync( const base = fs.readFileSync(
path.resolve(__dirname, '../templates/base-manager-head.html'), path.resolve(__dirname, '../templates/base-manager-head.html'),
'utf8' 'utf8'

View File

@ -13,7 +13,7 @@ const warnLegacyConfigurationFiles = deprecate(
` `
); );
const errorMixingConfigFiles = (first, second, configDir) => { const errorMixingConfigFiles = (first: string, second: string, configDir: string) => {
const firstPath = path.resolve(configDir, first); const firstPath = path.resolve(configDir, first);
const secondPath = path.resolve(configDir, second); const secondPath = path.resolve(configDir, second);
throw new Error(dedent` throw new Error(dedent`
@ -25,9 +25,9 @@ const errorMixingConfigFiles = (first, second, configDir) => {
`); `);
}; };
export default function validateConfigurationFiles(configDir) { export default function validateConfigurationFiles(configDir: string) {
const extensionsPattern = `{${Array.from(boost).join(',')}}`; const extensionsPattern = `{${Array.from(boost).join(',')}}`;
const exists = (file) => const exists = (file: string) =>
!!glob.sync(path.resolve(configDir, `${file}${extensionsPattern}`)).length; !!glob.sync(path.resolve(configDir, `${file}${extensionsPattern}`)).length;
const main = exists('main'); const main = exists('main');

View File

@ -6113,6 +6113,13 @@
"@types/through" "*" "@types/through" "*"
rxjs "^6.4.0" rxjs "^6.4.0"
"@types/interpret@^1.1.1":
version "1.1.1"
resolved "https://registry.yarnpkg.com/@types/interpret/-/interpret-1.1.1.tgz#b1bf85b0420e2414b989ce237658ad20dc03719b"
integrity sha512-HZ4d0m2Ebl8DmrOdYZHgYyipj/8Ftq1/ssB/oQR7fqfUrwtTP7IW3BDi2V445nhPBLzZjEkApaPVp83moSCXlA==
dependencies:
"@types/node" "*"
"@types/is-function@^1.0.0": "@types/is-function@^1.0.0":
version "1.0.0" version "1.0.0"
resolved "https://registry.yarnpkg.com/@types/is-function/-/is-function-1.0.0.tgz#1b0b819b1636c7baf0d6785d030d12edf70c3e83" resolved "https://registry.yarnpkg.com/@types/is-function/-/is-function-1.0.0.tgz#1b0b819b1636c7baf0d6785d030d12edf70c3e83"
@ -6238,6 +6245,13 @@
resolved "https://registry.yarnpkg.com/@types/mithril/-/mithril-2.0.3.tgz#f24a764515d9b17095845838b12f2444757d93fa" resolved "https://registry.yarnpkg.com/@types/mithril/-/mithril-2.0.3.tgz#f24a764515d9b17095845838b12f2444757d93fa"
integrity sha512-cZHOdO2IiXYeyjeDYdbOisSdfaJRzfmRo3zVzgu33IWTMA0KEQObp9fdvqcuYdPz93iJ1yCl19GcEjo/9yv+yA== integrity sha512-cZHOdO2IiXYeyjeDYdbOisSdfaJRzfmRo3zVzgu33IWTMA0KEQObp9fdvqcuYdPz93iJ1yCl19GcEjo/9yv+yA==
"@types/mock-fs@^4.10.0":
version "4.10.0"
resolved "https://registry.yarnpkg.com/@types/mock-fs/-/mock-fs-4.10.0.tgz#460061b186993d76856f669d5317cda8a007c24b"
integrity sha512-FQ5alSzmHMmliqcL36JqIA4Yyn9jyJKvRSGV3mvPh108VFatX7naJDzSG4fnFQNZFq9dIx0Dzoe6ddflMB2Xkg==
dependencies:
"@types/node" "*"
"@types/node-cleanup@^2.1.1": "@types/node-cleanup@^2.1.1":
version "2.1.1" version "2.1.1"
resolved "https://registry.yarnpkg.com/@types/node-cleanup/-/node-cleanup-2.1.1.tgz#c8f78a648897d2a40ed10632268ce15d343cc191" resolved "https://registry.yarnpkg.com/@types/node-cleanup/-/node-cleanup-2.1.1.tgz#c8f78a648897d2a40ed10632268ce15d343cc191"