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

CLI: Fix sb add / mdx-gfm for addons with non-serializable values #21731

Merged
merged 2 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions code/lib/cli/src/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,6 @@ export async function add(
return;
}
const main = await readConfig(mainConfig);
const addons = main.getFieldValue(['addons']);
if (addons && !Array.isArray(addons)) {
logger.error('Expected addons array in main.js config');
}

logger.log(`Verifying ${addonName}`);
const latestVersion = packageManager.latestVersion(addonName);
if (!latestVersion) {
Expand All @@ -109,8 +104,7 @@ export async function add(

// add to main.js
logger.log(`Adding '${addon}' to main.js addons field.`);
const updatedAddons = [...(addons || []), addonName];
main.setFieldValue(['addons'], updatedAddons);
main.appendValueToArray(['addons'], addonName);
await writeConfig(main);

if (!options.skipPostinstall) {
Expand Down
6 changes: 1 addition & 5 deletions code/lib/cli/src/automigrate/fixes/mdx-gfm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,9 @@ export const mdxgfm: Fix<Options> = {
);

await updateMainConfig({ mainConfigPath, dryRun }, async (main) => {
const addonsToAdd = ['@storybook/addon-mdx-gfm'];

const existingAddons = main.getFieldValue(['addons']) as Preset[];
const updatedAddons = [...existingAddons, ...addonsToAdd];
logger.info(`✅ Adding "@storybook/addon-mdx-gfm" addon`);
if (!dryRun) {
main.setFieldValue(['addons'], updatedAddons);
main.appendValueToArray(['addons'], '@storybook/addon-mdx-gfm');
}
});
}
Expand Down
69 changes: 69 additions & 0 deletions code/lib/csf-tools/src/ConfigFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ const setField = (path: string[], value: any, source: string) => {
return formatConfig(config);
};

const appendToArray = (path: string[], value: any, source: string) => {
const config = loadConfig(source).parse();
config.appendValueToArray(path, value);
return formatConfig(config);
};

const removeField = (path: string[], source: string) => {
const config = loadConfig(source).parse();
config.removeField(path);
Expand Down Expand Up @@ -450,6 +456,69 @@ describe('ConfigFile', () => {
});
});

describe('appendToArray', () => {
it('missing export', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { core: { builder: 'webpack5' } };
`
)
).toMatchInlineSnapshot(`
export default {
core: {
builder: 'webpack5'
},
addons: ['docs']
};
`);
});
it('found scalar', () => {
expect(() =>
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: 5 };
`
)
).toThrowErrorMatchingInlineSnapshot(`Expected array at 'addons', got 'NumericLiteral'`);
});
it('array of simple values', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: ['a11y', 'viewport'] };
`
)
).toMatchInlineSnapshot(`
export default {
addons: ['a11y', 'viewport', 'docs']
};
`);
});

it('array of complex values', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: [require.resolve('a11y'), someVariable] };
`
)
).toMatchInlineSnapshot(`
export default {
addons: [require.resolve('a11y'), someVariable, 'docs']
};
`);
});
});

describe('removeField', () => {
describe('named exports', () => {
it('missing export', () => {
Expand Down
23 changes: 22 additions & 1 deletion code/lib/csf-tools/src/ConfigFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,22 @@ export class ConfigFile {
}
}

appendValueToArray(path: string[], value: any) {
const node = this.valueToNode(value);
this.appendNodeToArray(path, node);
}

appendNodeToArray(path: string[], node: t.Expression) {
const current = this.getFieldNode(path);
if (!current) {
this.setFieldNode(path, t.arrayExpression([node]));
} else if (t.isArrayExpression(current)) {
current.elements.push(node);
} else {
throw new Error(`Expected array at '${path.join('.')}', got '${current.type}'`);
}
}

_inferQuotes() {
if (!this._quotes) {
// first 500 tokens for efficiency
Expand All @@ -462,7 +478,7 @@ export class ConfigFile {
return this._quotes;
}

setFieldValue(path: string[], value: any) {
valueToNode(value: any) {
const quotes = this._inferQuotes();
let valueNode;
// we do this rather than t.valueToNode because apparently
Expand All @@ -488,6 +504,11 @@ export class ConfigFile {
// double quotes is the default so we can skip all that
valueNode = t.valueToNode(value);
}
return valueNode;
}

setFieldValue(path: string[], value: any) {
const valueNode = this.valueToNode(value);
if (!valueNode) {
throw new Error(`Unexpected value ${JSON.stringify(value)}`);
}
Expand Down