@storybook/codemod 6.4.0-beta.20 → 6.4.0-beta.24

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.
Files changed (41) hide show
  1. package/package.json +4 -4
  2. package/dist/cjs/index.js +0 -142
  3. package/dist/cjs/lib/utils.js +0 -40
  4. package/dist/cjs/transforms/add-component-parameters.js +0 -64
  5. package/dist/cjs/transforms/csf-2-to-3.js +0 -169
  6. package/dist/cjs/transforms/csf-hoist-story-annotations.js +0 -93
  7. package/dist/cjs/transforms/csf-to-mdx.js +0 -196
  8. package/dist/cjs/transforms/mdx-to-csf.js +0 -153
  9. package/dist/cjs/transforms/move-builtin-addons.js +0 -57
  10. package/dist/cjs/transforms/storiesof-to-csf.js +0 -300
  11. package/dist/cjs/transforms/update-addon-info.js +0 -101
  12. package/dist/cjs/transforms/update-organisation-name.js +0 -83
  13. package/dist/cjs/transforms/upgrade-hierarchy-separators.js +0 -42
  14. package/dist/esm/index.js +0 -99
  15. package/dist/esm/lib/utils.js +0 -25
  16. package/dist/esm/transforms/add-component-parameters.js +0 -57
  17. package/dist/esm/transforms/csf-2-to-3.js +0 -152
  18. package/dist/esm/transforms/csf-hoist-story-annotations.js +0 -86
  19. package/dist/esm/transforms/csf-to-mdx.js +0 -188
  20. package/dist/esm/transforms/mdx-to-csf.js +0 -139
  21. package/dist/esm/transforms/move-builtin-addons.js +0 -50
  22. package/dist/esm/transforms/storiesof-to-csf.js +0 -287
  23. package/dist/esm/transforms/update-addon-info.js +0 -94
  24. package/dist/esm/transforms/update-organisation-name.js +0 -74
  25. package/dist/esm/transforms/upgrade-hierarchy-separators.js +0 -35
  26. package/dist/modern/index.js +0 -99
  27. package/dist/modern/lib/utils.js +0 -25
  28. package/dist/modern/transforms/add-component-parameters.js +0 -57
  29. package/dist/modern/transforms/csf-2-to-3.js +0 -152
  30. package/dist/modern/transforms/csf-hoist-story-annotations.js +0 -86
  31. package/dist/modern/transforms/csf-to-mdx.js +0 -188
  32. package/dist/modern/transforms/mdx-to-csf.js +0 -139
  33. package/dist/modern/transforms/move-builtin-addons.js +0 -50
  34. package/dist/modern/transforms/storiesof-to-csf.js +0 -287
  35. package/dist/modern/transforms/update-addon-info.js +0 -94
  36. package/dist/modern/transforms/update-organisation-name.js +0 -74
  37. package/dist/modern/transforms/upgrade-hierarchy-separators.js +0 -35
  38. package/dist/ts3.4/lib/utils.d.ts +0 -2
  39. package/dist/ts3.4/transforms/csf-2-to-3.d.ts +0 -6
  40. package/dist/ts3.9/lib/utils.d.ts +0 -2
  41. package/dist/ts3.9/transforms/csf-2-to-3.d.ts +0 -6
@@ -1,287 +0,0 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
2
-
3
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
4
-
5
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
- import prettier from 'prettier';
8
- import { logger } from '@storybook/node-logger';
9
- import { storyNameFromExport } from '@storybook/csf';
10
- import { sanitizeName, jscodeshiftToPrettierParser } from '../lib/utils';
11
- /**
12
- * Convert a legacy story API to component story format
13
- *
14
- * For example:
15
- *
16
- * ```
17
- * input { Button } from './Button';
18
- * storiesOf('Button', module).add('story', () => <Button label="The Button" />);
19
- * ```
20
- *
21
- * Becomes:
22
- *
23
- * ```
24
- * input { Button } from './Button';
25
- * export default {
26
- * title: 'Button'
27
- * }
28
- * export const story = () => <Button label="The Button" />;
29
- *
30
- * NOTES: only support chained storiesOf() calls
31
- */
32
-
33
- export default function transformer(file, api, options) {
34
- var LITERAL = ['ts', 'tsx'].includes(options.parser) ? 'StringLiteral' : 'Literal';
35
- var j = api.jscodeshift;
36
- var root = j(file.source);
37
-
38
- function extractDecorators(parameters) {
39
- if (!parameters) {
40
- return {};
41
- }
42
-
43
- if (!parameters.properties) {
44
- return {
45
- storyParams: parameters
46
- };
47
- }
48
-
49
- var storyDecorators = parameters.properties.find(function (p) {
50
- return p.key.name === 'decorators';
51
- });
52
-
53
- if (!storyDecorators) {
54
- return {
55
- storyParams: parameters
56
- };
57
- }
58
-
59
- storyDecorators = storyDecorators.value;
60
-
61
- var storyParams = _objectSpread({}, parameters);
62
-
63
- storyParams.properties = storyParams.properties.filter(function (p) {
64
- return p.key.name !== 'decorators';
65
- });
66
-
67
- if (storyParams.properties.length === 0) {
68
- return {
69
- storyDecorators: storyDecorators
70
- };
71
- }
72
-
73
- return {
74
- storyParams: storyParams,
75
- storyDecorators: storyDecorators
76
- };
77
- }
78
-
79
- function convertToModuleExports(path, originalExports) {
80
- var base = j(path);
81
- var statements = [];
82
- var extraExports = []; // .addDecorator
83
-
84
- var decorators = [];
85
- base.find(j.CallExpression).filter(function (call) {
86
- return call.node.callee.property && call.node.callee.property.name === 'addDecorator';
87
- }).forEach(function (add) {
88
- var decorator = add.node.arguments[0];
89
- decorators.push(decorator);
90
- });
91
-
92
- if (decorators.length > 0) {
93
- decorators.reverse();
94
- extraExports.push(j.property('init', j.identifier('decorators'), j.arrayExpression(decorators)));
95
- } // .addParameters
96
-
97
-
98
- var parameters = [];
99
- base.find(j.CallExpression).filter(function (call) {
100
- return call.node.callee.property && call.node.callee.property.name === 'addParameters';
101
- }).forEach(function (add) {
102
- // jscodeshift gives us the find results in reverse, but these args come in
103
- // order, so we double reverse here. ugh.
104
- var params = [...add.node.arguments[0].properties];
105
- params.reverse();
106
- params.forEach(function (prop) {
107
- return parameters.push(prop);
108
- });
109
- });
110
-
111
- if (parameters.length > 0) {
112
- parameters.reverse();
113
- extraExports.push(j.property('init', j.identifier('parameters'), j.objectExpression(parameters)));
114
- }
115
-
116
- if (originalExports.length > 0) {
117
- extraExports.push(j.property('init', j.identifier('excludeStories'), j.arrayExpression(originalExports.map(function (exp) {
118
- return j.literal(exp);
119
- }))));
120
- } // storiesOf(...)
121
-
122
-
123
- base.find(j.CallExpression).filter(function (call) {
124
- return call.node.callee.name === 'storiesOf';
125
- }).filter(function (call) {
126
- return call.node.arguments.length > 0 && call.node.arguments[0].type === LITERAL;
127
- }).forEach(function (storiesOf) {
128
- var title = storiesOf.node.arguments[0].value;
129
- statements.push(j.exportDefaultDeclaration(j.objectExpression([j.property('init', j.identifier('title'), j.literal(title)), ...extraExports])));
130
- }); // .add(...)
131
-
132
- var adds = [];
133
- base.find(j.CallExpression).filter(function (add) {
134
- return add.node.callee.property && add.node.callee.property.name === 'add';
135
- }).filter(function (add) {
136
- return add.node.arguments.length >= 2 && add.node.arguments[0].type === LITERAL;
137
- }).forEach(function (add) {
138
- return adds.push(add);
139
- });
140
- adds.reverse();
141
- adds.push(path);
142
- var identifiers = new Set();
143
- root.find(j.Identifier).forEach(function ({
144
- value: value
145
- }) {
146
- return identifiers.add(value.name);
147
- });
148
- adds.forEach(function (add) {
149
- var name = add.node.arguments[0].value;
150
- var key = sanitizeName(name);
151
-
152
- while (identifiers.has(key)) {
153
- key = `_${key}`;
154
- }
155
-
156
- identifiers.add(key);
157
-
158
- if (storyNameFromExport(key) === name) {
159
- name = null;
160
- }
161
-
162
- var val = add.node.arguments[1];
163
- statements.push(j.exportDeclaration(false, j.variableDeclaration('const', [j.variableDeclarator(j.identifier(key), val)])));
164
- var storyAnnotations = [];
165
-
166
- if (name) {
167
- storyAnnotations.push(j.property('init', j.identifier('name'), j.literal(name)));
168
- }
169
-
170
- if (add.node.arguments.length > 2) {
171
- var originalStoryParams = add.node.arguments[2];
172
-
173
- var _extractDecorators = extractDecorators(originalStoryParams),
174
- storyParams = _extractDecorators.storyParams,
175
- storyDecorators = _extractDecorators.storyDecorators;
176
-
177
- if (storyParams) {
178
- storyAnnotations.push(j.property('init', j.identifier('parameters'), storyParams));
179
- }
180
-
181
- if (storyDecorators) {
182
- storyAnnotations.push(j.property('init', j.identifier('decorators'), storyDecorators));
183
- }
184
- }
185
-
186
- if (storyAnnotations.length > 0) {
187
- statements.push(j.assignmentStatement('=', j.memberExpression(j.identifier(key), j.identifier('story')), j.objectExpression(storyAnnotations)));
188
- }
189
- });
190
- var stmt = path.parent.node.type === 'VariableDeclarator' ? path.parent.parent : path.parent;
191
- statements.reverse();
192
- statements.forEach(function (s) {
193
- return stmt.insertAfter(s);
194
- });
195
- j(stmt).remove();
196
- } // Save the original storiesOf
197
-
198
-
199
- var initialStoriesOf = root.find(j.CallExpression).filter(function (call) {
200
- return call.node.callee.name === 'storiesOf';
201
- });
202
- var defaultExports = root.find(j.ExportDefaultDeclaration); // If there's already a default export
203
-
204
- if (defaultExports.size() > 0) {
205
- if (initialStoriesOf.size() > 0) {
206
- logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls but existing default export, SKIPPING: '${file.path}'`);
207
- }
208
-
209
- return root.toSource();
210
- } // Exclude all the original named exports
211
-
212
-
213
- var originalExports = [];
214
- root.find(j.ExportNamedDeclaration).forEach(function (exp) {
215
- var _exp$node = exp.node,
216
- declaration = _exp$node.declaration,
217
- specifiers = _exp$node.specifiers;
218
-
219
- if (declaration) {
220
- var id = declaration.id,
221
- declarations = declaration.declarations;
222
-
223
- if (declarations) {
224
- declarations.forEach(function (decl) {
225
- var _decl$id = decl.id,
226
- name = _decl$id.name,
227
- properties = _decl$id.properties;
228
-
229
- if (name) {
230
- originalExports.push(name);
231
- } else if (properties) {
232
- properties.forEach(function (prop) {
233
- return originalExports.push(prop.key.name);
234
- });
235
- }
236
- });
237
- } else if (id) {
238
- originalExports.push(id.name);
239
- }
240
- } else if (specifiers) {
241
- specifiers.forEach(function (spec) {
242
- return originalExports.push(spec.exported.name);
243
- });
244
- }
245
- }); // each top-level add expression corresponds to the last "add" of the chain.
246
- // replace it with the entire export statements
247
-
248
- root.find(j.CallExpression).filter(function (add) {
249
- return add.node.callee.property && add.node.callee.property.name === 'add';
250
- }).filter(function (add) {
251
- return add.node.arguments.length >= 2 && add.node.arguments[0].type === LITERAL;
252
- }).filter(function (add) {
253
- return ['ExpressionStatement', 'VariableDeclarator'].includes(add.parentPath.node.type);
254
- }).forEach(function (path) {
255
- return convertToModuleExports(path, originalExports);
256
- }); // remove storiesOf import
257
-
258
- root.find(j.ImportSpecifier).filter(function (spec) {
259
- return spec.node.imported.name === 'storiesOf' && spec.parent.node.source.value.startsWith('@storybook/');
260
- }).forEach(function (spec) {
261
- var toRemove = spec.parent.node.specifiers.length > 1 ? spec : spec.parent;
262
- j(toRemove).remove();
263
- });
264
- var source = root.toSource({
265
- trailingComma: true,
266
- quote: 'single',
267
- tabWidth: 2
268
- });
269
-
270
- if (initialStoriesOf.size() > 1) {
271
- logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`);
272
- return source;
273
- }
274
-
275
- var prettierConfig = prettier.resolveConfig.sync('.', {
276
- editorconfig: true
277
- }) || {
278
- printWidth: 100,
279
- tabWidth: 2,
280
- bracketSpacing: true,
281
- trailingComma: 'es5',
282
- singleQuote: true
283
- };
284
- return prettier.format(source, _objectSpread(_objectSpread({}, prettierConfig), {}, {
285
- parser: jscodeshiftToPrettierParser(options.parser) || 'babel'
286
- }));
287
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Takes the deprecated addon-info API, addWithInfo, and
3
- * converts to the new withInfo API.
4
- *
5
- * Example of deprecated addWithInfo API:
6
- *
7
- * storiesOf('Button')
8
- * .addWithInfo(
9
- * 'story name',
10
- * 'Story description.',
11
- * () => (
12
- * <Button label="The Button" />
13
- * )
14
- * )
15
- *
16
- * Converts to the new withInfo API:
17
- *
18
- * storiesOf('Button')
19
- * .add('story name', withInfo(
20
- * 'Story description.'
21
- * )(() => (
22
- * <Button label="The Button" />
23
- * )))
24
- */
25
- export default function transformer(file, api) {
26
- var j = api.jscodeshift;
27
- var root = j(file.source);
28
- /**
29
- * Returns a list of parameters for the withInfo function. The contents
30
- * of this list is either the second argument from the original
31
- * addWithInfo function, if no additional options were used, or a
32
- * combined object of all the options from the original function.
33
- * @param {list} args - original addWithInfo function parameters
34
- * @return {list} the modified list of parameters for the new function
35
- */
36
-
37
- var getOptions = function (args) {
38
- if (args[3] === undefined) {
39
- if (args[2] === undefined) {
40
- // when the optional description string is not supplied for addWithInfo, use story name
41
- return [args[0]];
42
- }
43
-
44
- return [args[1]];
45
- }
46
-
47
- return [j.objectExpression([j.property('init', j.identifier('text'), args[1]), ...args[3].properties])];
48
- };
49
- /**
50
- * Constructs the new withInfo function from the parameters of the
51
- * original addWithInfo function.
52
- * @param {CallExpression} addWithInfoExpression - original function
53
- * @returns {CallExpression} the new withInfo function
54
- */
55
-
56
-
57
- var withInfo = function (addWithInfoExpression) {
58
- var node = addWithInfoExpression.node;
59
- var args = node.arguments; // if optional description string is not supplied, the story component becomes second arg
60
-
61
- var storyComponent = args[2] ? args[2] : args[1];
62
- node.callee.property.name = 'add';
63
- node.arguments = [args[0], j.callExpression(j.callExpression(j.identifier('withInfo'), getOptions(args)), [storyComponent])];
64
- return node;
65
- };
66
- /**
67
- * Checks for - import { withInfo } from "@storybook/addon-info";
68
- * Adds the import if necessary.
69
- */
70
-
71
-
72
- var checkWithInfoImport = function () {
73
- var importExists = root.find(j.ImportDeclaration).filter(function (imp) {
74
- return imp.node.source.value === '@storybook/addon-info';
75
- }).size();
76
- if (importExists) return;
77
- root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier('withInfo'))], j.literal('@storybook/addon-info')));
78
- };
79
-
80
- var addWithInfoExpressions = root.find(j.CallExpression, {
81
- callee: {
82
- property: {
83
- name: 'addWithInfo'
84
- }
85
- }
86
- });
87
-
88
- if (addWithInfoExpressions.size()) {
89
- checkWithInfoImport();
90
- addWithInfoExpressions.replaceWith(withInfo);
91
- }
92
-
93
- return root.toSource();
94
- }
@@ -1,74 +0,0 @@
1
- export var packageNames = {
2
- '@kadira/react-storybook-decorator-centered': '@storybook/addon-centered',
3
- '@kadira/storybook-addons': '@storybook/addons',
4
- '@kadira/storybook-addon-actions': '@storybook/addon-actions',
5
- '@kadira/storybook-addon-comments': '@storybook/addon-comments',
6
- '@kadira/storybook-addon-graphql': '@storybook/addon-graphql',
7
- '@kadira/storybook-addon-info': '@storybook/addon-info',
8
- '@kadira/storybook-addon-knobs': '@storybook/addon-knobs',
9
- '@kadira/storybook-addon-links': '@storybook/addon-links',
10
- '@kadira/storybook-addon-notes': '@storybook/addon-notes',
11
- '@kadira/storybook-addon-options': '@storybook/addon-options',
12
- '@kadira/storybook-channels': '@storybook/channels',
13
- '@kadira/storybook-channel-postmsg': '@storybook/channel-postmessage',
14
- '@kadira/storybook-channel-websocket': '@storybook/channel-websocket',
15
- '@kadira/storybook-ui': '@storybook/ui',
16
- '@kadira/react-native-storybook': '@storybook/react-native',
17
- '@kadira/react-storybook': '@storybook/react',
18
- '@kadira/getstorybook': '@storybook/cli',
19
- '@kadira/storybook': '@storybook/react',
20
- storyshots: '@storybook/addon-storyshots',
21
- getstorybook: '@storybook/cli'
22
- };
23
- export default function transformer(file, api) {
24
- var j = api.jscodeshift;
25
- var packageNamesKeys = Object.keys(packageNames);
26
- /**
27
- * Checks whether the node value matches a Storybook package
28
- * @param {string} the import declaration node
29
- * @returns {string} whether the node value matches a Storybook package
30
- */
31
-
32
- var getMatch = function (oldpart) {
33
- return packageNamesKeys.find(function (newpart) {
34
- return oldpart.match(newpart);
35
- });
36
- };
37
- /**
38
- * Returns the name of the Storybook packages with the organisation name,
39
- * replacing the old `@kadira/` prefix.
40
- * @param {string} oldPackageName the name of the old package
41
- * @return {string} the new package name
42
- * @example
43
- * // returns '@storybook/storybook'
44
- * getNewPackageName('@kadira/storybook')
45
- */
46
-
47
-
48
- var getNewPackageName = function (oldPackageName) {
49
- var match = getMatch(oldPackageName);
50
-
51
- if (match) {
52
- var replacement = packageNames[match];
53
- return oldPackageName.replace(match, replacement);
54
- }
55
-
56
- return oldPackageName;
57
- };
58
- /**
59
- * updatePackageName - updates the source name of the Storybook packages
60
- * @param {ImportDeclaration} declaration the import declaration
61
- * @returns {ImportDeclaration.Node} the import declaration node
62
- */
63
-
64
-
65
- var updatePackageName = function (declaration) {
66
- // eslint-disable-next-line no-param-reassign
67
- declaration.node.source.value = getNewPackageName(declaration.node.source.value);
68
- return declaration.node;
69
- };
70
-
71
- return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({
72
- quote: 'single'
73
- });
74
- }
@@ -1,35 +0,0 @@
1
- function upgradeSeparator(path) {
2
- return path.replace(/[|.]/g, '/');
3
- }
4
-
5
- export default function transformer(file, api, options) {
6
- var j = api.jscodeshift;
7
- var root = j(file.source); // storiesOf(...)
8
-
9
- root.find(j.CallExpression).filter(function (call) {
10
- return call.node.callee.name === 'storiesOf';
11
- }).filter(function (call) {
12
- return call.node.arguments.length > 0 && ['Literal', 'StringLiteral'].includes(call.node.arguments[0].type);
13
- }).forEach(function (call) {
14
- var arg0 = call.node.arguments[0];
15
- arg0.value = upgradeSeparator(arg0.value);
16
- }); // export default { title: ... }
17
-
18
- root.find(j.ExportDefaultDeclaration).filter(function (def) {
19
- return def.node.declaration.properties.map(function (p) {
20
- return p.key.name;
21
- }).includes('title');
22
- }).forEach(function (def) {
23
- if (def.node.declaration && def.node.declaration.properties) {
24
- def.node.declaration.properties.forEach(function (p) {
25
- if (p.key.name === 'title') {
26
- // eslint-disable-next-line no-param-reassign
27
- p.value.value = upgradeSeparator(p.value.value);
28
- }
29
- });
30
- }
31
- });
32
- return root.toSource({
33
- quote: 'single'
34
- });
35
- }
@@ -1,99 +0,0 @@
1
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
-
3
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
-
5
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
6
-
7
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
8
-
9
- function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
10
-
11
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
12
-
13
- import "core-js/modules/es.promise.js";
14
- import "core-js/modules/es.symbol.description.js";
15
-
16
- /* eslint import/prefer-default-export: "off" */
17
- import fs from 'fs';
18
- import path from 'path';
19
- import { promisify } from 'util';
20
- import globby from 'globby';
21
- import { sync as spawnSync } from 'cross-spawn';
22
- import { jscodeshiftToPrettierParser } from './lib/utils';
23
- export { default as updateOrganisationName, packageNames } from './transforms/update-organisation-name';
24
- export { default as updateAddonInfo } from './transforms/update-addon-info';
25
- var TRANSFORM_DIR = `${__dirname}/transforms`;
26
- export function listCodemods() {
27
- return fs.readdirSync(TRANSFORM_DIR).filter(function (fname) {
28
- return fname.endsWith('.js');
29
- }).map(function (fname) {
30
- return fname.slice(0, -3);
31
- });
32
- }
33
- var renameAsync = promisify(fs.rename);
34
-
35
- async function renameFile(file, from, to, {
36
- logger: logger
37
- }) {
38
- var newFile = file.replace(from, to);
39
- logger.log(`Rename: ${file} ${newFile}`);
40
- return renameAsync(file, newFile);
41
- }
42
-
43
- export async function runCodemod(codemod, {
44
- glob: glob,
45
- logger: logger,
46
- dryRun: dryRun,
47
- rename: rename,
48
- parser: parser
49
- }) {
50
- var codemods = listCodemods();
51
-
52
- if (!codemods.includes(codemod)) {
53
- throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);
54
- }
55
-
56
- var renameParts = null;
57
-
58
- if (rename) {
59
- renameParts = rename.split(':');
60
-
61
- if (renameParts.length !== 2) {
62
- throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);
63
- }
64
- } // jscodeshift/prettier know how to handle .ts/.tsx extensions,
65
- // so if the user uses one of those globs, we can auto-infer
66
-
67
-
68
- var inferredParser = parser;
69
-
70
- if (!parser) {
71
- var extension = path.extname(glob).slice(1);
72
- var knownParser = jscodeshiftToPrettierParser(extension);
73
- if (knownParser !== 'babel') inferredParser = extension;
74
- }
75
-
76
- var files = await globby([glob, '!**/node_modules', '!**/dist']);
77
- logger.log(`=> Applying ${codemod}: ${files.length} files`);
78
-
79
- if (!dryRun) {
80
- var parserArgs = inferredParser ? ['--parser', inferredParser] : [];
81
- spawnSync('npx', ['jscodeshift', '-t', `${TRANSFORM_DIR}/${codemod}.js`, ...parserArgs, ...files], {
82
- stdio: 'inherit'
83
- });
84
- }
85
-
86
- if (renameParts) {
87
- var _renameParts = renameParts,
88
- _renameParts2 = _slicedToArray(_renameParts, 2),
89
- from = _renameParts2[0],
90
- to = _renameParts2[1];
91
-
92
- logger.log(`=> Renaming ${rename}: ${files.length} files`);
93
- await Promise.all(files.map(function (file) {
94
- return renameFile(file, new RegExp(`${from}$`), to, {
95
- logger: logger
96
- });
97
- }));
98
- }
99
- }
@@ -1,25 +0,0 @@
1
- import camelCase from 'lodash/camelCase';
2
- import upperFirst from 'lodash/upperFirst';
3
- export var sanitizeName = function (name) {
4
- var key = upperFirst(camelCase(name)); // prepend _ if name starts with a digit
5
-
6
- if (/^\d/.test(key)) {
7
- key = `_${key}`;
8
- } // prepend _ if name starts with a digit
9
-
10
-
11
- if (/^\d/.test(key)) {
12
- key = `_${key}`;
13
- }
14
-
15
- return key;
16
- };
17
- export function jscodeshiftToPrettierParser(parser) {
18
- var parserMap = {
19
- babylon: 'babel',
20
- flow: 'flow',
21
- ts: 'typescript',
22
- tsx: 'typescript'
23
- };
24
- return parserMap[parser] || 'babel';
25
- }
@@ -1,57 +0,0 @@
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
- export default function transformer(file, api) {
21
- var j = api.jscodeshift;
22
- var root = j(file.source); // Create a dictionary whose keys are all the named imports in the file.
23
- // For instance:
24
- //
25
- // import foo from 'foo';
26
- // import { bar, baz } from 'zoo';
27
- //
28
- // => { foo: true, bar: true, baz: true }
29
-
30
- var importMap = {};
31
- root.find(j.ImportDeclaration).forEach(function (imp) {
32
- return imp.node.specifiers.forEach(function (spec) {
33
- importMap[spec.local.name] = true;
34
- });
35
- });
36
-
37
- function getLeafName(string) {
38
- var parts = string.split(/\/|\.|\|/);
39
- return parts[parts.length - 1];
40
- }
41
-
42
- function addComponentParameter(call) {
43
- var node = call.node;
44
- var leafName = getLeafName(node.arguments[0].value);
45
- return j.callExpression(j.memberExpression(node, j.identifier('addParameters')), [j.objectExpression([j.property('init', j.identifier('component'), j.identifier(leafName))])]);
46
- }
47
-
48
- var storiesOfCalls = root.find(j.CallExpression).filter(function (call) {
49
- return call.node.callee.name === 'storiesOf';
50
- }).filter(function (call) {
51
- return call.node.arguments.length > 0 && call.node.arguments[0].type === 'Literal';
52
- }).filter(function (call) {
53
- var leafName = getLeafName(call.node.arguments[0].value);
54
- return importMap[leafName];
55
- }).replaceWith(addComponentParameter);
56
- return root.toSource();
57
- }