@storybook/codemod 7.0.0-alpha.8 → 7.0.0-beta.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (133) hide show
  1. package/README.md +0 -36
  2. package/dist/index.d.ts +261 -0
  3. package/dist/index.js +1 -0
  4. package/dist/index.mjs +1 -0
  5. package/jest.config.js +7 -0
  6. package/package.json +32 -29
  7. package/src/index.js +77 -0
  8. package/src/lib/utils.test.js +9 -0
  9. package/{dist/esm/lib/utils.js → src/lib/utils.ts} +10 -11
  10. package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.input.js +44 -0
  11. package/src/transforms/__testfixtures__/add-component-parameters/add-component-parameters.output.snapshot +68 -0
  12. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.input.js +25 -0
  13. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/basic.output.snapshot +27 -0
  14. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.input.js +25 -0
  15. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.output.snapshot +28 -0
  16. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.input.js +13 -0
  17. package/src/transforms/__testfixtures__/csf-hoist-story-annotations/variable.output.snapshot +17 -0
  18. package/src/transforms/__testfixtures__/csf-to-mdx/basic.input.js +20 -0
  19. package/src/transforms/__testfixtures__/csf-to-mdx/basic.output.snapshot +18 -0
  20. package/src/transforms/__testfixtures__/csf-to-mdx/component-id.input.js +9 -0
  21. package/src/transforms/__testfixtures__/csf-to-mdx/component-id.output.snapshot +10 -0
  22. package/src/transforms/__testfixtures__/csf-to-mdx/decorators.input.js +13 -0
  23. package/src/transforms/__testfixtures__/csf-to-mdx/decorators.output.snapshot +12 -0
  24. package/src/transforms/__testfixtures__/csf-to-mdx/exclude-stories.input.js +23 -0
  25. package/src/transforms/__testfixtures__/csf-to-mdx/exclude-stories.output.snapshot +22 -0
  26. package/src/transforms/__testfixtures__/csf-to-mdx/parameters.input.js +16 -0
  27. package/src/transforms/__testfixtures__/csf-to-mdx/parameters.output.snapshot +17 -0
  28. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.input.js +19 -0
  29. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.output.snapshot +18 -0
  30. package/src/transforms/__testfixtures__/csf-to-mdx/story-parameters.input.js +24 -0
  31. package/src/transforms/__testfixtures__/csf-to-mdx/story-parameters.output.snapshot +22 -0
  32. package/src/transforms/__testfixtures__/mdx-to-csf/basic.input.js +18 -0
  33. package/src/transforms/__testfixtures__/mdx-to-csf/basic.output.snapshot +40 -0
  34. package/src/transforms/__testfixtures__/mdx-to-csf/component-id.input.js +6 -0
  35. package/src/transforms/__testfixtures__/mdx-to-csf/component-id.output.snapshot +17 -0
  36. package/src/transforms/__testfixtures__/mdx-to-csf/decorators.input.js +8 -0
  37. package/src/transforms/__testfixtures__/mdx-to-csf/decorators.output.snapshot +18 -0
  38. package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.input.js +19 -0
  39. package/src/transforms/__testfixtures__/mdx-to-csf/exclude-stories.output.snapshot +39 -0
  40. package/src/transforms/__testfixtures__/mdx-to-csf/parameters.input.js +14 -0
  41. package/src/transforms/__testfixtures__/mdx-to-csf/parameters.output.snapshot +23 -0
  42. package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.input.js +3 -0
  43. package/src/transforms/__testfixtures__/mdx-to-csf/plaintext.output.snapshot +11 -0
  44. package/src/transforms/__testfixtures__/mdx-to-csf/story-function.input.js +10 -0
  45. package/src/transforms/__testfixtures__/mdx-to-csf/story-function.output.snapshot +18 -0
  46. package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.input.js +18 -0
  47. package/src/transforms/__testfixtures__/mdx-to-csf/story-parameters.output.snapshot +32 -0
  48. package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.input.js +22 -0
  49. package/src/transforms/__testfixtures__/mdx-to-csf/story-refs.output.snapshot +34 -0
  50. package/src/transforms/__testfixtures__/move-builtin-addons/default.input.js +2 -0
  51. package/src/transforms/__testfixtures__/move-builtin-addons/default.output.snapshot +8 -0
  52. package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.input.js +3 -0
  53. package/src/transforms/__testfixtures__/move-builtin-addons/with-no-change.output.snapshot +7 -0
  54. package/src/transforms/__testfixtures__/storiesof-to-csf/basic.input.js +18 -0
  55. package/src/transforms/__testfixtures__/storiesof-to-csf/basic.output.snapshot +45 -0
  56. package/src/transforms/__testfixtures__/storiesof-to-csf/collision.input.js +11 -0
  57. package/src/transforms/__testfixtures__/storiesof-to-csf/collision.output.snapshot +38 -0
  58. package/src/transforms/__testfixtures__/storiesof-to-csf/const.input.js +1 -0
  59. package/src/transforms/__testfixtures__/storiesof-to-csf/const.output.snapshot +13 -0
  60. package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.input.js +9 -0
  61. package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.output.snapshot +18 -0
  62. package/src/transforms/__testfixtures__/storiesof-to-csf/default.input.js +7 -0
  63. package/src/transforms/__testfixtures__/storiesof-to-csf/default.output.snapshot +17 -0
  64. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.input.js +1 -0
  65. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.js +5 -0
  66. package/src/transforms/__testfixtures__/storiesof-to-csf/digit.output.snapshot +9 -0
  67. package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.input.js +11 -0
  68. package/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.output.snapshot +23 -0
  69. package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.input.js +12 -0
  70. package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.output.snapshot +23 -0
  71. package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.input.js +14 -0
  72. package/src/transforms/__testfixtures__/storiesof-to-csf/export-names.output.snapshot +26 -0
  73. package/src/transforms/__testfixtures__/storiesof-to-csf/exports.input.js +2 -0
  74. package/src/transforms/__testfixtures__/storiesof-to-csf/exports.output.snapshot +16 -0
  75. package/src/transforms/__testfixtures__/storiesof-to-csf/module.input.js +12 -0
  76. package/src/transforms/__testfixtures__/storiesof-to-csf/module.output.snapshot +16 -0
  77. package/src/transforms/__testfixtures__/storiesof-to-csf/multi.input.js +14 -0
  78. package/src/transforms/__testfixtures__/storiesof-to-csf/multi.output.snapshot +39 -0
  79. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.input.js +8 -0
  80. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters-as-var.output.snapshot +20 -0
  81. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.input.js +10 -0
  82. package/src/transforms/__testfixtures__/storiesof-to-csf/parameters.output.snapshot +23 -0
  83. package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.input.js +11 -0
  84. package/src/transforms/__testfixtures__/storiesof-to-csf/storiesof-var.output.snapshot +23 -0
  85. package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.input.js +11 -0
  86. package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.output.snapshot +29 -0
  87. package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js +14 -0
  88. package/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.output.snapshot +32 -0
  89. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.input.js +198 -0
  90. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.output.snapshot +198 -0
  91. package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.input.js +19 -0
  92. package/src/transforms/__testfixtures__/update-organisation-name/update-organisation-name.output.snapshot +23 -0
  93. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.input.js +3 -0
  94. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.output.snapshot +7 -0
  95. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.input.js +5 -0
  96. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/dynamic-storiesof.output.snapshot +9 -0
  97. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.input.js +8 -0
  98. package/src/transforms/__testfixtures__/upgrade-hierarchy-separators/storiesof.output.snapshot +12 -0
  99. package/src/transforms/__tests__/csf-2-to-3.test.ts +250 -0
  100. package/src/transforms/__tests__/transforms.tests.js +32 -0
  101. package/{dist/esm → src}/transforms/add-component-parameters.js +26 -21
  102. package/src/transforms/csf-2-to-3.ts +184 -0
  103. package/src/transforms/csf-hoist-story-annotations.js +97 -0
  104. package/src/transforms/csf-to-mdx.js +190 -0
  105. package/src/transforms/move-builtin-addons.js +32 -0
  106. package/src/transforms/storiesof-to-csf.js +277 -0
  107. package/{dist/esm → src}/transforms/update-addon-info.js +44 -24
  108. package/{dist/esm → src}/transforms/update-organisation-name.js +21 -24
  109. package/src/transforms/upgrade-hierarchy-separators.js +39 -0
  110. package/tsconfig.json +7 -0
  111. package/LICENSE +0 -21
  112. package/dist/cjs/index.js +0 -142
  113. package/dist/cjs/lib/utils.js +0 -45
  114. package/dist/cjs/transforms/add-component-parameters.js +0 -64
  115. package/dist/cjs/transforms/csf-2-to-3.js +0 -180
  116. package/dist/cjs/transforms/csf-hoist-story-annotations.js +0 -93
  117. package/dist/cjs/transforms/csf-to-mdx.js +0 -196
  118. package/dist/cjs/transforms/mdx-to-csf.js +0 -153
  119. package/dist/cjs/transforms/move-builtin-addons.js +0 -57
  120. package/dist/cjs/transforms/storiesof-to-csf.js +0 -300
  121. package/dist/cjs/transforms/update-addon-info.js +0 -101
  122. package/dist/cjs/transforms/update-organisation-name.js +0 -83
  123. package/dist/cjs/transforms/upgrade-hierarchy-separators.js +0 -42
  124. package/dist/esm/index.js +0 -99
  125. package/dist/esm/transforms/csf-2-to-3.js +0 -163
  126. package/dist/esm/transforms/csf-hoist-story-annotations.js +0 -86
  127. package/dist/esm/transforms/csf-to-mdx.js +0 -188
  128. package/dist/esm/transforms/mdx-to-csf.js +0 -139
  129. package/dist/esm/transforms/move-builtin-addons.js +0 -50
  130. package/dist/esm/transforms/storiesof-to-csf.js +0 -287
  131. package/dist/esm/transforms/upgrade-hierarchy-separators.js +0 -35
  132. package/dist/types/lib/utils.d.ts +0 -2
  133. package/dist/types/transforms/csf-2-to-3.d.ts +0 -6
@@ -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,7 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "skipLibCheck": true
5
+ },
6
+ "include": ["src/**/*"]
7
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2017 Kadira Inc. <hello@kadira.io>
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
package/dist/cjs/index.js DELETED
@@ -1,142 +0,0 @@
1
- "use strict";
2
-
3
- require("core-js/modules/es.symbol.description.js");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.listCodemods = listCodemods;
9
- Object.defineProperty(exports, "packageNames", {
10
- enumerable: true,
11
- get: function () {
12
- return _updateOrganisationName.packageNames;
13
- }
14
- });
15
- exports.runCodemod = runCodemod;
16
- Object.defineProperty(exports, "updateAddonInfo", {
17
- enumerable: true,
18
- get: function () {
19
- return _updateAddonInfo.default;
20
- }
21
- });
22
- Object.defineProperty(exports, "updateOrganisationName", {
23
- enumerable: true,
24
- get: function () {
25
- return _updateOrganisationName.default;
26
- }
27
- });
28
-
29
- require("core-js/modules/es.promise.js");
30
-
31
- var _fs = _interopRequireDefault(require("fs"));
32
-
33
- var _path = _interopRequireDefault(require("path"));
34
-
35
- var _util = require("util");
36
-
37
- var _globby = _interopRequireDefault(require("globby"));
38
-
39
- var _crossSpawn = require("cross-spawn");
40
-
41
- var _utils = require("./lib/utils");
42
-
43
- var _updateOrganisationName = _interopRequireWildcard(require("./transforms/update-organisation-name"));
44
-
45
- var _updateAddonInfo = _interopRequireDefault(require("./transforms/update-addon-info"));
46
-
47
- 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); }
48
-
49
- 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; }
50
-
51
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
52
-
53
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
54
-
55
- 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."); }
56
-
57
- 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); }
58
-
59
- 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; }
60
-
61
- 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; }
62
-
63
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
64
-
65
- var TRANSFORM_DIR = `${__dirname}/transforms`;
66
-
67
- function listCodemods() {
68
- return _fs.default.readdirSync(TRANSFORM_DIR).filter(function (fname) {
69
- return fname.endsWith('.js');
70
- }).map(function (fname) {
71
- return fname.slice(0, -3);
72
- });
73
- }
74
-
75
- var renameAsync = (0, _util.promisify)(_fs.default.rename);
76
-
77
- async function renameFile(file, from, to, {
78
- logger: logger
79
- }) {
80
- var newFile = file.replace(from, to);
81
- logger.log(`Rename: ${file} ${newFile}`);
82
- return renameAsync(file, newFile);
83
- }
84
-
85
- async function runCodemod(codemod, {
86
- glob: glob,
87
- logger: logger,
88
- dryRun: dryRun,
89
- rename: rename,
90
- parser: parser
91
- }) {
92
- var codemods = listCodemods();
93
-
94
- if (!codemods.includes(codemod)) {
95
- throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);
96
- }
97
-
98
- var renameParts = null;
99
-
100
- if (rename) {
101
- renameParts = rename.split(':');
102
-
103
- if (renameParts.length !== 2) {
104
- throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);
105
- }
106
- } // jscodeshift/prettier know how to handle .ts/.tsx extensions,
107
- // so if the user uses one of those globs, we can auto-infer
108
-
109
-
110
- var inferredParser = parser;
111
-
112
- if (!parser) {
113
- var extension = _path.default.extname(glob).slice(1);
114
-
115
- var knownParser = (0, _utils.jscodeshiftToPrettierParser)(extension);
116
- if (knownParser !== 'babel') inferredParser = extension;
117
- }
118
-
119
- var files = await (0, _globby.default)([glob, '!**/node_modules', '!**/dist']);
120
- logger.log(`=> Applying ${codemod}: ${files.length} files`);
121
-
122
- if (!dryRun) {
123
- var parserArgs = inferredParser ? ['--parser', inferredParser] : [];
124
- (0, _crossSpawn.sync)('npx', ['jscodeshift', '-t', `${TRANSFORM_DIR}/${codemod}.js`, ...parserArgs, ...files], {
125
- stdio: 'inherit'
126
- });
127
- }
128
-
129
- if (renameParts) {
130
- var _renameParts = renameParts,
131
- _renameParts2 = _slicedToArray(_renameParts, 2),
132
- from = _renameParts2[0],
133
- to = _renameParts2[1];
134
-
135
- logger.log(`=> Renaming ${rename}: ${files.length} files`);
136
- await Promise.all(files.map(function (file) {
137
- return renameFile(file, new RegExp(`${from}$`), to, {
138
- logger: logger
139
- });
140
- }));
141
- }
142
- }
@@ -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
- var storiesOfCalls = 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-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;
@@ -1,93 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = transformer;
7
-
8
- var getContainingStatement = function (n) {
9
- if (n.node.type.endsWith('Statement')) {
10
- return n;
11
- }
12
-
13
- return getContainingStatement(n.parent);
14
- };
15
- /**
16
- * Hoist CSF .story annotations
17
- *
18
- * For example:
19
- *
20
- * ```
21
- * export const Basic = () => <Button />
22
- * Basic.story = {
23
- * name: 'foo',
24
- * parameters: { ... },
25
- * decorators = [ ... ],
26
- * };
27
- * ```
28
- *
29
- * Becomes:
30
- *
31
- * ```
32
- * export const Basic = () => <Button />
33
- * Basic.storyName = 'foo';
34
- * Basic.parameters = { ... };
35
- * Basic.decorators = [ ... ];
36
- * ```
37
- */
38
-
39
-
40
- function transformer(file, api) {
41
- var j = api.jscodeshift;
42
- var root = j(file.source);
43
-
44
- var renameKey = function (exp) {
45
- return exp.type === 'Identifier' && exp.name === 'name' ? j.identifier('storyName') : exp;
46
- }; // 1. If the program does not have `export default { title: '....' }, skip it
47
-
48
-
49
- var defaultExportWithTitle = root.find(j.ExportDefaultDeclaration).filter(function (def) {
50
- return def.node.declaration.type === 'ObjectExpression' && def.node.declaration.properties.map(function (p) {
51
- return p.key.name;
52
- }).includes('title');
53
- });
54
-
55
- if (defaultExportWithTitle.size() === 0) {
56
- return root.toSource();
57
- } // 2. Replace each Foo.story = { x: xVal } with Foo.x = xVal;
58
-
59
-
60
- var storyAssignments = root.find(j.AssignmentExpression).filter(function (exp) {
61
- var _exp$node = exp.node,
62
- left = _exp$node.left,
63
- right = _exp$node.right;
64
- return left.type === 'MemberExpression' && left.object.type === 'Identifier' && left.property.type === 'Identifier' && left.property.name === 'story' && right.type === 'ObjectExpression';
65
- });
66
- storyAssignments.forEach(function (exp) {
67
- var _exp$node2 = exp.node,
68
- left = _exp$node2.left,
69
- right = _exp$node2.right;
70
- right.properties.forEach(function (prop) {
71
- var stmt = getContainingStatement(exp);
72
- stmt.insertBefore(j.assignmentStatement('=', j.memberExpression(left.object, renameKey(prop.key)), prop.value));
73
- });
74
- }); // 3. Remove the .story annotations
75
-
76
- storyAssignments.remove(); // 4. Replace each Foo.story.x with Foo.x;
77
-
78
- var storyOverrides = root.find(j.AssignmentExpression).filter(function (exp) {
79
- var left = exp.node.left;
80
- return left.type === 'MemberExpression' && left.object.type === 'MemberExpression' && left.object.property.type === 'Identifier' && left.object.property.name === 'story' && left.property.type === 'Identifier' // ?? ANNOTATION_FIELDS.includes(right.property.name)
81
- ;
82
- });
83
- storyOverrides.replaceWith(function (exp) {
84
- var _exp$node3 = exp.node,
85
- left = _exp$node3.left,
86
- right = _exp$node3.right;
87
- return j.assignmentExpression('=', j.memberExpression(left.object.object, renameKey(left.property)), right);
88
- }); // 4. Render the updated tree
89
-
90
- return root.toSource({
91
- quote: 'single'
92
- });
93
- }