Skip to content
5 changes: 4 additions & 1 deletion code/core/src/common/js-package-manager/BUNProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@ export class BUNProxy extends JsPackageManager {

public async getModulePackageJSON(packageName: string): Promise<PackageJson | null> {
const wantedPath = join('node_modules', packageName, 'package.json');
const packageJsonPath = find.up(wantedPath, { cwd: this.cwd, last: getProjectRoot() });
const packageJsonPath = find.up(wantedPath, {
cwd: this.primaryPackageJson.operationDir,
last: getProjectRoot(),
});

if (!packageJsonPath) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export abstract class JsPackageManager {
abstract getRunCommand(command: string): string;

/** Get the package.json file for a given module. */
abstract getModulePackageJSON(packageName: string): Promise<PackageJson | null>;
abstract getModulePackageJSON(packageName: string, cwd?: string): Promise<PackageJson | null>;

isStorybookInMonorepo() {
const turboJsonPath = find.up(`turbo.json`, { last: getProjectRoot() });
Expand Down
5 changes: 4 additions & 1 deletion code/core/src/common/js-package-manager/NPMProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ export class NPMProxy extends JsPackageManager {

async getModulePackageJSON(packageName: string): Promise<PackageJson | null> {
const wantedPath = join('node_modules', packageName, 'package.json');
const packageJsonPath = find.up(wantedPath, { cwd: this.cwd, last: getProjectRoot() });
const packageJsonPath = find.up(wantedPath, {
cwd: this.primaryPackageJson.operationDir,
last: getProjectRoot(),
});

if (!packageJsonPath) {
return null;
Expand Down
5 changes: 4 additions & 1 deletion code/core/src/common/js-package-manager/PNPMProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ export class PNPMProxy extends JsPackageManager {
}

const wantedPath = join('node_modules', packageName, 'package.json');
const packageJsonPath = find.up(wantedPath, { cwd: this.cwd, last: getProjectRoot() });
const packageJsonPath = find.up(wantedPath, {
cwd: this.primaryPackageJson.operationDir,
last: getProjectRoot(),
});

if (!packageJsonPath) {
return null;
Expand Down
5 changes: 4 additions & 1 deletion code/core/src/common/js-package-manager/Yarn1Proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ export class Yarn1Proxy extends JsPackageManager {

public async getModulePackageJSON(packageName: string): Promise<PackageJson | null> {
const wantedPath = join('node_modules', packageName, 'package.json');
const packageJsonPath = find.up(wantedPath, { cwd: this.cwd, last: getProjectRoot() });
const packageJsonPath = find.up(wantedPath, {
cwd: this.primaryPackageJson.operationDir,
last: getProjectRoot(),
});

if (!packageJsonPath) {
return null;
Expand Down
2 changes: 1 addition & 1 deletion code/core/src/common/js-package-manager/Yarn2Proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ export class Yarn2Proxy extends JsPackageManager {
// TODO: Remove pnp compatibility code in SB11
async getModulePackageJSON(packageName: string): Promise<PackageJson | null> {
const pnpapiPath = find.any(['.pnp.js', '.pnp.cjs'], {
cwd: this.cwd,
cwd: this.primaryPackageJson.operationDir,
last: getProjectRoot(),
});

Expand Down
20 changes: 0 additions & 20 deletions code/core/src/common/utils/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import uniqueString from 'unique-string';
import type { JsPackageManager } from '../js-package-manager';
import satelliteAddons from '../satellite-addons';
import storybookPackagesVersions from '../versions';
import { rendererPackages } from './get-storybook-info';

const tempDir = () => realpath(os.tmpdir());

Expand Down Expand Up @@ -67,25 +66,6 @@ export function parseList(str: string): string[] {
.filter((item) => item.length > 0);
}

/**
* Given a package manager, returns the coerced version of Storybook. It tries to find renderer
* packages in the project and returns the coerced version of the first one found. Example: If
*
* @storybook/react version 8.0.0-alpha.14 is installed, it returns the coerced version 8.0.0
*/
export async function getCoercedStorybookVersion(packageManager: JsPackageManager) {
const packages = (
await Promise.all(
Object.keys(rendererPackages).map(async (pkg) => ({
name: pkg,
version: (await packageManager.getModulePackageJSON(pkg))?.version ?? null,
}))
)
).filter(({ version }) => !!version);

return packages[0]?.version || storybookPackagesVersions.storybook;
}

export function getEnvConfig(program: Record<string, any>, configEnv: Record<string, any>): void {
Object.keys(configEnv).forEach((fieldName) => {
const envVarName = configEnv[fieldName];
Expand Down
6 changes: 3 additions & 3 deletions code/core/src/common/utils/get-storybook-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,12 @@ export const getStorybookInfo = async (
const frameworkValue = mainConfig.framework;
const frameworkField = typeof frameworkValue === 'string' ? frameworkValue : frameworkValue?.name;
const addons = getAddonNames(mainConfig);
const version = getStorybookVersionSpecifier(configDir);
const versionSpecifier = getStorybookVersionSpecifier(configDir);

if (!frameworkField) {
return {
...configInfo,
version,
versionSpecifier,
addons,
mainConfig,
mainConfigPath: configInfo.mainConfigPath ?? undefined,
Expand Down Expand Up @@ -183,7 +183,7 @@ export const getStorybookInfo = async (
addons,
mainConfig,
framework,
version,
versionSpecifier,
renderer: renderer ?? undefined,
builder: builder ?? undefined,
frameworkPackage,
Expand Down
2 changes: 1 addition & 1 deletion code/core/src/telemetry/storybook-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ export const computeStorybookMetadata = async ({
portableStoriesFileCount,
applicationFileCount,
storybookVersion: version,
storybookVersionSpecifier: storybookInfo.version ?? '',
storybookVersionSpecifier: storybookInfo.versionSpecifier ?? '',
language,
storybookPackages,
addons,
Expand Down
2 changes: 1 addition & 1 deletion code/core/src/types/modules/core-common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ export type CoreCommon_AddonInfo = { name: string; inEssentials: boolean };

export interface CoreCommon_StorybookInfo {
addons: string[];
version?: string;
versionSpecifier?: string;
framework?: SupportedFramework;
renderer?: SupportedRenderer;
builder?: SupportedBuilder;
Expand Down
1 change: 0 additions & 1 deletion code/lib/cli-storybook/src/add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ vi.mock('storybook/internal/common', () => {
getAbsolutePathWrapperName: MockWrapGetAbsolutePathUtils.getAbsolutePathWrapperName,
wrapValueWithGetAbsolutePathWrapper:
MockWrapGetAbsolutePathUtils.wrapValueWithGetAbsolutePathWrapper,
getCoercedStorybookVersion: vi.fn(() => '8.0.0'),
versions: {
storybook: '8.0.0',
'@storybook/addon-docs': '8.0.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,18 +131,11 @@ export const removeEssentials: Fix<AddonDocsOptions> = {
dryRun,
packageManager,
configDir,
storybookVersion,
storiesPaths,
mainConfigPath,
previewConfigPath,
}) {
const {
hasEssentials,
hasDocsDisabled,
hasDocsAddon,
additionalAddonsToRemove,
essentialsOptions,
} = result;
const { hasEssentials, hasDocsDisabled, additionalAddonsToRemove, essentialsOptions } = result;

if (!hasEssentials && additionalAddonsToRemove.length === 0) {
return;
Expand Down
19 changes: 12 additions & 7 deletions code/lib/cli-storybook/src/automigrate/helpers/mainConfigFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
getStorybookInfo,
} from 'storybook/internal/common';
import type { PackageManagerName } from 'storybook/internal/common';
import { frameworkToRenderer, getCoercedStorybookVersion } from 'storybook/internal/common';
import { frameworkToRenderer } from 'storybook/internal/common';
import type { ConfigFile } from 'storybook/internal/csf-tools';
import { readConfig, writeConfig as writeConfigFile } from 'storybook/internal/csf-tools';
import { logger } from 'storybook/internal/node-logger';
Expand Down Expand Up @@ -101,11 +101,9 @@ export const getFrameworkOptions = (

export const getStorybookData = async ({
configDir: userDefinedConfigDir,
cwd,
packageManagerName,
}: {
configDir?: string;
cwd?: string;
packageManagerName?: PackageManagerName;
cache?: boolean;
}) => {
Expand All @@ -115,15 +113,19 @@ export const getStorybookData = async ({
mainConfigPath: mainConfigPath,
configDir: configDirFromScript,
previewConfigPath,
} = await getStorybookInfo(userDefinedConfigDir, cwd);
versionSpecifier,
} = await getStorybookInfo(
userDefinedConfigDir,
userDefinedConfigDir ? dirname(userDefinedConfigDir) : undefined
);

const configDir = userDefinedConfigDir || configDirFromScript || '.storybook';

logger.debug('Loading main config...');

const workingDir = isAbsolute(configDir)
? dirname(configDir)
: dirname(join(cwd ?? process.cwd(), configDir));
: dirname(join(process.cwd(), configDir));

logger.debug('Getting stories paths...');
const storiesPaths = await getStoriesPathsFromConfig({
Expand All @@ -140,12 +142,15 @@ export const getStorybookData = async ({
});

logger.debug('Getting Storybook version...');
const storybookVersion = await getCoercedStorybookVersion(packageManager);
const versionInstalled = (await packageManager.getModulePackageJSON('storybook'))?.version;

return {
configDir,
mainConfig,
storybookVersion,
/** The version specifier of Storybook from the user's package.json */
versionSpecifier,
/** The version of Storybook installed in the user's project */
versionInstalled,
mainConfigPath,
previewConfigPath,
packageManager,
Expand Down
33 changes: 12 additions & 21 deletions code/lib/cli-storybook/src/automigrate/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ vi.mock('storybook/internal/node-logger', () => ({
},
}));

const fixes: Fix<any>[] = [
const fixes: Fix[] = [
{
id: 'fix-1',

Expand Down Expand Up @@ -88,7 +88,7 @@ class PackageManager implements Partial<JsPackageManager> {
}
}

const packageManager = new PackageManager() as any as JsPackageManager;
const packageManager = new PackageManager() as unknown as JsPackageManager;

const dryRun = false;
const yes = true;
Expand All @@ -113,17 +113,10 @@ const common = {
storiesPaths: [],
};

const runFixWrapper = async ({
beforeVersion,
storybookVersion,
}: {
beforeVersion: string;
storybookVersion: string;
}) => {
const runFixWrapper = async ({ storybookVersion }: { storybookVersion: string }) => {
return runFixes({
...common,
storybookVersion,
beforeVersion,
});
};

Expand All @@ -134,15 +127,13 @@ const runAutomigrateWrapper = async ({
beforeVersion: string;
storybookVersion: string;
}) => {
getStorybookData.mockImplementation(() => {
return {
...common,
beforeVersion,
storybookVersion,
isLatest: true,
};
getStorybookData.mockResolvedValue({
...common,
beforeVersion,
versionInstalled: storybookVersion,
isLatest: true,
});
return doAutomigrate({ configDir });
return doAutomigrate({ configDir, fixes });
};

describe('runFixes', () => {
Expand All @@ -161,7 +152,7 @@ describe('runFixes', () => {
});

it('should be necessary to run fix-1 from SB 6.5.15 to 7.0.0', async () => {
const { fixResults } = await runFixWrapper({ beforeVersion, storybookVersion: '7.0.0' });
const { fixResults } = await runFixWrapper({ storybookVersion: '7.0.0' });

expect(fixResults).toEqual({
'fix-1': 'succeeded',
Expand All @@ -182,15 +173,15 @@ describe('runFixes', () => {
it('should fail if an error is thrown by migration', async () => {
check1.mockRejectedValue(new Error('check1 error'));

const { fixResults } = await runFixWrapper({ beforeVersion, storybookVersion: '7.0.0' });
const { fixResults } = await runFixWrapper({ storybookVersion: '7.0.0' });

expect(fixResults).toEqual({
'fix-1': 'check_failed',
});
expect(run1).not.toHaveBeenCalled();
});

it('should throw error if an error is thrown my migration', async () => {
it('should throw error if an error is thrown by migration', async () => {
check1.mockRejectedValue(new Error('check1 error'));

const result = runAutomigrateWrapper({ beforeVersion, storybookVersion: '7.0.0' });
Expand Down
10 changes: 3 additions & 7 deletions code/lib/cli-storybook/src/automigrate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const doAutomigrate = async (options: AutofixOptionsFromCLI) => {
mainConfig,
mainConfigPath,
previewConfigPath,
storybookVersion,
versionInstalled,
configDir,
packageManager,
storiesPaths,
Expand All @@ -55,7 +55,7 @@ export const doAutomigrate = async (options: AutofixOptionsFromCLI) => {
packageManagerName: options.packageManager,
});

if (!storybookVersion) {
if (!versionInstalled) {
throw new Error('Could not determine Storybook version');
}

Expand All @@ -66,8 +66,7 @@ export const doAutomigrate = async (options: AutofixOptionsFromCLI) => {
const outcome = await automigrate({
...options,
packageManager,
storybookVersion,
beforeVersion: storybookVersion,
storybookVersion: versionInstalled,
mainConfigPath,
mainConfig,
previewConfigPath,
Expand Down Expand Up @@ -114,7 +113,6 @@ export const automigrate = async ({
mainConfigPath,
previewConfigPath,
storybookVersion,
beforeVersion,
renderer: rendererPackage,
skipInstall,
hideMigrationSummary = false,
Expand Down Expand Up @@ -184,7 +182,6 @@ export const automigrate = async ({
mainConfig,
mainConfigPath,
storybookVersion,
beforeVersion,
isUpgrade: !!isUpgrade,
dryRun,
yes,
Expand Down Expand Up @@ -219,7 +216,6 @@ type RunFixesOptions = {
previewConfigPath?: string;
mainConfig: StorybookConfigRaw;
storybookVersion: string;
beforeVersion: string;
isUpgrade?: boolean;
};

Expand Down
2 changes: 0 additions & 2 deletions code/lib/cli-storybook/src/automigrate/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,6 @@ export interface AutofixOptions extends Omit<AutofixOptionsFromCLI, 'packageMana
mainConfigPath: string;
previewConfigPath?: string;
mainConfig: StorybookConfigRaw;
/** The version of Storybook before the migration. */
beforeVersion: string;
storybookVersion: string;
/** Whether the migration is part of an upgrade. */
isUpgrade: boolean;
Expand Down
Loading