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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: Improve internal types #23632

Merged
merged 2 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion code/lib/core-common/src/utils/validate-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const renderers = ['html', 'preact', 'react', 'server', 'svelte', 'vue', 'vue3',

const rendererNames = [...renderers, ...renderers.map((renderer) => `@storybook/${renderer}`)];

export function validateFrameworkName(frameworkName: string | undefined) {
export function validateFrameworkName(
frameworkName: string | undefined
): asserts frameworkName is string {
const automigrateMessage = `Please run 'npx storybook@next automigrate' to automatically fix your config.

See the migration guide for more information:
Expand Down
29 changes: 15 additions & 14 deletions code/lib/core-server/src/build-dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ export async function buildDevStandalone(
options: CLIOptions & LoadOptions & BuilderOptions
): Promise<{ port: number; address: string; networkAddress: string }> {
const { packageJson, versionUpdates } = options;
const { version } = packageJson;
invariant(version !== undefined, 'Expected package.json version to be defined.');
invariant(
packageJson.version !== undefined,
`Expected package.json#version to be defined in the "${packageJson.name}" package}`
);
// updateInfo are cached, so this is typically pretty fast
const [port, versionCheck] = await Promise.all([
getServerPort(options.port),
versionUpdates
? updateCheck(version)
? updateCheck(packageJson.version)
: Promise.resolve({ success: false, cached: false, data: {}, time: Date.now() }),
]);

Expand All @@ -64,10 +66,9 @@ export async function buildDevStandalone(

const config = await loadMainConfig(options);
const { framework } = config;
invariant(framework, 'framework is required in Storybook v7');
const corePresets = [];

const frameworkName = typeof framework === 'string' ? framework : framework.name;
const frameworkName = typeof framework === 'string' ? framework : framework?.name;
validateFrameworkName(frameworkName);

corePresets.push(join(frameworkName, 'preset'));
Expand All @@ -84,7 +85,8 @@ export async function buildDevStandalone(
});

const { renderer, builder, disableTelemetry } = await presets.apply<CoreConfig>('core', {});
invariant(builder, 'no builder configured!');

invariant(builder, 'No builder configured in core.builder');

if (!options.disableTelemetry && !disableTelemetry) {
if (versionCheck.success && !versionCheck.cached) {
Expand All @@ -98,9 +100,8 @@ export async function buildDevStandalone(
getManagerBuilder(),
]);

const resolvedRenderer = renderer
? resolveAddonName(options.configDir, renderer, options)
: undefined;
const resolvedRenderer = renderer && resolveAddonName(options.configDir, renderer, options);

// Load second pass: all presets are applied in order
presets = await loadAllPresets({
corePresets: [
Expand Down Expand Up @@ -128,10 +129,10 @@ export async function buildDevStandalone(
fullOptions
);

const previewTotalTime = previewResult && previewResult.totalTime;
const managerTotalTime = managerResult ? managerResult.totalTime : undefined;
const previewStats = previewResult && previewResult.stats;
const managerStats = managerResult && managerResult.stats;
const previewTotalTime = previewResult?.totalTime;
const managerTotalTime = managerResult?.totalTime;
const previewStats = previewResult?.stats;
const managerStats = managerResult?.stats;

if (options.webpackStatsJson) {
const target = options.webpackStatsJson === true ? options.outputDir : options.webpackStatsJson;
Expand Down Expand Up @@ -162,7 +163,7 @@ export async function buildDevStandalone(
if (!options.quiet) {
outputStartupInformation({
updateInfo: versionCheck,
version,
version: packageJson.version,
name,
address,
networkAddress,
Expand Down
7 changes: 3 additions & 4 deletions code/lib/core-server/src/build-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,21 +173,20 @@ export async function buildStaticStandalone(options: BuildStaticStandaloneOption
storyStoreV7: !!features?.storyStoreV7,
});

const initializedStoryIndexGeneratorPromise = generator.initialize().then(() => generator);
initializedStoryIndexGenerator = generator.initialize().then(() => generator);
effects.push(
extractStoriesJson(
join(options.outputDir, 'stories.json'),
initializedStoryIndexGeneratorPromise,
initializedStoryIndexGenerator as Promise<StoryIndexGenerator>,
convertToIndexV3
)
);
effects.push(
extractStoriesJson(
join(options.outputDir, 'index.json'),
initializedStoryIndexGeneratorPromise
initializedStoryIndexGenerator as Promise<StoryIndexGenerator>
)
);
initializedStoryIndexGenerator = initializedStoryIndexGeneratorPromise;
}

if (!core?.disableProjectJson) {
Expand Down
13 changes: 4 additions & 9 deletions code/lib/core-server/src/utils/get-builders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,10 @@ export async function getPreviewBuilder(
builderName: string,
configDir: string
): Promise<Builder<unknown>> {
let builderPackage: string;
if (builderName) {
builderPackage = require.resolve(
['webpack5'].includes(builderName) ? `@storybook/builder-${builderName}` : builderName,
{ paths: [configDir] }
);
} else {
throw new Error('no builder configured!');
}
const builderPackage = require.resolve(
['webpack5'].includes(builderName) ? `@storybook/builder-${builderName}` : builderName,
{ paths: [configDir] }
);
const previewBuilder = await import(pathToFileURL(builderPackage).href);
return previewBuilder;
}
Expand Down
64 changes: 32 additions & 32 deletions code/lib/core-server/src/utils/getStoryIndexGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,40 +14,40 @@ export async function getStoryIndexGenerator(
},
options: Options,
serverChannel: ServerChannel
) {
if (features?.buildStoriesJson || features?.storyStoreV7) {
const workingDir = process.cwd();
const directories = {
configDir: options.configDir,
workingDir,
};
const stories = options.presets.apply('stories');
const deprecatedStoryIndexers = options.presets.apply('storyIndexers', []);
const indexers = options.presets.apply('indexers', []);
const docsOptions = options.presets.apply<DocsOptions>('docs', {});
const normalizedStories = normalizeStories(await stories, directories);
): Promise<StoryIndexGenerator | undefined> {
if (!features?.buildStoriesJson && !features?.storyStoreV7) {
return undefined;
}
const workingDir = process.cwd();
const directories = {
configDir: options.configDir,
workingDir,
};
const stories = options.presets.apply('stories');
const deprecatedStoryIndexers = options.presets.apply('storyIndexers', []);
const indexers = options.presets.apply('indexers', []);
const docsOptions = options.presets.apply<DocsOptions>('docs', {});
const normalizedStories = normalizeStories(await stories, directories);

const generator = new StoryIndexGenerator(normalizedStories, {
...directories,
storyIndexers: await deprecatedStoryIndexers,
indexers: await indexers,
docs: await docsOptions,
workingDir,
storiesV2Compatibility: !features?.storyStoreV7,
storyStoreV7: features.storyStoreV7 ?? false,
});
const generator = new StoryIndexGenerator(normalizedStories, {
...directories,
storyIndexers: await deprecatedStoryIndexers,
indexers: await indexers,
docs: await docsOptions,
workingDir,
storiesV2Compatibility: !features?.storyStoreV7,
storyStoreV7: features.storyStoreV7 ?? false,
});

const initializedStoryIndexGenerator = generator.initialize().then(() => generator);
const initializedStoryIndexGenerator = generator.initialize().then(() => generator);

useStoriesJson({
router,
initializedStoryIndexGenerator,
normalizedStories,
serverChannel,
workingDir,
});
useStoriesJson({
router,
initializedStoryIndexGenerator,
normalizedStories,
serverChannel,
workingDir,
});

return initializedStoryIndexGenerator;
}
return Promise.resolve(undefined);
return initializedStoryIndexGenerator;
}
5 changes: 3 additions & 2 deletions code/lib/core-server/src/utils/server-statics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { dedent } from 'ts-dedent';
import { defaultStaticDirs } from './constants';

export async function useStatics(router: any, options: Options) {
const staticDirs = await options.presets.apply<StorybookConfig['staticDirs']>('staticDirs');
const staticDirs =
(await options.presets.apply<StorybookConfig['staticDirs']>('staticDirs')) ?? [];
const faviconPath = await options.presets.apply<string>('favicon');

if (options.staticDir && !isEqual(staticDirs, defaultStaticDirs)) {
Expand All @@ -26,7 +27,7 @@ export async function useStatics(router: any, options: Options) {
}

const statics = [
...(staticDirs ?? []).map((dir) => (typeof dir === 'string' ? dir : `${dir.from}:${dir.to}`)),
...staticDirs.map((dir) => (typeof dir === 'string' ? dir : `${dir.from}:${dir.to}`)),
...(options.staticDir || []),
];

Expand Down
13 changes: 9 additions & 4 deletions code/lib/core-server/src/withTelemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { loadAllPresets, cache } from '@storybook/core-common';
import { telemetry, getPrecedingUpgrade, oneWayHash } from '@storybook/telemetry';
import type { EventType } from '@storybook/telemetry';
import { logger } from '@storybook/node-logger';
import invariant from 'tiny-invariant';

type TelemetryOptions = {
cliOptions: CLIOptions;
Expand Down Expand Up @@ -66,7 +67,7 @@ async function getErrorLevel({
}

export async function sendTelemetryError(
error: Error,
error: unknown,
eventType: EventType,
options: TelemetryOptions
) {
Expand All @@ -80,13 +81,17 @@ export async function sendTelemetryError(
if (errorLevel !== 'none') {
const precedingUpgrade = await getPrecedingUpgrade();

invariant(
error instanceof Error,
'The error passed to sendTelemetryError was not an Error, please only send Errors'
);
await telemetry(
'error',
{
eventType,
precedingUpgrade,
error: errorLevel === 'full' ? error : undefined,
errorHash: oneWayHash(error.message || ''),
errorHash: oneWayHash(error.message),
},
{
immediate: true,
Expand Down Expand Up @@ -132,8 +137,8 @@ export async function withTelemetry<T>(
}

const { printError = logger.error } = options;
printError(error instanceof Error ? error.message : String(error));
if (error instanceof Error) await sendTelemetryError(error, eventType, options);
printError(error);
await sendTelemetryError(error, eventType, options);

throw error;
} finally {
Expand Down
3 changes: 2 additions & 1 deletion code/lib/node-logger/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export const logger = {
plain: (message: string): void => console.log(message),
line: (count = 1): void => console.log(`${Array(count - 1).fill('\n')}`),
warn: (message: string): void => npmLog.warn('', message),
error: (message: string): void => npmLog.error('', message),
// npmLog supports anything we log, it will just stringify it
error: (message: unknown): void => npmLog.error('', message as string),
trace: ({ message, time }: { message: string; time: [number, number] }): void =>
npmLog.info('', `${message} (${colors.purple(prettyTime(time))})`),
setLevel: (level = 'info'): void => {
Expand Down