@storybook/codemod 7.0.0-alpha.37 → 7.0.0-alpha.39

Sign up to get free protection for your applications and to get access to all the features.
Files changed (131) hide show
  1. package/dist/index.d.ts +261 -0
  2. package/dist/index.js +1 -0
  3. package/dist/index.mjs +1 -0
  4. package/package.json +24 -15
  5. package/src/index.js +77 -0
  6. package/src/lib/utils.test.js +9 -0
  7. package/{dist/esm/lib/utils.js → src/lib/utils.ts} +10 -11
  8. package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.input.js +44 -0
  9. package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.output.snapshot +68 -0
  10. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.input.js +25 -0
  11. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.output.snapshot +27 -0
  12. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.input.js +25 -0
  13. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.output.snapshot +28 -0
  14. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.input.js +13 -0
  15. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.output.snapshot +17 -0
  16. package/src/transforms/__testfixtures__/csf-to-mdx/basic.input.js +20 -0
  17. package/src/transforms/__testfixtures__/csf-to-mdx/basic.output.snapshot +18 -0
  18. package/src/transforms/__testfixtures__/csf-to-mdx/component-id.input.js +9 -0
  19. package/src/transforms/__testfixtures__/csf-to-mdx/component-id.output.snapshot +10 -0
  20. package/src/transforms/__testfixtures__/csf-to-mdx/decorators.input.js +13 -0
  21. package/src/transforms/__testfixtures__/csf-to-mdx/decorators.output.snapshot +12 -0
  22. package/src/transforms/__testfixtures__/csf-to-mdx/exclude-stories.input.js +23 -0
  23. package/src/transforms/__testfixtures__/csf-to-mdx/exclude-stories.output.snapshot +22 -0
  24. package/src/transforms/__testfixtures__/csf-to-mdx/parameters.input.js +16 -0
  25. package/src/transforms/__testfixtures__/csf-to-mdx/parameters.output.snapshot +17 -0
  26. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.input.js +19 -0
  27. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.output.snapshot +18 -0
  28. package/src/transforms/__testfixtures__/csf-to-mdx/story-parameters.input.js +24 -0
  29. package/src/transforms/__testfixtures__/csf-to-mdx/story-parameters.output.snapshot +22 -0
  30. package/src/transforms/__testfixtures__/mdx-to-csf/basic.input.js +18 -0
  31. package/src/transforms/__testfixtures__/mdx-to-csf/basic.output.snapshot +40 -0
  32. package/src/transforms/__testfixtures__/mdx-to-csf/component-id.input.js +6 -0
  33. package/src/transforms/__testfixtures__/mdx-to-csf/component-id.output.snapshot +17 -0
  34. package/src/transforms/__testfixtures__/mdx-to-csf/decorators.input.js +8 -0
  35. package/src/transforms/__testfixtures__/mdx-to-csf/decorators.output.snapshot +18 -0
  36. package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.input.js +19 -0
  37. package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.output.snapshot +39 -0
  38. package/src/transforms/__testfixtures__/mdx-to-csf/parameters.input.js +14 -0
  39. package/src/transforms/__testfixtures__/mdx-to-csf/parameters.output.snapshot +23 -0
  40. package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.input.js +3 -0
  41. package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.output.snapshot +11 -0
  42. package/src/transforms/__testfixtures__/mdx-to-csf/story-function.input.js +10 -0
  43. package/src/transforms/__testfixtures__/mdx-to-csf/story-function.output.snapshot +18 -0
  44. package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.input.js +18 -0
  45. package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.output.snapshot +32 -0
  46. package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.input.js +22 -0
  47. package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.output.snapshot +34 -0
  48. package/src/transforms/__testfixtures__/move-builtin-addons/default.input.js +2 -0
  49. package/src/transforms/__testfixtures__/move-builtin-addons/default.output.snapshot +8 -0
  50. package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.input.js +3 -0
  51. package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.output.snapshot +7 -0
  52. package/src/transforms/__testfixtures__/storiesof-to-csf/basic.input.js +18 -0
  53. package/src/transforms/__testfixtures__/storiesof-to-csf/basic.output.snapshot +45 -0
  54. package/src/transforms/__testfixtures__/storiesof-to-csf/collision.input.js +11 -0
  55. package/src/transforms/__testfixtures__/storiesof-to-csf/collision.output.snapshot +38 -0
  56. package/src/transforms/__testfixtures__/storiesof-to-csf/const.input.js +1 -0
  57. package/src/transforms/__testfixtures__/storiesof-to-csf/const.output.snapshot +13 -0
  58. package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.input.js +9 -0
  59. package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.output.snapshot +18 -0
  60. package/src/transforms/__testfixtures__/storiesof-to-csf/default.input.js +7 -0
  61. package/src/transforms/__testfixtures__/storiesof-to-csf/default.output.snapshot +17 -0
  62. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.input.js +1 -0
  63. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.js +5 -0
  64. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.snapshot +9 -0
  65. package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.input.js +11 -0
  66. package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.output.snapshot +23 -0
  67. package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.input.js +12 -0
  68. package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.output.snapshot +23 -0
  69. package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.input.js +14 -0
  70. package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.output.snapshot +26 -0
  71. package/src/transforms/__testfixtures__/storiesof-to-csf/exports.input.js +2 -0
  72. package/src/transforms/__testfixtures__/storiesof-to-csf/exports.output.snapshot +16 -0
  73. package/src/transforms/__testfixtures__/storiesof-to-csf/module.input.js +12 -0
  74. package/src/transforms/__testfixtures__/storiesof-to-csf/module.output.snapshot +16 -0
  75. package/src/transforms/__testfixtures__/storiesof-to-csf/multi.input.js +14 -0
  76. package/src/transforms/__testfixtures__/storiesof-to-csf/multi.output.snapshot +39 -0
  77. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.input.js +8 -0
  78. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.output.snapshot +20 -0
  79. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.input.js +10 -0
  80. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.output.snapshot +23 -0
  81. package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.input.js +11 -0
  82. package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.output.snapshot +23 -0
  83. package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.input.js +11 -0
  84. package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.output.snapshot +29 -0
  85. package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js +14 -0
  86. package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.output.snapshot +32 -0
  87. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.input.js +198 -0
  88. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.output.snapshot +198 -0
  89. package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.input.js +19 -0
  90. package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.output.snapshot +23 -0
  91. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.input.js +3 -0
  92. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.output.snapshot +7 -0
  93. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.input.js +5 -0
  94. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.output.snapshot +9 -0
  95. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.input.js +8 -0
  96. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.output.snapshot +12 -0
  97. package/src/transforms/__tests__/csf-2-to-3.test.ts +251 -0
  98. package/src/transforms/__tests__/transforms.tests.js +30 -0
  99. package/{dist/esm → src}/transforms/add-component-parameters.js +26 -21
  100. package/src/transforms/csf-2-to-3.ts +183 -0
  101. package/src/transforms/csf-hoist-story-annotations.js +97 -0
  102. package/src/transforms/csf-to-mdx.js +190 -0
  103. package/src/transforms/mdx-to-csf.js +184 -0
  104. package/src/transforms/move-builtin-addons.js +32 -0
  105. package/src/transforms/storiesof-to-csf.js +277 -0
  106. package/{dist/esm → src}/transforms/update-addon-info.js +44 -24
  107. package/{dist/esm → src}/transforms/update-organisation-name.js +19 -22
  108. package/src/transforms/upgrade-hierarchy-separators.js +39 -0
  109. package/tsconfig.json +13 -0
  110. package/dist/cjs/index.js +0 -139
  111. package/dist/cjs/lib/utils.js +0 -45
  112. package/dist/cjs/transforms/add-component-parameters.js +0 -64
  113. package/dist/cjs/transforms/csf-2-to-3.js +0 -180
  114. package/dist/cjs/transforms/csf-hoist-story-annotations.js +0 -93
  115. package/dist/cjs/transforms/csf-to-mdx.js +0 -196
  116. package/dist/cjs/transforms/mdx-to-csf.js +0 -153
  117. package/dist/cjs/transforms/move-builtin-addons.js +0 -55
  118. package/dist/cjs/transforms/storiesof-to-csf.js +0 -300
  119. package/dist/cjs/transforms/update-addon-info.js +0 -101
  120. package/dist/cjs/transforms/update-organisation-name.js +0 -83
  121. package/dist/cjs/transforms/upgrade-hierarchy-separators.js +0 -42
  122. package/dist/esm/index.js +0 -97
  123. package/dist/esm/transforms/csf-2-to-3.js +0 -163
  124. package/dist/esm/transforms/csf-hoist-story-annotations.js +0 -86
  125. package/dist/esm/transforms/csf-to-mdx.js +0 -188
  126. package/dist/esm/transforms/mdx-to-csf.js +0 -139
  127. package/dist/esm/transforms/move-builtin-addons.js +0 -48
  128. package/dist/esm/transforms/storiesof-to-csf.js +0 -287
  129. package/dist/esm/transforms/upgrade-hierarchy-separators.js +0 -35
  130. package/dist/types/lib/utils.d.ts +0 -2
  131. package/dist/types/transforms/csf-2-to-3.d.ts +0 -6
@@ -23,8 +23,9 @@
23
23
  * )))
24
24
  */
25
25
  export default function transformer(file, api) {
26
- var j = api.jscodeshift;
27
- var root = j(file.source);
26
+ const j = api.jscodeshift;
27
+ const root = j(file.source);
28
+
28
29
  /**
29
30
  * Returns a list of parameters for the withInfo function. The contents
30
31
  * of this list is either the second argument from the original
@@ -33,56 +34,75 @@ export default function transformer(file, api) {
33
34
  * @param {list} args - original addWithInfo function parameters
34
35
  * @return {list} the modified list of parameters for the new function
35
36
  */
36
-
37
- var getOptions = function (args) {
37
+ const getOptions = (args) => {
38
38
  if (args[3] === undefined) {
39
39
  if (args[2] === undefined) {
40
40
  // when the optional description string is not supplied for addWithInfo, use story name
41
41
  return [args[0]];
42
42
  }
43
-
44
43
  return [args[1]];
45
44
  }
46
-
47
- return [j.objectExpression([j.property('init', j.identifier('text'), args[1]), ...args[3].properties])];
45
+ return [
46
+ j.objectExpression([
47
+ j.property('init', j.identifier('text'), args[1]),
48
+ ...args[3].properties,
49
+ ]),
50
+ ];
48
51
  };
52
+
49
53
  /**
50
54
  * Constructs the new withInfo function from the parameters of the
51
55
  * original addWithInfo function.
52
56
  * @param {CallExpression} addWithInfoExpression - original function
53
57
  * @returns {CallExpression} the new withInfo function
54
58
  */
59
+ const withInfo = (addWithInfoExpression) => {
60
+ const { node } = addWithInfoExpression;
61
+ const args = node.arguments;
55
62
 
63
+ // if optional description string is not supplied, the story component becomes second arg
64
+ const storyComponent = args[2] ? args[2] : args[1];
56
65
 
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
66
  node.callee.property.name = 'add';
63
- node.arguments = [args[0], j.callExpression(j.callExpression(j.identifier('withInfo'), getOptions(args)), [storyComponent])];
67
+ node.arguments = [
68
+ args[0],
69
+ j.callExpression(j.callExpression(j.identifier('withInfo'), getOptions(args)), [
70
+ storyComponent,
71
+ ]),
72
+ ];
73
+
64
74
  return node;
65
75
  };
76
+
66
77
  /**
67
78
  * Checks for - import { withInfo } from "@storybook/addon-info";
68
79
  * Adds the import if necessary.
69
80
  */
81
+ const checkWithInfoImport = () => {
82
+ const importExists = root
83
+ .find(j.ImportDeclaration)
84
+ .filter((imp) => imp.node.source.value === '@storybook/addon-info')
85
+ .size();
70
86
 
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
87
  if (importExists) return;
77
- root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier('withInfo'))], j.literal('@storybook/addon-info')));
88
+
89
+ root
90
+ .find(j.ImportDeclaration)
91
+ .at(-1)
92
+ .insertAfter(
93
+ j.importDeclaration(
94
+ [j.importSpecifier(j.identifier('withInfo'))],
95
+ j.literal('@storybook/addon-info')
96
+ )
97
+ );
78
98
  };
79
99
 
80
- var addWithInfoExpressions = root.find(j.CallExpression, {
100
+ const addWithInfoExpressions = root.find(j.CallExpression, {
81
101
  callee: {
82
102
  property: {
83
- name: 'addWithInfo'
84
- }
85
- }
103
+ name: 'addWithInfo',
104
+ },
105
+ },
86
106
  });
87
107
 
88
108
  if (addWithInfoExpressions.size()) {
@@ -91,4 +111,4 @@ export default function transformer(file, api) {
91
111
  }
92
112
 
93
113
  return root.toSource();
94
- }
114
+ }
@@ -1,4 +1,4 @@
1
- export var packageNames = {
1
+ export const packageNames = {
2
2
  '@kadira/react-storybook-decorator-centered': '@storybook/addon-centered',
3
3
  '@kadira/storybook-addons': '@storybook/addons',
4
4
  '@kadira/storybook-addon-actions': '@storybook/addon-actions',
@@ -18,22 +18,21 @@ export var packageNames = {
18
18
  '@kadira/getstorybook': '@storybook/cli',
19
19
  '@kadira/storybook': '@storybook/react',
20
20
  storyshots: '@storybook/addon-storyshots',
21
- getstorybook: '@storybook/cli'
21
+ getstorybook: '@storybook/cli',
22
22
  };
23
+
23
24
  export default function transformer(file, api) {
24
- var j = api.jscodeshift;
25
- var packageNamesKeys = Object.keys(packageNames);
25
+ const j = api.jscodeshift;
26
+
27
+ const packageNamesKeys = Object.keys(packageNames);
28
+
26
29
  /**
27
30
  * Checks whether the node value matches a Storybook package
28
31
  * @param {string} the import declaration node
29
32
  * @returns {string} whether the node value matches a Storybook package
30
33
  */
34
+ const getMatch = (oldpart) => packageNamesKeys.find((newpart) => oldpart.match(newpart));
31
35
 
32
- var getMatch = function (oldpart) {
33
- return packageNamesKeys.find(function (newpart) {
34
- return oldpart.match(newpart);
35
- });
36
- };
37
36
  /**
38
37
  * Returns the name of the Storybook packages with the organisation name,
39
38
  * replacing the old `@kadira/` prefix.
@@ -43,32 +42,30 @@ export default function transformer(file, api) {
43
42
  * // returns '@storybook/storybook'
44
43
  * getNewPackageName('@kadira/storybook')
45
44
  */
46
-
47
-
48
- var getNewPackageName = function (oldPackageName) {
49
- var match = getMatch(oldPackageName);
45
+ const getNewPackageName = (oldPackageName) => {
46
+ const match = getMatch(oldPackageName);
50
47
 
51
48
  if (match) {
52
- var replacement = packageNames[match];
49
+ const replacement = packageNames[match];
53
50
  return oldPackageName.replace(match, replacement);
54
51
  }
55
-
56
52
  return oldPackageName;
57
53
  };
54
+
58
55
  /**
59
56
  * updatePackageName - updates the source name of the Storybook packages
60
57
  * @param {ImportDeclaration} declaration the import declaration
61
58
  * @returns {ImportDeclaration.Node} the import declaration node
62
59
  */
63
-
64
-
65
- var updatePackageName = function (declaration) {
60
+ const updatePackageName = (declaration) => {
66
61
  // eslint-disable-next-line no-param-reassign
67
62
  declaration.node.source.value = getNewPackageName(declaration.node.source.value);
63
+
68
64
  return declaration.node;
69
65
  };
70
66
 
71
- return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({
72
- quote: 'single'
73
- });
74
- }
67
+ return j(file.source)
68
+ .find(j.ImportDeclaration)
69
+ .replaceWith(updatePackageName)
70
+ .toSource({ quote: 'single' });
71
+ }
@@ -0,0 +1,39 @@
1
+ function upgradeSeparator(path) {
2
+ return path.replace(/[|.]/g, '/');
3
+ }
4
+
5
+ export default function transformer(file, api, options) {
6
+ const j = api.jscodeshift;
7
+ const root = j(file.source);
8
+
9
+ // storiesOf(...)
10
+ root
11
+ .find(j.CallExpression)
12
+ .filter((call) => call.node.callee.name === 'storiesOf')
13
+ .filter(
14
+ (call) =>
15
+ call.node.arguments.length > 0 &&
16
+ ['Literal', 'StringLiteral'].includes(call.node.arguments[0].type)
17
+ )
18
+ .forEach((call) => {
19
+ const arg0 = call.node.arguments[0];
20
+ arg0.value = upgradeSeparator(arg0.value);
21
+ });
22
+
23
+ // export default { title: ... }
24
+ root
25
+ .find(j.ExportDefaultDeclaration)
26
+ .filter((def) => def.node.declaration.properties.map((p) => p.key.name).includes('title'))
27
+ .forEach((def) => {
28
+ if (def.node.declaration && def.node.declaration.properties) {
29
+ def.node.declaration.properties.forEach((p) => {
30
+ if (p.key.name === 'title') {
31
+ // eslint-disable-next-line no-param-reassign
32
+ p.value.value = upgradeSeparator(p.value.value);
33
+ }
34
+ });
35
+ }
36
+ });
37
+
38
+ return root.toSource({ quote: 'single' });
39
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {},
4
+ "include": ["src/**/*"],
5
+ "exclude": [
6
+ "src/**/*.test.*",
7
+ "src/**/tests/**/*",
8
+ "src/**/__tests__/**/*",
9
+ "src/**/*.stories.*",
10
+ "src/**/*.mockdata.*",
11
+ "src/**/__testfixtures__/**"
12
+ ]
13
+ }
package/dist/cjs/index.js DELETED
@@ -1,139 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.listCodemods = listCodemods;
7
- Object.defineProperty(exports, "packageNames", {
8
- enumerable: true,
9
- get: function () {
10
- return _updateOrganisationName.packageNames;
11
- }
12
- });
13
- exports.runCodemod = runCodemod;
14
- Object.defineProperty(exports, "updateAddonInfo", {
15
- enumerable: true,
16
- get: function () {
17
- return _updateAddonInfo.default;
18
- }
19
- });
20
- Object.defineProperty(exports, "updateOrganisationName", {
21
- enumerable: true,
22
- get: function () {
23
- return _updateOrganisationName.default;
24
- }
25
- });
26
-
27
- var _fs = _interopRequireDefault(require("fs"));
28
-
29
- var _path = _interopRequireDefault(require("path"));
30
-
31
- var _util = require("util");
32
-
33
- var _globby = _interopRequireDefault(require("globby"));
34
-
35
- var _crossSpawn = require("cross-spawn");
36
-
37
- var _utils = require("./lib/utils");
38
-
39
- var _updateOrganisationName = _interopRequireWildcard(require("./transforms/update-organisation-name"));
40
-
41
- var _updateAddonInfo = _interopRequireDefault(require("./transforms/update-addon-info"));
42
-
43
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
44
-
45
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
46
-
47
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
48
-
49
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
50
-
51
- 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."); }
52
-
53
- 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); }
54
-
55
- 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; }
56
-
57
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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; }
58
-
59
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
60
-
61
- var TRANSFORM_DIR = `${__dirname}/transforms`;
62
-
63
- function listCodemods() {
64
- return _fs.default.readdirSync(TRANSFORM_DIR).filter(function (fname) {
65
- return fname.endsWith('.js');
66
- }).map(function (fname) {
67
- return fname.slice(0, -3);
68
- });
69
- }
70
-
71
- var renameAsync = (0, _util.promisify)(_fs.default.rename);
72
-
73
- async function renameFile(file, from, to, {
74
- logger: logger
75
- }) {
76
- var newFile = file.replace(from, to);
77
- logger.log(`Rename: ${file} ${newFile}`);
78
- return renameAsync(file, newFile);
79
- }
80
-
81
- async function runCodemod(codemod, {
82
- glob: glob,
83
- logger: logger,
84
- dryRun: dryRun,
85
- rename: rename,
86
- parser: parser
87
- }) {
88
- var codemods = listCodemods();
89
-
90
- if (!codemods.includes(codemod)) {
91
- throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);
92
- }
93
-
94
- var renameParts = null;
95
-
96
- if (rename) {
97
- renameParts = rename.split(':');
98
-
99
- if (renameParts.length !== 2) {
100
- throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);
101
- }
102
- } // jscodeshift/prettier know how to handle .ts/.tsx extensions,
103
- // so if the user uses one of those globs, we can auto-infer
104
-
105
-
106
- var inferredParser = parser;
107
-
108
- if (!parser) {
109
- var extension = _path.default.extname(glob).slice(1);
110
-
111
- var knownParser = (0, _utils.jscodeshiftToPrettierParser)(extension);
112
- if (knownParser !== 'babel') inferredParser = extension;
113
- }
114
-
115
- var files = await (0, _globby.default)([glob, '!**/node_modules', '!**/dist']);
116
- logger.log(`=> Applying ${codemod}: ${files.length} files`);
117
-
118
- if (!dryRun) {
119
- var parserArgs = inferredParser ? ['--parser', inferredParser] : [];
120
- (0, _crossSpawn.sync)('npx', ['jscodeshift', '-t', `${TRANSFORM_DIR}/${codemod}.js`, ...parserArgs, ...files], {
121
- stdio: 'inherit',
122
- shell: true
123
- });
124
- }
125
-
126
- if (renameParts) {
127
- var _renameParts = renameParts,
128
- _renameParts2 = _slicedToArray(_renameParts, 2),
129
- from = _renameParts2[0],
130
- to = _renameParts2[1];
131
-
132
- logger.log(`=> Renaming ${rename}: ${files.length} files`);
133
- await Promise.all(files.map(function (file) {
134
- return renameFile(file, new RegExp(`${from}$`), to, {
135
- logger: logger
136
- });
137
- }));
138
- }
139
- }
@@ -1,45 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.jscodeshiftToPrettierParser = jscodeshiftToPrettierParser;
7
- exports.sanitizeName = void 0;
8
-
9
- var _camelCase = _interopRequireDefault(require("lodash/camelCase"));
10
-
11
- var _upperFirst = _interopRequireDefault(require("lodash/upperFirst"));
12
-
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
- var sanitizeName = function (name) {
16
- var key = (0, _upperFirst.default)((0, _camelCase.default)(name)); // prepend _ if name starts with a digit
17
-
18
- if (/^\d/.test(key)) {
19
- key = `_${key}`;
20
- } // prepend _ if name starts with a digit
21
-
22
-
23
- if (/^\d/.test(key)) {
24
- key = `_${key}`;
25
- }
26
-
27
- return key;
28
- };
29
-
30
- exports.sanitizeName = sanitizeName;
31
-
32
- function jscodeshiftToPrettierParser(parser) {
33
- var parserMap = {
34
- babylon: 'babel',
35
- flow: 'flow',
36
- ts: 'typescript',
37
- tsx: 'typescript'
38
- };
39
-
40
- if (!parser) {
41
- return 'babel';
42
- }
43
-
44
- return parserMap[parser] || 'babel';
45
- }
@@ -1,64 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = transformer;
7
-
8
- /**
9
- * Adds a `component` parameter for each storiesOf(...) call.
10
- *
11
- * For example:
12
- *
13
- * input { Button } from './Button';
14
- * storiesOf('Button', module).add('story', () => <Button label="The Button" />);
15
- *
16
- * Becomes:
17
- *
18
- * input { Button } from './Button';
19
- * storiesOf('Button', module)
20
- * .addParameters({ component: Button })
21
- * .add('story', () => <Button label="The Button" />);
22
- *
23
- * Heuristics:
24
- * - The storiesOf "kind" name must be Button
25
- * - Button must be imported in the file
26
- */
27
- function transformer(file, api) {
28
- var j = api.jscodeshift;
29
- var root = j(file.source); // Create a dictionary whose keys are all the named imports in the file.
30
- // For instance:
31
- //
32
- // import foo from 'foo';
33
- // import { bar, baz } from 'zoo';
34
- //
35
- // => { foo: true, bar: true, baz: true }
36
-
37
- var importMap = {};
38
- root.find(j.ImportDeclaration).forEach(function (imp) {
39
- return imp.node.specifiers.forEach(function (spec) {
40
- importMap[spec.local.name] = true;
41
- });
42
- });
43
-
44
- function getLeafName(string) {
45
- var parts = string.split(/\/|\.|\|/);
46
- return parts[parts.length - 1];
47
- }
48
-
49
- function addComponentParameter(call) {
50
- var node = call.node;
51
- var leafName = getLeafName(node.arguments[0].value);
52
- return j.callExpression(j.memberExpression(node, j.identifier('addParameters')), [j.objectExpression([j.property('init', j.identifier('component'), j.identifier(leafName))])]);
53
- }
54
-
55
- root.find(j.CallExpression).filter(function (call) {
56
- return call.node.callee.name === 'storiesOf';
57
- }).filter(function (call) {
58
- return call.node.arguments.length > 0 && call.node.arguments[0].type === 'Literal';
59
- }).filter(function (call) {
60
- var leafName = getLeafName(call.node.arguments[0].value);
61
- return importMap[leafName];
62
- }).replaceWith(addComponentParameter);
63
- return root.toSource();
64
- }
@@ -1,180 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- var _prettier = _interopRequireDefault(require("prettier"));
9
-
10
- var t = _interopRequireWildcard(require("@babel/types"));
11
-
12
- var _csfTools = require("@storybook/csf-tools");
13
-
14
- var _utils = require("../lib/utils");
15
-
16
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
-
18
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19
-
20
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
-
22
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
23
-
24
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
25
-
26
- 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; }
27
-
28
- var logger = console;
29
-
30
- var _rename = function (annotation) {
31
- return annotation === 'storyName' ? 'name' : annotation;
32
- };
33
-
34
- var getTemplateBindVariable = function (init) {
35
- return t.isCallExpression(init) && t.isMemberExpression(init.callee) && t.isIdentifier(init.callee.object) && t.isIdentifier(init.callee.property) && init.callee.property.name === 'bind' && (init.arguments.length === 0 || init.arguments.length === 1 && t.isObjectExpression(init.arguments[0]) && init.arguments[0].properties.length === 0) ? init.callee.object.name : null;
36
- }; // export const A = ...
37
- // A.parameters = { ... }; <===
38
-
39
-
40
- var isStoryAnnotation = function (stmt, objectExports) {
41
- return t.isExpressionStatement(stmt) && t.isAssignmentExpression(stmt.expression) && t.isMemberExpression(stmt.expression.left) && t.isIdentifier(stmt.expression.left.object) && objectExports[stmt.expression.left.object.name];
42
- };
43
-
44
- var isTemplateDeclaration = function (stmt, templates) {
45
- return t.isVariableDeclaration(stmt) && stmt.declarations.length === 1 && t.isIdentifier(stmt.declarations[0].id) && templates[stmt.declarations[0].id.name];
46
- };
47
-
48
- var getNewExport = function (stmt, objectExports) {
49
- if (t.isExportNamedDeclaration(stmt) && t.isVariableDeclaration(stmt.declaration) && stmt.declaration.declarations.length === 1) {
50
- var decl = stmt.declaration.declarations[0];
51
-
52
- if (t.isVariableDeclarator(decl) && t.isIdentifier(decl.id)) {
53
- return objectExports[decl.id.name];
54
- }
55
- }
56
-
57
- return null;
58
- }; // Remove render function when it matches the global render function in react
59
- // export default { component: Cat };
60
- // export const A = (args) => <Cat {...args} />;
61
-
62
-
63
- var isReactGlobalRenderFn = function (csf, storyFn) {
64
- var _csf$_meta;
65
-
66
- if ((_csf$_meta = csf._meta) !== null && _csf$_meta !== void 0 && _csf$_meta.component && t.isArrowFunctionExpression(storyFn) && storyFn.params.length === 1 && t.isJSXElement(storyFn.body)) {
67
- var openingElement = storyFn.body.openingElement;
68
-
69
- if (openingElement.selfClosing && t.isJSXIdentifier(openingElement.name) && openingElement.attributes.length === 1) {
70
- var attr = openingElement.attributes[0];
71
- var param = storyFn.params[0];
72
-
73
- if (t.isJSXSpreadAttribute(attr) && t.isIdentifier(attr.argument) && t.isIdentifier(param) && param.name === attr.argument.name && csf._meta.component === openingElement.name.name) {
74
- return true;
75
- }
76
- }
77
- }
78
-
79
- return false;
80
- }; // A simple CSF story is a no-arg story without any extra annotations (params, args, etc.)
81
-
82
-
83
- var isSimpleCSFStory = function (init, annotations) {
84
- return annotations.length === 0 && t.isArrowFunctionExpression(init) && init.params.length === 0;
85
- };
86
-
87
- function transform({
88
- source: source
89
- }, api, options) {
90
- var makeTitle = function (userTitle) {
91
- return userTitle || 'FIXME';
92
- };
93
-
94
- var csf = (0, _csfTools.loadCsf)(source, {
95
- makeTitle: makeTitle
96
- });
97
-
98
- try {
99
- csf.parse();
100
- } catch (err) {
101
- logger.log(`Error ${err}, skipping`);
102
- return source;
103
- }
104
-
105
- var objectExports = {};
106
- Object.entries(csf._storyExports).forEach(function ([key, decl]) {
107
- var annotations = Object.entries(csf._storyAnnotations[key]).map(function ([annotation, val]) {
108
- return t.objectProperty(t.identifier(_rename(annotation)), val);
109
- });
110
-
111
- if (t.isVariableDeclarator(decl)) {
112
- var init = decl.init,
113
- id = decl.id; // only replace arrow function expressions && template
114
- // ignore no-arg stories without annotations
115
-
116
- var template = getTemplateBindVariable(init);
117
-
118
- if (!t.isArrowFunctionExpression(init) && !template || isSimpleCSFStory(init, annotations)) {
119
- return;
120
- } // Remove the render function when we can hoist the template
121
- // const Template = (args) => <Cat {...args} />;
122
- // export const A = Template.bind({});
123
-
124
-
125
- var storyFn = template && csf._templates[template];
126
-
127
- if (!storyFn) {
128
- storyFn = init;
129
- }
130
-
131
- var keyId = t.identifier(key); // @ts-expect-error (Converted from ts-ignore)
132
-
133
- var typeAnnotation = id.typeAnnotation;
134
-
135
- if (typeAnnotation) {
136
- keyId.typeAnnotation = typeAnnotation;
137
- }
138
-
139
- var renderAnnotation = isReactGlobalRenderFn(csf, storyFn) ? [] : [t.objectProperty(t.identifier('render'), storyFn)];
140
- objectExports[key] = t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(keyId, t.objectExpression([...renderAnnotation, ...annotations]))]));
141
- }
142
- });
143
-
144
- var updatedBody = csf._ast.program.body.reduce(function (acc, stmt) {
145
- // remove story annotations & template declarations
146
- if (isStoryAnnotation(stmt, objectExports) || isTemplateDeclaration(stmt, csf._templates)) {
147
- return acc;
148
- } // replace story exports with new object exports
149
-
150
-
151
- var newExport = getNewExport(stmt, objectExports);
152
-
153
- if (newExport) {
154
- acc.push(newExport);
155
- return acc;
156
- } // include unknown statements
157
-
158
-
159
- acc.push(stmt);
160
- return acc;
161
- }, []);
162
-
163
- csf._ast.program.body = updatedBody;
164
- var output = (0, _csfTools.formatCsf)(csf);
165
- var prettierConfig = _prettier.default.resolveConfig.sync('.', {
166
- editorconfig: true
167
- }) || {
168
- printWidth: 100,
169
- tabWidth: 2,
170
- bracketSpacing: true,
171
- trailingComma: 'es5',
172
- singleQuote: true
173
- };
174
- return _prettier.default.format(output, _objectSpread(_objectSpread({}, prettierConfig), {}, {
175
- parser: (0, _utils.jscodeshiftToPrettierParser)(options === null || options === void 0 ? void 0 : options.parser)
176
- }));
177
- }
178
-
179
- var _default = transform;
180
- exports.default = _default;