@storybook/codemod 0.0.0-pr-23609-sha-f47ef339
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +262 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +1 -0
- package/dist/transforms/add-component-parameters.d.ts +22 -0
- package/dist/transforms/add-component-parameters.js +1 -0
- package/dist/transforms/csf-2-to-3.d.ts +8 -0
- package/dist/transforms/csf-2-to-3.js +3 -0
- package/dist/transforms/csf-hoist-story-annotations.d.ts +26 -0
- package/dist/transforms/csf-hoist-story-annotations.js +1 -0
- package/dist/transforms/mdx-to-csf.d.ts +7 -0
- package/dist/transforms/mdx-to-csf.js +61 -0
- package/dist/transforms/move-builtin-addons.d.ts +3 -0
- package/dist/transforms/move-builtin-addons.js +1 -0
- package/dist/transforms/storiesof-to-csf.d.ts +24 -0
- package/dist/transforms/storiesof-to-csf.js +1 -0
- package/dist/transforms/update-addon-info.d.ts +27 -0
- package/dist/transforms/update-addon-info.js +1 -0
- package/dist/transforms/update-organisation-name.d.ts +25 -0
- package/dist/transforms/update-organisation-name.js +1 -0
- package/dist/transforms/upgrade-deprecated-types.d.ts +10 -0
- package/dist/transforms/upgrade-deprecated-types.js +2 -0
- package/dist/transforms/upgrade-hierarchy-separators.d.ts +3 -0
- package/dist/transforms/upgrade-hierarchy-separators.js +1 -0
- package/jest.config.js +9 -0
- package/package.json +102 -0
- package/project.json +6 -0
- package/src/index.ts +103 -0
- package/src/lib/utils.test.js +9 -0
- package/src/lib/utils.ts +29 -0
- package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.input.js +44 -0
- package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.output.snapshot +68 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.input.js +25 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.output.snapshot +27 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.input.js +25 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.output.snapshot +28 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.input.js +13 -0
- package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.output.snapshot +17 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/basic.input.mdx +18 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/basic.output.snapshot +40 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/component-id.input.mdx +6 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/component-id.output.snapshot +17 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/decorators.input.mdx +8 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/decorators.output.snapshot +18 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.input.mdx +19 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.output.snapshot +39 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/parameters.input.mdx +14 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/parameters.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.input.mdx +3 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.output.snapshot +11 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-function.input.mdx +10 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-function.output.snapshot +18 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.input.mdx +18 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.output.snapshot +32 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.input.mdx +22 -0
- package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.output.snapshot +34 -0
- package/src/transforms/__testfixtures__/move-builtin-addons/default.input.js +2 -0
- package/src/transforms/__testfixtures__/move-builtin-addons/default.output.snapshot +8 -0
- package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.input.js +3 -0
- package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.output.snapshot +7 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/basic.input.js +18 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/basic.output.snapshot +45 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/collision.input.js +11 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/collision.output.snapshot +38 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/const.input.js +1 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/const.output.snapshot +13 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.input.js +9 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.output.snapshot +18 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/default.input.js +7 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/default.output.snapshot +17 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/digit.input.js +1 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.js +5 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.snapshot +9 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.input.js +11 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.input.js +12 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.input.js +14 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.output.snapshot +26 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/exports.input.js +2 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/exports.output.snapshot +16 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/module.input.js +12 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/module.output.snapshot +16 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/multi.input.js +14 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/multi.output.snapshot +39 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.input.js +8 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.output.snapshot +20 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.input.js +10 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.input.js +11 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.input.js +11 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.output.snapshot +29 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js +14 -0
- package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.output.snapshot +32 -0
- package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.input.js +184 -0
- package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.output.snapshot +184 -0
- package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.input.js +19 -0
- package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.output.snapshot +23 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.input.js +3 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.output.snapshot +7 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.input.js +5 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.output.snapshot +9 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.input.js +8 -0
- package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.output.snapshot +12 -0
- package/src/transforms/__tests__/csf-2-to-3.test.ts +439 -0
- package/src/transforms/__tests__/mdx-to-csf.test.ts +628 -0
- package/src/transforms/__tests__/transforms.tests.js +32 -0
- package/src/transforms/__tests__/upgrade-deprecated-types.test.ts +170 -0
- package/src/transforms/add-component-parameters.js +62 -0
- package/src/transforms/csf-2-to-3.ts +336 -0
- package/src/transforms/csf-hoist-story-annotations.js +97 -0
- package/src/transforms/mdx-to-csf.ts +340 -0
- package/src/transforms/move-builtin-addons.js +32 -0
- package/src/transforms/storiesof-to-csf.js +277 -0
- package/src/transforms/update-addon-info.js +114 -0
- package/src/transforms/update-organisation-name.js +71 -0
- package/src/transforms/upgrade-deprecated-types.ts +142 -0
- package/src/transforms/upgrade-hierarchy-separators.js +39 -0
- package/tsconfig.json +10 -0
package/README.md
ADDED
@@ -0,0 +1,262 @@
|
|
1
|
+
# Storybook Codemods
|
2
|
+
|
3
|
+
Storybook Codemods is a collection of codemod scripts written with JSCodeshift.
|
4
|
+
It will help you migrate breaking changes & deprecations.
|
5
|
+
|
6
|
+
## CLI Integration
|
7
|
+
|
8
|
+
The preferred way to run these codemods is via the CLI's `migrate` command.
|
9
|
+
|
10
|
+
To get a list of available codemods:
|
11
|
+
|
12
|
+
```
|
13
|
+
npx sb migrate --list
|
14
|
+
```
|
15
|
+
|
16
|
+
To run a codemod `<name-of-codemod>`:
|
17
|
+
|
18
|
+
```
|
19
|
+
npx sb migrate <name-of-codemod> --glob="**/*.stories.js"
|
20
|
+
```
|
21
|
+
|
22
|
+
## Installation
|
23
|
+
|
24
|
+
If you want to run these codemods by hand:
|
25
|
+
|
26
|
+
```sh
|
27
|
+
yarn add jscodeshift @storybook/codemod --dev
|
28
|
+
```
|
29
|
+
|
30
|
+
- `@storybook/codemod` is our collection of codemod scripts.
|
31
|
+
- `jscodeshift` is a tool we use to apply our codemods.
|
32
|
+
|
33
|
+
After running the migration commands, you can remove them from your `package.json`, if you added them.
|
34
|
+
|
35
|
+
## How to run a codemod script
|
36
|
+
|
37
|
+
From the directory where you installed both `jscodeshift` and `@storybook/codemod` run:
|
38
|
+
|
39
|
+
Example:
|
40
|
+
|
41
|
+
```sh
|
42
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/update-organisation-name.js . --ignore-pattern "node_modules|dist"
|
43
|
+
```
|
44
|
+
|
45
|
+
Explanation:
|
46
|
+
|
47
|
+
<jscodeShiftCommand> -t <transformFileLocation> <pathToSource> --ignore-pattern "<globPatternToIgnore>"
|
48
|
+
|
49
|
+
## Transforms
|
50
|
+
|
51
|
+
### update-organisation-name
|
52
|
+
|
53
|
+
Updates package names in imports to migrate to the new package names of storybook.
|
54
|
+
|
55
|
+
```sh
|
56
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/update-organisation-name.js . --ignore-pattern "node_modules|dist"
|
57
|
+
```
|
58
|
+
|
59
|
+
There's a mapping of paths we replace but this example explains the gist of it:
|
60
|
+
|
61
|
+
Example:
|
62
|
+
|
63
|
+
```js
|
64
|
+
import { storiesOf } from '@kadira/storybook';
|
65
|
+
import { linkTo } from '@kadira/storybook-addon-links';
|
66
|
+
```
|
67
|
+
|
68
|
+
Becomes
|
69
|
+
|
70
|
+
```js
|
71
|
+
import { storiesOf } from '@storybook/react';
|
72
|
+
import { linkTo } from '@storybook/addon-links';
|
73
|
+
```
|
74
|
+
|
75
|
+
### update-addon-info
|
76
|
+
|
77
|
+
Replaces the Info addon's deprecated `addWithInfo` API with the standard `withInfo` API.
|
78
|
+
|
79
|
+
```sh
|
80
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/update-addon-info.js . --ignore-pattern "node_modules|dist"
|
81
|
+
```
|
82
|
+
|
83
|
+
Example:
|
84
|
+
|
85
|
+
```js
|
86
|
+
storiesOf('Button').addWithInfo('simple usage', 'This is the basic usage of the button.', () => (
|
87
|
+
<Button label="The Button" />
|
88
|
+
));
|
89
|
+
```
|
90
|
+
|
91
|
+
Becomes
|
92
|
+
|
93
|
+
```js
|
94
|
+
storiesOf('Button').add(
|
95
|
+
'simple usage',
|
96
|
+
withInfo('This is the basic usage of the button.')(() => <Button label="The Button" />)
|
97
|
+
);
|
98
|
+
```
|
99
|
+
|
100
|
+
With options example:
|
101
|
+
|
102
|
+
```js
|
103
|
+
storiesOf('Button').addWithInfo(
|
104
|
+
'simple usage (disable source)',
|
105
|
+
'This is the basic usage of the button.',
|
106
|
+
() => <Button label="The Button" />,
|
107
|
+
{ source: false, inline: true }
|
108
|
+
);
|
109
|
+
```
|
110
|
+
|
111
|
+
Becomes
|
112
|
+
|
113
|
+
```js
|
114
|
+
storiesOf('Button').add(
|
115
|
+
'simple usage (disable source)',
|
116
|
+
withInfo({
|
117
|
+
text: 'This is the basic usage of the button.',
|
118
|
+
source: false,
|
119
|
+
inline: true,
|
120
|
+
})(() => <Button label="The Button" />)
|
121
|
+
);
|
122
|
+
```
|
123
|
+
|
124
|
+
### add-component-parameters
|
125
|
+
|
126
|
+
This tries to smartly adds "component" parameters to all your existing stories
|
127
|
+
for use in SB Docs.
|
128
|
+
|
129
|
+
```sh
|
130
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/add-component-parameters.js . --ignore-pattern "node_modules|dist"
|
131
|
+
```
|
132
|
+
|
133
|
+
For example:
|
134
|
+
|
135
|
+
```js
|
136
|
+
import { Button } from './Button';
|
137
|
+
storiesOf('Button', module).add('story', () => <Button label="The Button" />);
|
138
|
+
```
|
139
|
+
|
140
|
+
Becomes:
|
141
|
+
|
142
|
+
```js
|
143
|
+
import { Button } from './Button';
|
144
|
+
storiesOf('Button', module)
|
145
|
+
.addParameters({ component: Button })
|
146
|
+
.add('story', () => <Button label="The Button" />);
|
147
|
+
```
|
148
|
+
|
149
|
+
Heuristics:
|
150
|
+
|
151
|
+
- The storiesOf "kind" name must be Button
|
152
|
+
- Button must be imported in the file
|
153
|
+
|
154
|
+
### storiesof-to-csf
|
155
|
+
|
156
|
+
This converts all of your "old-style" `storiesOf` stories into Component Story Format (CSF), which uses standard ES6 modules.
|
157
|
+
|
158
|
+
> NOTE: The output of this transformation may require manual editing after running the transformation. `storiesOf` API allows multiple "kinds" (components) to be declared per file, but CSF only allows a single component per file. Therefore, if you use this feature in your input stories, you will need to split up the resulting outputs by hand. You'll see a warning at the console if you need to hand edit.
|
159
|
+
|
160
|
+
```sh
|
161
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/storiesof-to-csf.js . --ignore-pattern "node_modules|dist"
|
162
|
+
```
|
163
|
+
|
164
|
+
For example:
|
165
|
+
|
166
|
+
```js
|
167
|
+
storiesOf('Button', module)
|
168
|
+
.add('story', () => <Button label="Story 1" />)
|
169
|
+
.add('second story', () => <Button label="Story 2" onClick={action('click')} />)
|
170
|
+
.add('complex story', () => (
|
171
|
+
<div>
|
172
|
+
<Button label="The Button" onClick={action('onClick')} />
|
173
|
+
<br />
|
174
|
+
</div>
|
175
|
+
));
|
176
|
+
```
|
177
|
+
|
178
|
+
Becomes:
|
179
|
+
|
180
|
+
```js
|
181
|
+
export default {
|
182
|
+
title: 'Button',
|
183
|
+
};
|
184
|
+
|
185
|
+
export const story = () => <Button label="Story 1" />;
|
186
|
+
|
187
|
+
export const story2 = () => <Button label="Story 2" onClick={action('click')} />;
|
188
|
+
story2.story = { name: 'second story' };
|
189
|
+
|
190
|
+
export const story3 = () => (
|
191
|
+
<div>
|
192
|
+
<Button label="The Button" onClick={action('onClick')} />
|
193
|
+
<br />
|
194
|
+
</div>
|
195
|
+
);
|
196
|
+
story3.story = { name: 'complex story' };
|
197
|
+
```
|
198
|
+
|
199
|
+
Heuristics:
|
200
|
+
|
201
|
+
- If a file has any default export, it will be skipped
|
202
|
+
- If a file has multiple `storiesOf` declarations, it will convert each one separately. This generates invalid ES6, but you can edit the file by hand to split it into multiple files (or whatever is appropriate).
|
203
|
+
|
204
|
+
### upgrade-hierarchy-separators
|
205
|
+
|
206
|
+
Starting in 5.3, Storybook is moving to using a single path separator, `/`, to specify the story hierarchy. It previously defaulted to `|` for story "roots" (optional) and either `/` or `.` for denoting paths. This codemod updates the old default to the new default.
|
207
|
+
|
208
|
+
```sh
|
209
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/upgrade-hierarchy-separators.js . --ignore-pattern "node_modules|dist"
|
210
|
+
```
|
211
|
+
|
212
|
+
For example:
|
213
|
+
|
214
|
+
```js
|
215
|
+
storiesOf('Foo|Bar/baz');
|
216
|
+
storiesOf('Foo.Bar.baz');
|
217
|
+
|
218
|
+
export default {
|
219
|
+
title: 'Foo|Bar/baz.whatever',
|
220
|
+
};
|
221
|
+
```
|
222
|
+
|
223
|
+
Becomes:
|
224
|
+
|
225
|
+
```js
|
226
|
+
storiesOf('Foo/Bar/baz');
|
227
|
+
storiesOf('Foo/Bar/baz');
|
228
|
+
|
229
|
+
export default {
|
230
|
+
title: 'Foo/Bar/baz/whatever',
|
231
|
+
};
|
232
|
+
```
|
233
|
+
|
234
|
+
### csf-hoist-story-annotations
|
235
|
+
|
236
|
+
Starting in 6.0, Storybook has deprecated the `.story` annotation in CSF and is using hoisted annotations.
|
237
|
+
|
238
|
+
```sh
|
239
|
+
./node_modules/.bin/jscodeshift -t ./node_modules/@storybook/codemod/dist/transforms/csf-hoist-story-annotations.js . --ignore-pattern "node_modules|dist" --extensions=js
|
240
|
+
```
|
241
|
+
|
242
|
+
For example:
|
243
|
+
|
244
|
+
```js
|
245
|
+
export const Basic = () => <Button />
|
246
|
+
Basic.story = {
|
247
|
+
name: 'foo',
|
248
|
+
parameters: { ... },
|
249
|
+
decorators: [ ... ],
|
250
|
+
};
|
251
|
+
```
|
252
|
+
|
253
|
+
Becomes:
|
254
|
+
|
255
|
+
```js
|
256
|
+
export const Basic = () => <Button />
|
257
|
+
Basic.storyName = 'foo';
|
258
|
+
Basic.parameters = { ... };
|
259
|
+
Basic.decorators = [ ... ];
|
260
|
+
```
|
261
|
+
|
262
|
+
The new syntax is slightly more compact, is more ergonomic, and resembles React's `displayName`/`propTypes`/`defaultProps` annotations.
|
package/dist/index.d.ts
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
export { packageNames, default as updateOrganisationName } from './transforms/update-organisation-name.js';
|
2
|
+
export { default as updateAddonInfo } from './transforms/update-addon-info.js';
|
3
|
+
|
4
|
+
declare function listCodemods(): string[];
|
5
|
+
declare function runCodemod(codemod: any, { glob, logger, dryRun, rename, parser }: any): Promise<void>;
|
6
|
+
|
7
|
+
export { listCodemods, runCodemod };
|
package/dist/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{listCodemods:()=>listCodemods,packageNames:()=>packageNames,runCodemod:()=>runCodemod,updateAddonInfo:()=>transformer2,updateOrganisationName:()=>transformer});module.exports=__toCommonJS(src_exports);var import_fs=__toESM(require("fs")),import_path=__toESM(require("path")),import_util=require("util"),import_globby=__toESM(require("globby")),import_cross_spawn=require("cross-spawn");var import_camelCase=__toESM(require("lodash/camelCase.js")),import_upperFirst=__toESM(require("lodash/upperFirst.js"));function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}function transformer2(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return import_fs.default.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=(0,import_util.promisify)(import_fs.default.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=import_path.default.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await(0,import_globby.default)([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),files.length===0){logger.log(`=> No matching files for glob: ${glob}`);return}if(!dryRun&&files.length>0){let parserArgs=inferredParser?["--parser",inferredParser]:[];if((0,import_cross_spawn.sync)("node",[require.resolve("jscodeshift/bin/jscodeshift"),"--no-babel","--fail-on-error","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0}).status===1){logger.log("Skipped renaming because of errors.");return}}if(!renameParts&&codemod==="mdx-to-csf"&&(renameParts=[".stories.mdx",".mdx"],rename=".stories.mdx:.mdx;"),renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}0&&(module.exports={listCodemods,packageNames,runCodemod,updateAddonInfo,updateOrganisationName});
|
@@ -0,0 +1,22 @@
|
|
1
|
+
/**
|
2
|
+
* Adds a `component` parameter for each storiesOf(...) call.
|
3
|
+
*
|
4
|
+
* For example:
|
5
|
+
*
|
6
|
+
* input { Button } from './Button';
|
7
|
+
* storiesOf('Button', module).add('story', () => <Button label="The Button" />);
|
8
|
+
*
|
9
|
+
* Becomes:
|
10
|
+
*
|
11
|
+
* input { Button } from './Button';
|
12
|
+
* storiesOf('Button', module)
|
13
|
+
* .addParameters({ component: Button })
|
14
|
+
* .add('story', () => <Button label="The Button" />);
|
15
|
+
*
|
16
|
+
* Heuristics:
|
17
|
+
* - The storiesOf "kind" name must be Button
|
18
|
+
* - Button must be imported in the file
|
19
|
+
*/
|
20
|
+
declare function transformer(file: any, api: any): any;
|
21
|
+
|
22
|
+
export { transformer as default };
|
@@ -0,0 +1 @@
|
|
1
|
+
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var add_component_parameters_exports={};__export(add_component_parameters_exports,{default:()=>transformer});module.exports=__toCommonJS(add_component_parameters_exports);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),importMap={};root.find(j.ImportDeclaration).forEach(imp=>imp.node.specifiers.forEach(spec=>{importMap[spec.local.name]=!0}));function getLeafName(string){let parts=string.split(/\/|\.|\|/);return parts[parts.length-1]}function addComponentParameter(call){let{node}=call,leafName=getLeafName(node.arguments[0].value);return j.callExpression(j.memberExpression(node,j.identifier("addParameters")),[j.objectExpression([j.property("init",j.identifier("component"),j.identifier(leafName))])])}return root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type==="Literal").filter(call=>{let leafName=getLeafName(call.node.arguments[0].value);return importMap[leafName]}).replaceWith(addComponentParameter),root.toSource()}
|
@@ -0,0 +1,3 @@
|
|
1
|
+
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_2_to_3_exports={};__export(csf_2_to_3_exports,{default:()=>transform,parser:()=>parser});module.exports=__toCommonJS(csf_2_to_3_exports);var import_prettier2=__toESM(require("prettier")),t2=__toESM(require("@babel/types")),import_types=require("@babel/types"),import_csf_tools2=require("@storybook/csf-tools"),babel2=__toESM(require("@babel/core")),recast2=__toESM(require("recast"));var import_prettier=__toESM(require("prettier")),babel=__toESM(require("@babel/core")),import_csf_tools=require("@storybook/csf-tools"),recast=__toESM(require("recast")),t=__toESM(require("@babel/types"));var deprecatedTypes=["ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta","Story"];function migrateType(oldType){return oldType==="Story"||oldType==="ComponentStory"?"StoryFn":oldType.replace("Component","")}function upgradeDeprecatedTypes(file){let importedNamespaces=new Set,typeReferencesToUpdate=new Set,existingImports=[];file.path.traverse({ImportDeclaration:path=>{existingImports.push(...path.get("specifiers").map(specifier=>({name:specifier.node.local.name,isAlias:!(specifier.isImportSpecifier()&&t.isIdentifier(specifier.node.imported)&&specifier.node.local.name===specifier.node.imported.name),path:specifier}))),path.node.source.value.startsWith("@storybook")&&path.get("specifiers").forEach(specifier=>{if(specifier.isImportNamespaceSpecifier()&&importedNamespaces.add(specifier.node.local.name),!specifier.isImportSpecifier())return;let imported=specifier.get("imported");if(imported.isIdentifier()&&deprecatedTypes.includes(imported.node.name)){imported.node.name===specifier.node.local.name&&typeReferencesToUpdate.add(specifier.node.local.name);let newType=migrateType(imported.node.name);if(!existingImports.some(it=>it.name===newType))imported.replaceWith(t.identifier(newType)),existingImports.push({name:newType,isAlias:!1,path:specifier});else{let existingImport=existingImports.find(it=>it.name===newType&&it.isAlias);if(existingImport)throw existingImport.path.buildCodeFrameError(`This codemod does not support local imports that are called the same as a storybook import.
|
2
|
+
Rename this local import and try again.`);specifier.remove()}}})}}),file.path.traverse({TSTypeReference:path=>{let typeName=path.get("typeName");if(typeName.isIdentifier())typeReferencesToUpdate.has(typeName.node.name)&&typeName.replaceWith(t.identifier(migrateType(typeName.node.name)));else if(typeName.isTSQualifiedName()){let namespace=typeName.get("left");if(namespace.isIdentifier()&&importedNamespaces.has(namespace.node.name)){let right=typeName.get("right");deprecatedTypes.includes(right.node.name)&&right.replaceWith(t.identifier(migrateType(right.node.name)))}}}})}var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t2.isCallExpression(init)&&t2.isMemberExpression(init.callee)&&t2.isIdentifier(init.callee.object)&&t2.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t2.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t2.isExpressionStatement(stmt)&&t2.isAssignmentExpression(stmt.expression)&&t2.isMemberExpression(stmt.expression.left)&&t2.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],getNewExport=(stmt,objectExports)=>{if(t2.isExportNamedDeclaration(stmt)&&t2.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t2.isVariableDeclarator(decl)&&t2.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{var _a;if((_a=csf._meta)!=null&&_a.component&&t2.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t2.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t2.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t2.isJSXSpreadAttribute(attr)&&t2.isIdentifier(attr.argument)&&t2.isIdentifier(param)&¶m.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t2.isArrowFunctionExpression(init)&&init.params.length===0;function removeUnusedTemplates(csf){Object.entries(csf._templates).forEach(([template,templateExpression])=>{let references=[];if(babel2.traverse(csf._ast,{Identifier:path=>{path.node.name===template&&references.push(path)}}),references.length===1){let reference=references[0];reference.parentPath.isVariableDeclarator()&&reference.parentPath.node.init===templateExpression&&reference.parentPath.remove()}})}function transform(info,api,options){let makeTitle=userTitle=>userTitle||"FIXME",csf=(0,import_csf_tools2.loadCsf)(info.source,{makeTitle});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),info.source}let file=new babel2.File({filename:info.path},{code:info.source,ast:csf._ast}),importHelper=new StorybookImportHelper(file,info),objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t2.objectProperty(t2.identifier(renameAnnotation(annotation)),val));if(t2.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t2.isArrowFunctionExpression(init)&&!template)return;if(isSimpleCSFStory(init,annotations)){objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryFn"),init)]));return}let storyFn=template&&t2.identifier(template);storyFn||(storyFn=init);let renderAnnotation=isReactGlobalRenderFn(csf,template?csf._templates[template]:storyFn)?[]:[t2.objectProperty(t2.identifier("render"),storyFn)];objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryObj"),t2.objectExpression([...renderAnnotation,...annotations]))]))}}),csf._ast.program.body=csf._ast.program.body.reduce((acc,stmt)=>{let statement=stmt;if(isStoryAnnotation(statement,objectExports))return acc;let newExport=getNewExport(statement,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(statement),acc)},[]),upgradeDeprecatedTypes(file),importHelper.removeDeprecatedStoryImport(),removeUnusedTemplates(csf);let output=recast2.print(csf._ast,{}).code;try{let prettierConfig=import_prettier2.default.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=import_prettier2.default.format(output,{...prettierConfig,filepath:info.path})}catch{logger.log(`Failed applying prettier to ${info.path}.`)}return output}var StorybookImportHelper=class{constructor(file,info){this.getAllSbImportDeclarations=file=>{let found=[];return file.path.traverse({ImportDeclaration:path=>{let source=path.node.source.value;if(source.startsWith("@storybook/csf")||!source.startsWith("@storybook"))return;path.get("specifiers").some(specifier=>{if(specifier.isImportNamespaceSpecifier())throw new Error(`This codemod does not support namespace imports for a ${path.node.source.value} package.
|
3
|
+
Replace the namespace import with named imports and try again.`);if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return imported.isIdentifier()?["Story","StoryFn","StoryObj","Meta","ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta"].includes(imported.node.name):!1})&&found.push(path)}}),found};this.getOrAddImport=type=>{let sbImport=this.sbImportDeclarations.find(path=>path.node.importKind==="type")??this.sbImportDeclarations[0];if(sbImport==null)return;let specifiers=sbImport.get("specifiers"),importSpecifier2=specifiers.find(specifier=>{if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return imported.isIdentifier()?imported.node.name===type:!1});return importSpecifier2?importSpecifier2.node.local.name:(specifiers[0].insertBefore(t2.importSpecifier(t2.identifier(type),t2.identifier(type))),type)};this.removeDeprecatedStoryImport=()=>{this.sbImportDeclarations.flatMap(it=>it.get("specifiers")).filter(specifier=>{if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return imported.isIdentifier()?imported.node.name==="Story":!1}).forEach(path=>path.remove())};this.getAllLocalImports=()=>this.sbImportDeclarations.flatMap(it=>it.get("specifiers")).map(it=>it.node.local.name);this.updateTypeTo=(id,type)=>{if((0,import_types.isIdentifier)(id)&&(0,import_types.isTSTypeAnnotation)(id.typeAnnotation)&&(0,import_types.isTSTypeReference)(id.typeAnnotation.typeAnnotation)&&(0,import_types.isIdentifier)(id.typeAnnotation.typeAnnotation.typeName)){let{name}=id.typeAnnotation.typeAnnotation.typeName;if(this.getAllLocalImports().includes(name)){let localTypeImport=this.getOrAddImport(type);return{...id,typeAnnotation:t2.tsTypeAnnotation(t2.tsTypeReference(t2.identifier(localTypeImport),id.typeAnnotation.typeAnnotation.typeParameters))}}}return id};this.sbImportDeclarations=this.getAllSbImportDeclarations(file)}},parser="tsx";0&&(module.exports={parser});
|
@@ -0,0 +1,26 @@
|
|
1
|
+
/**
|
2
|
+
* Hoist CSF .story annotations
|
3
|
+
*
|
4
|
+
* For example:
|
5
|
+
*
|
6
|
+
* ```
|
7
|
+
* export const Basic = () => <Button />
|
8
|
+
* Basic.story = {
|
9
|
+
* name: 'foo',
|
10
|
+
* parameters: { ... },
|
11
|
+
* decorators = [ ... ],
|
12
|
+
* };
|
13
|
+
* ```
|
14
|
+
*
|
15
|
+
* Becomes:
|
16
|
+
*
|
17
|
+
* ```
|
18
|
+
* export const Basic = () => <Button />
|
19
|
+
* Basic.storyName = 'foo';
|
20
|
+
* Basic.parameters = { ... };
|
21
|
+
* Basic.decorators = [ ... ];
|
22
|
+
* ```
|
23
|
+
*/
|
24
|
+
declare function transformer(file: any, api: any): any;
|
25
|
+
|
26
|
+
export { transformer as default };
|
@@ -0,0 +1 @@
|
|
1
|
+
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_hoist_story_annotations_exports={};__export(csf_hoist_story_annotations_exports,{default:()=>transformer});module.exports=__toCommonJS(csf_hoist_story_annotations_exports);var getContainingStatement=n=>n.node.type.endsWith("Statement")?n:getContainingStatement(n.parent);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),renameKey=exp=>exp.type==="Identifier"&&exp.name==="name"?j.identifier("storyName"):exp;if(root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.type==="ObjectExpression"&&def.node.declaration.properties.map(p=>p.key.name).includes("title")).size()===0)return root.toSource();let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left,right}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.property.type==="Identifier"&&left.property.name==="story"&&right.type==="ObjectExpression"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;right.properties.forEach(prop=>{getContainingStatement(exp).insertBefore(j.assignmentStatement("=",j.memberExpression(left.object,renameKey(prop.key)),prop.value))})}),storyAssignments.remove(),root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.property.type==="Identifier"&&left.object.property.name==="story"&&left.property.type==="Identifier"}).replaceWith(exp=>{let{left,right}=exp.node;return j.assignmentExpression("=",j.memberExpression(left.object.object,renameKey(left.property)),right)}),root.toSource({quote:"single"})}
|
@@ -0,0 +1,7 @@
|
|
1
|
+
import { FileInfo } from 'jscodeshift';
|
2
|
+
|
3
|
+
declare function jscodeshift(info: FileInfo): string;
|
4
|
+
declare function transform(source: string, baseName: string): [mdx: string, csf: string];
|
5
|
+
declare function nameToValidExport(name: string): string;
|
6
|
+
|
7
|
+
export { jscodeshift as default, nameToValidExport, transform };
|