@storybook/codemod 7.0.0-beta.2 → 7.0.0-beta.21

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. package/dist/chunk-3OPQTROG.mjs +1 -0
  2. package/dist/chunk-B5FMQ3BX.mjs +1 -0
  3. package/dist/chunk-HBPKIMKE.mjs +1 -0
  4. package/dist/index.d.ts +13 -261
  5. package/dist/index.js +1 -1
  6. package/dist/index.mjs +1 -1
  7. package/dist/transforms/add-component-parameters.d.ts +22 -0
  8. package/dist/transforms/add-component-parameters.js +1 -0
  9. package/dist/transforms/add-component-parameters.mjs +1 -0
  10. package/dist/transforms/csf-2-to-3.d.ts +6 -0
  11. package/dist/transforms/csf-2-to-3.js +1 -0
  12. package/dist/transforms/csf-2-to-3.mjs +1 -0
  13. package/dist/transforms/csf-hoist-story-annotations.d.ts +26 -0
  14. package/dist/transforms/csf-hoist-story-annotations.js +1 -0
  15. package/dist/transforms/csf-hoist-story-annotations.mjs +1 -0
  16. package/dist/transforms/csf-to-mdx.d.ts +29 -0
  17. package/dist/transforms/csf-to-mdx.js +3 -0
  18. package/dist/transforms/csf-to-mdx.mjs +3 -0
  19. package/dist/transforms/move-builtin-addons.d.ts +3 -0
  20. package/dist/transforms/move-builtin-addons.js +1 -0
  21. package/dist/transforms/move-builtin-addons.mjs +1 -0
  22. package/dist/transforms/storiesof-to-csf.d.ts +24 -0
  23. package/dist/transforms/storiesof-to-csf.js +1 -0
  24. package/dist/transforms/storiesof-to-csf.mjs +1 -0
  25. package/dist/transforms/update-addon-info.d.ts +27 -0
  26. package/dist/transforms/update-addon-info.js +1 -0
  27. package/dist/transforms/update-addon-info.mjs +1 -0
  28. package/dist/transforms/update-organisation-name.d.ts +25 -0
  29. package/dist/transforms/update-organisation-name.js +1 -0
  30. package/dist/transforms/update-organisation-name.mjs +1 -0
  31. package/dist/transforms/upgrade-hierarchy-separators.d.ts +3 -0
  32. package/dist/transforms/upgrade-hierarchy-separators.js +1 -0
  33. package/dist/transforms/upgrade-hierarchy-separators.mjs +1 -0
  34. package/package.json +28 -7
  35. package/src/index.js +11 -1
  36. package/src/lib/utils.ts +2 -2
  37. package/src/transforms/__testfixtures__/csf-to-mdx/decorators.input.js +1 -1
  38. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.input.js +1 -1
  39. package/src/transforms/__testfixtures__/csf-to-mdx/story-function.output.snapshot +1 -1
  40. package/src/transforms/__testfixtures__/mdx-to-csf/{basic.input.js → basic.input.mdx} +0 -0
  41. package/src/transforms/__testfixtures__/mdx-to-csf/{component-id.input.js → component-id.input.mdx} +0 -0
  42. package/src/transforms/__testfixtures__/mdx-to-csf/{decorators.input.js → decorators.input.mdx} +0 -0
  43. package/src/transforms/__testfixtures__/mdx-to-csf/{exclude-stories.input.js → exclude-stories.input.mdx} +0 -0
  44. package/src/transforms/__testfixtures__/mdx-to-csf/{parameters.input.js → parameters.input.mdx} +0 -0
  45. package/src/transforms/__testfixtures__/mdx-to-csf/{plaintext.input.js → plaintext.input.mdx} +0 -0
  46. package/src/transforms/__testfixtures__/mdx-to-csf/{story-function.input.js → story-function.input.mdx} +0 -0
  47. package/src/transforms/__testfixtures__/mdx-to-csf/{story-parameters.input.js → story-parameters.input.mdx} +0 -0
  48. package/src/transforms/__testfixtures__/mdx-to-csf/{story-refs.input.js → story-refs.input.mdx} +0 -0
  49. package/src/transforms/__testfixtures__/storiesof-to-csf/decorators.input.js +1 -1
  50. package/src/transforms/__testfixtures__/storiesof-to-csf/export-function.input.js +1 -1
  51. package/src/transforms/__testfixtures__/storiesof-to-csf/story-decorators.input.js +1 -1
  52. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.input.js +34 -48
  53. package/src/transforms/__testfixtures__/update-addon-info/update-addon-info.output.snapshot +33 -47
  54. package/src/transforms/__tests__/csf-2-to-3.test.ts +5 -3
  55. package/src/transforms/csf-2-to-3.ts +23 -16
  56. package/tsconfig.json +4 -2
@@ -0,0 +1 @@
1
+ var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}export{packageNames,transformer};
@@ -0,0 +1 @@
1
+ function transformer(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}export{transformer};
@@ -0,0 +1 @@
1
+ import camelCase from"lodash/camelCase.js";import upperFirst from"lodash/upperFirst.js";var sanitizeName=name=>{let key=upperFirst(camelCase(name));return/^\d/.test(key)&&(key=`_${key}`),/^\d/.test(key)&&(key=`_${key}`),key};function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}export{sanitizeName,jscodeshiftToPrettierParser};
package/dist/index.d.ts CHANGED
@@ -1,261 +1,13 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { promisify } from 'util';
4
- import globby from 'globby';
5
- import { sync } from 'cross-spawn';
6
-
7
- declare function jscodeshiftToPrettierParser(parser?: string): string;
8
-
9
- const packageNames = {
10
- '@kadira/react-storybook-decorator-centered': '@storybook/addon-centered',
11
- '@kadira/storybook-addons': '@storybook/preview-api',
12
- '@kadira/storybook-addon-actions': '@storybook/addon-actions',
13
- '@kadira/storybook-addon-comments': '@storybook/addon-comments',
14
- '@kadira/storybook-addon-graphql': '@storybook/addon-graphql',
15
- '@kadira/storybook-addon-info': '@storybook/addon-info',
16
- '@kadira/storybook-addon-knobs': '@storybook/addon-knobs',
17
- '@kadira/storybook-addon-links': '@storybook/addon-links',
18
- '@kadira/storybook-addon-notes': '@storybook/addon-notes',
19
- '@kadira/storybook-addon-options': '@storybook/addon-options',
20
- '@kadira/storybook-channels': '@storybook/channels',
21
- '@kadira/storybook-channel-postmsg': '@storybook/channel-postmessage',
22
- '@kadira/storybook-channel-websocket': '@storybook/channel-websocket',
23
- '@kadira/storybook-ui': '@storybook/manager',
24
- '@kadira/react-native-storybook': '@storybook/react-native',
25
- '@kadira/react-storybook': '@storybook/react',
26
- '@kadira/getstorybook': '@storybook/cli',
27
- '@kadira/storybook': '@storybook/react',
28
- storyshots: '@storybook/addon-storyshots',
29
- getstorybook: '@storybook/cli',
30
- };
31
-
32
- function transformer$1(file, api) {
33
- const j = api.jscodeshift;
34
-
35
- const packageNamesKeys = Object.keys(packageNames);
36
-
37
- /**
38
- * Checks whether the node value matches a Storybook package
39
- * @param {string} the import declaration node
40
- * @returns {string} whether the node value matches a Storybook package
41
- */
42
- const getMatch = (oldpart) => packageNamesKeys.find((newpart) => oldpart.match(newpart));
43
-
44
- /**
45
- * Returns the name of the Storybook packages with the organisation name,
46
- * replacing the old `@kadira/` prefix.
47
- * @param {string} oldPackageName the name of the old package
48
- * @return {string} the new package name
49
- * @example
50
- * // returns '@storybook/storybook'
51
- * getNewPackageName('@kadira/storybook')
52
- */
53
- const getNewPackageName = (oldPackageName) => {
54
- const match = getMatch(oldPackageName);
55
-
56
- if (match) {
57
- const replacement = packageNames[match];
58
- return oldPackageName.replace(match, replacement);
59
- }
60
- return oldPackageName;
61
- };
62
-
63
- /**
64
- * updatePackageName - updates the source name of the Storybook packages
65
- * @param {ImportDeclaration} declaration the import declaration
66
- * @returns {ImportDeclaration.Node} the import declaration node
67
- */
68
- const updatePackageName = (declaration) => {
69
- // eslint-disable-next-line no-param-reassign
70
- declaration.node.source.value = getNewPackageName(declaration.node.source.value);
71
-
72
- return declaration.node;
73
- };
74
-
75
- return j(file.source)
76
- .find(j.ImportDeclaration)
77
- .replaceWith(updatePackageName)
78
- .toSource({ quote: 'single' });
79
- }
80
-
81
- /**
82
- * Takes the deprecated addon-info API, addWithInfo, and
83
- * converts to the new withInfo API.
84
- *
85
- * Example of deprecated addWithInfo API:
86
- *
87
- * storiesOf('Button')
88
- * .addWithInfo(
89
- * 'story name',
90
- * 'Story description.',
91
- * () => (
92
- * <Button label="The Button" />
93
- * )
94
- * )
95
- *
96
- * Converts to the new withInfo API:
97
- *
98
- * storiesOf('Button')
99
- * .add('story name', withInfo(
100
- * 'Story description.'
101
- * )(() => (
102
- * <Button label="The Button" />
103
- * )))
104
- */
105
- function transformer(file, api) {
106
- const j = api.jscodeshift;
107
- const root = j(file.source);
108
-
109
- /**
110
- * Returns a list of parameters for the withInfo function. The contents
111
- * of this list is either the second argument from the original
112
- * addWithInfo function, if no additional options were used, or a
113
- * combined object of all the options from the original function.
114
- * @param {list} args - original addWithInfo function parameters
115
- * @return {list} the modified list of parameters for the new function
116
- */
117
- const getOptions = (args) => {
118
- if (args[3] === undefined) {
119
- if (args[2] === undefined) {
120
- // when the optional description string is not supplied for addWithInfo, use story name
121
- return [args[0]];
122
- }
123
- return [args[1]];
124
- }
125
- return [
126
- j.objectExpression([
127
- j.property('init', j.identifier('text'), args[1]),
128
- ...args[3].properties,
129
- ]),
130
- ];
131
- };
132
-
133
- /**
134
- * Constructs the new withInfo function from the parameters of the
135
- * original addWithInfo function.
136
- * @param {CallExpression} addWithInfoExpression - original function
137
- * @returns {CallExpression} the new withInfo function
138
- */
139
- const withInfo = (addWithInfoExpression) => {
140
- const { node } = addWithInfoExpression;
141
- const args = node.arguments;
142
-
143
- // if optional description string is not supplied, the story component becomes second arg
144
- const storyComponent = args[2] ? args[2] : args[1];
145
-
146
- node.callee.property.name = 'add';
147
- node.arguments = [
148
- args[0],
149
- j.callExpression(j.callExpression(j.identifier('withInfo'), getOptions(args)), [
150
- storyComponent,
151
- ]),
152
- ];
153
-
154
- return node;
155
- };
156
-
157
- /**
158
- * Checks for - import { withInfo } from "@storybook/addon-info";
159
- * Adds the import if necessary.
160
- */
161
- const checkWithInfoImport = () => {
162
- const importExists = root
163
- .find(j.ImportDeclaration)
164
- .filter((imp) => imp.node.source.value === '@storybook/addon-info')
165
- .size();
166
-
167
- if (importExists) return;
168
-
169
- root
170
- .find(j.ImportDeclaration)
171
- .at(-1)
172
- .insertAfter(
173
- j.importDeclaration(
174
- [j.importSpecifier(j.identifier('withInfo'))],
175
- j.literal('@storybook/addon-info')
176
- )
177
- );
178
- };
179
-
180
- const addWithInfoExpressions = root.find(j.CallExpression, {
181
- callee: {
182
- property: {
183
- name: 'addWithInfo',
184
- },
185
- },
186
- });
187
-
188
- if (addWithInfoExpressions.size()) {
189
- checkWithInfoImport();
190
- addWithInfoExpressions.replaceWith(withInfo);
191
- }
192
-
193
- return root.toSource();
194
- }
195
-
196
- /* eslint import/prefer-default-export: "off" */
197
-
198
- const TRANSFORM_DIR = `${__dirname}/transforms`;
199
-
200
- function listCodemods() {
201
- return fs
202
- .readdirSync(TRANSFORM_DIR)
203
- .filter((fname) => fname.endsWith('.js'))
204
- .map((fname) => fname.slice(0, -3));
205
- }
206
-
207
- const renameAsync = promisify(fs.rename);
208
-
209
- async function renameFile(file, from, to, { logger }) {
210
- const newFile = file.replace(from, to);
211
- logger.log(`Rename: ${file} ${newFile}`);
212
- return renameAsync(file, newFile);
213
- }
214
-
215
- async function runCodemod(codemod, { glob, logger, dryRun, rename, parser }) {
216
- const codemods = listCodemods();
217
- if (!codemods.includes(codemod)) {
218
- throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);
219
- }
220
-
221
- let renameParts = null;
222
- if (rename) {
223
- renameParts = rename.split(':');
224
- if (renameParts.length !== 2) {
225
- throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);
226
- }
227
- }
228
-
229
- // jscodeshift/prettier know how to handle .ts/.tsx extensions,
230
- // so if the user uses one of those globs, we can auto-infer
231
- let inferredParser = parser;
232
- if (!parser) {
233
- const extension = path.extname(glob).slice(1);
234
- const knownParser = jscodeshiftToPrettierParser(extension);
235
- if (knownParser !== 'babel') inferredParser = extension;
236
- }
237
-
238
- const files = await globby([glob, '!**/node_modules', '!**/dist']);
239
- logger.log(`=> Applying ${codemod}: ${files.length} files`);
240
- if (!dryRun) {
241
- const parserArgs = inferredParser ? ['--parser', inferredParser] : [];
242
- sync(
243
- 'npx',
244
- ['jscodeshift', '-t', `${TRANSFORM_DIR}/${codemod}.js`, ...parserArgs, ...files],
245
- {
246
- stdio: 'inherit',
247
- shell: true,
248
- }
249
- );
250
- }
251
-
252
- if (renameParts) {
253
- const [from, to] = renameParts;
254
- logger.log(`=> Renaming ${rename}: ${files.length} files`);
255
- await Promise.all(
256
- files.map((file) => renameFile(file, new RegExp(`${from}$`), to, { logger }))
257
- );
258
- }
259
- }
260
-
261
- export { listCodemods, packageNames, runCodemod, transformer as updateAddonInfo, transformer$1 as updateOrganisationName };
1
+ export { default as updateAddonInfo } from './transforms/update-addon-info.js';
2
+ export { packageNames, default as updateOrganisationName } from './transforms/update-organisation-name.js';
3
+
4
+ declare function listCodemods(): string[];
5
+ declare function runCodemod(codemod: any, { glob, logger, dryRun, rename, parser }: {
6
+ glob: any;
7
+ logger: any;
8
+ dryRun: any;
9
+ rename: any;
10
+ parser: any;
11
+ }): Promise<void>;
12
+
13
+ export { listCodemods, runCodemod };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var R=Object.create;var l=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var S=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},h=(o,r,t,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of v(r))!C.call(o,n)&&n!==t&&l(o,n,{get:()=>r[n],enumerable:!(a=N(r,n))||a.enumerable});return o};var p=(o,r,t)=>(t=o!=null?R(A(o)):{},h(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),W=o=>h(l({},"__esModule",{value:!0}),o);var z={};S(z,{listCodemods:()=>E,packageNames:()=>m,runCodemod:()=>q,updateAddonInfo:()=>b,updateOrganisationName:()=>y});module.exports=W(z);var u=p(require("fs")),x=p(require("path")),w=require("util"),$=p(require("globby")),I=require("cross-spawn");var _=p(require("lodash/camelCase")),D=p(require("lodash/upperFirst"));function g(o){let r={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return o&&r[o]||"babel"}var m={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function y(o,r){let t=r.jscodeshift,a=Object.keys(m),n=s=>a.find(e=>s.match(e)),c=s=>{let e=n(s);if(e){let i=m[e];return s.replace(e,i)}return s},f=s=>(s.node.source.value=c(s.node.source.value),s.node);return t(o.source).find(t.ImportDeclaration).replaceWith(f).toSource({quote:"single"})}function b(o,r){let t=r.jscodeshift,a=t(o.source),n=e=>e[3]===void 0?e[2]===void 0?[e[0]]:[e[1]]:[t.objectExpression([t.property("init",t.identifier("text"),e[1]),...e[3].properties])],c=e=>{let{node:i}=e,d=i.arguments,k=d[2]?d[2]:d[1];return i.callee.property.name="add",i.arguments=[d[0],t.callExpression(t.callExpression(t.identifier("withInfo"),n(d)),[k])],i},f=()=>{a.find(t.ImportDeclaration).filter(i=>i.node.source.value==="@storybook/addon-info").size()||a.find(t.ImportDeclaration).at(-1).insertAfter(t.importDeclaration([t.importSpecifier(t.identifier("withInfo"))],t.literal("@storybook/addon-info")))},s=a.find(t.CallExpression,{callee:{property:{name:"addWithInfo"}}});return s.size()&&(f(),s.replaceWith(c)),a.toSource()}var j=`${__dirname}/transforms`;function E(){return u.default.readdirSync(j).filter(o=>o.endsWith(".js")).map(o=>o.slice(0,-3))}var F=(0,w.promisify)(u.default.rename);async function O(o,r,t,{logger:a}){let n=o.replace(r,t);return a.log(`Rename: ${o} ${n}`),F(o,n)}async function q(o,{glob:r,logger:t,dryRun:a,rename:n,parser:c}){if(!E().includes(o))throw new Error(`Unknown codemod ${o}. Run --list for options.`);let s=null;if(n&&(s=n.split(":"),s.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${n}"`);let e=c;if(!c){let d=x.default.extname(r).slice(1);g(d)!=="babel"&&(e=d)}let i=await(0,$.default)([r,"!**/node_modules","!**/dist"]);if(t.log(`=> Applying ${o}: ${i.length} files`),!a){let d=e?["--parser",e]:[];(0,I.sync)("npx",["jscodeshift","-t",`${j}/${o}.js`,...d,...i],{stdio:"inherit",shell:!0})}if(s){let[d,k]=s;t.log(`=> Renaming ${n}: ${i.length} files`),await Promise.all(i.map(P=>O(P,new RegExp(`${d}$`),k,{logger:t})))}}0&&(module.exports={listCodemods,packageNames,runCodemod,updateAddonInfo,updateOrganisationName});
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{listCodemods:()=>listCodemods,packageNames:()=>packageNames,runCodemod:()=>runCodemod,updateAddonInfo:()=>transformer2,updateOrganisationName:()=>transformer});module.exports=__toCommonJS(src_exports);var import_fs=__toESM(require("fs")),import_path=__toESM(require("path")),import_util=require("util"),import_globby=__toESM(require("globby")),import_cross_spawn=require("cross-spawn");var import_camelCase=__toESM(require("lodash/camelCase.js")),import_upperFirst=__toESM(require("lodash/upperFirst.js"));function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}function transformer2(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return import_fs.default.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=(0,import_util.promisify)(import_fs.default.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=import_path.default.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await(0,import_globby.default)([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];(0,import_cross_spawn.sync)("npx",["jscodeshift","--no-babel","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}0&&(module.exports={listCodemods,packageNames,runCodemod,updateAddonInfo,updateOrganisationName});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import fs from"fs";import path from"path";import{promisify}from"util";import globby from"globby";import{sync as spawnSync}from"cross-spawn";import camelCase from"lodash/camelCase";import upperFirst from"lodash/upperFirst";function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}function transformer2(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return fs.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=promisify(fs.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=path.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await globby([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];spawnSync("npx",["jscodeshift","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}export{listCodemods,packageNames,runCodemod,transformer2 as updateAddonInfo,transformer as updateOrganisationName};
1
+ import{packageNames,transformer}from"./chunk-3OPQTROG.mjs";import{jscodeshiftToPrettierParser}from"./chunk-HBPKIMKE.mjs";import{transformer as transformer2}from"./chunk-B5FMQ3BX.mjs";import fs from"fs";import path from"path";import{promisify}from"util";import globby from"globby";import{sync as spawnSync}from"cross-spawn";var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return fs.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=promisify(fs.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=path.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await globby([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];spawnSync("npx",["jscodeshift","--no-babel","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}export{listCodemods,packageNames,runCodemod,transformer2 as updateAddonInfo,transformer as updateOrganisationName};
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Adds a `component` parameter for each storiesOf(...) call.
3
+ *
4
+ * For example:
5
+ *
6
+ * input { Button } from './Button';
7
+ * storiesOf('Button', module).add('story', () => <Button label="The Button" />);
8
+ *
9
+ * Becomes:
10
+ *
11
+ * input { Button } from './Button';
12
+ * storiesOf('Button', module)
13
+ * .addParameters({ component: Button })
14
+ * .add('story', () => <Button label="The Button" />);
15
+ *
16
+ * Heuristics:
17
+ * - The storiesOf "kind" name must be Button
18
+ * - Button must be imported in the file
19
+ */
20
+ declare function transformer(file: any, api: any): any;
21
+
22
+ export { transformer as default };
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var add_component_parameters_exports={};__export(add_component_parameters_exports,{default:()=>transformer});module.exports=__toCommonJS(add_component_parameters_exports);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),importMap={};root.find(j.ImportDeclaration).forEach(imp=>imp.node.specifiers.forEach(spec=>{importMap[spec.local.name]=!0}));function getLeafName(string){let parts=string.split(/\/|\.|\|/);return parts[parts.length-1]}function addComponentParameter(call){let{node}=call,leafName=getLeafName(node.arguments[0].value);return j.callExpression(j.memberExpression(node,j.identifier("addParameters")),[j.objectExpression([j.property("init",j.identifier("component"),j.identifier(leafName))])])}return root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type==="Literal").filter(call=>{let leafName=getLeafName(call.node.arguments[0].value);return importMap[leafName]}).replaceWith(addComponentParameter),root.toSource()}0&&(module.exports={});
@@ -0,0 +1 @@
1
+ function transformer(file,api){let j=api.jscodeshift,root=j(file.source),importMap={};root.find(j.ImportDeclaration).forEach(imp=>imp.node.specifiers.forEach(spec=>{importMap[spec.local.name]=!0}));function getLeafName(string){let parts=string.split(/\/|\.|\|/);return parts[parts.length-1]}function addComponentParameter(call){let{node}=call,leafName=getLeafName(node.arguments[0].value);return j.callExpression(j.memberExpression(node,j.identifier("addParameters")),[j.objectExpression([j.property("init",j.identifier("component"),j.identifier(leafName))])])}return root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type==="Literal").filter(call=>{let leafName=getLeafName(call.node.arguments[0].value);return importMap[leafName]}).replaceWith(addComponentParameter),root.toSource()}export{transformer as default};
@@ -0,0 +1,6 @@
1
+ import { FileInfo, API, Options } from 'jscodeshift';
2
+
3
+ declare function transform({ source, path }: FileInfo, api: API, options: Options): string;
4
+ declare const parser = "tsx";
5
+
6
+ export { transform as default, parser };
@@ -0,0 +1 @@
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_2_to_3_exports={};__export(csf_2_to_3_exports,{default:()=>transform,parser:()=>parser});module.exports=__toCommonJS(csf_2_to_3_exports);var import_prettier=__toESM(require("prettier")),t=__toESM(require("@babel/types")),import_csf_tools=require("@storybook/csf-tools"),logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>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,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{var _a;if((_a=csf._meta)!=null&&_a.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source,path},api,options){let csf=(0,import_csf_tools.loadCsf)(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=(0,import_csf_tools.formatCsf)(csf);try{let prettierConfig=import_prettier.default.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=import_prettier.default.format(output,{...prettierConfig,filepath:path})}catch{logger.log(`Failed applying prettier to ${path}.`)}return output}var parser="tsx";0&&(module.exports={parser});
@@ -0,0 +1 @@
1
+ import prettier from"prettier";import*as t from"@babel/types";import{formatCsf,loadCsf}from"@storybook/csf-tools";var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>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,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{if(csf._meta?.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source,path},api,options){let csf=loadCsf(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=formatCsf(csf);try{let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=prettier.format(output,{...prettierConfig,filepath:path})}catch{logger.log(`Failed applying prettier to ${path}.`)}return output}var parser="tsx";export{transform as default,parser};
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Hoist CSF .story annotations
3
+ *
4
+ * For example:
5
+ *
6
+ * ```
7
+ * export const Basic = () => <Button />
8
+ * Basic.story = {
9
+ * name: 'foo',
10
+ * parameters: { ... },
11
+ * decorators = [ ... ],
12
+ * };
13
+ * ```
14
+ *
15
+ * Becomes:
16
+ *
17
+ * ```
18
+ * export const Basic = () => <Button />
19
+ * Basic.storyName = 'foo';
20
+ * Basic.parameters = { ... };
21
+ * Basic.decorators = [ ... ];
22
+ * ```
23
+ */
24
+ declare function transformer(file: any, api: any): any;
25
+
26
+ export { transformer as default };
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_hoist_story_annotations_exports={};__export(csf_hoist_story_annotations_exports,{default:()=>transformer});module.exports=__toCommonJS(csf_hoist_story_annotations_exports);var getContainingStatement=n=>n.node.type.endsWith("Statement")?n:getContainingStatement(n.parent);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),renameKey=exp=>exp.type==="Identifier"&&exp.name==="name"?j.identifier("storyName"):exp;if(root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.type==="ObjectExpression"&&def.node.declaration.properties.map(p=>p.key.name).includes("title")).size()===0)return root.toSource();let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left,right}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.property.type==="Identifier"&&left.property.name==="story"&&right.type==="ObjectExpression"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;right.properties.forEach(prop=>{getContainingStatement(exp).insertBefore(j.assignmentStatement("=",j.memberExpression(left.object,renameKey(prop.key)),prop.value))})}),storyAssignments.remove(),root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.property.type==="Identifier"&&left.object.property.name==="story"&&left.property.type==="Identifier"}).replaceWith(exp=>{let{left,right}=exp.node;return j.assignmentExpression("=",j.memberExpression(left.object.object,renameKey(left.property)),right)}),root.toSource({quote:"single"})}0&&(module.exports={});
@@ -0,0 +1 @@
1
+ var getContainingStatement=n=>n.node.type.endsWith("Statement")?n:getContainingStatement(n.parent);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),renameKey=exp=>exp.type==="Identifier"&&exp.name==="name"?j.identifier("storyName"):exp;if(root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.type==="ObjectExpression"&&def.node.declaration.properties.map(p=>p.key.name).includes("title")).size()===0)return root.toSource();let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left,right}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.property.type==="Identifier"&&left.property.name==="story"&&right.type==="ObjectExpression"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;right.properties.forEach(prop=>{getContainingStatement(exp).insertBefore(j.assignmentStatement("=",j.memberExpression(left.object,renameKey(prop.key)),prop.value))})}),storyAssignments.remove(),root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.property.type==="Identifier"&&left.object.property.name==="story"&&left.property.type==="Identifier"}).replaceWith(exp=>{let{left,right}=exp.node;return j.assignmentExpression("=",j.memberExpression(left.object.object,renameKey(left.property)),right)}),root.toSource({quote:"single"})}export{transformer as default};
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Convert a component's module story file into an MDX file
3
+ *
4
+ * For example:
5
+ *
6
+ * ```
7
+ * input { Button } from './Button';
8
+ * export default {
9
+ * title: 'Button'
10
+ * }
11
+ * export const story = () => <Button label="The Button" />;
12
+ * ```
13
+ *
14
+ * Becomes:
15
+ *
16
+ * ```
17
+ * import { Meta, Story } from '@storybook/addon-docs';
18
+ * input { Button } from './Button';
19
+ *
20
+ * <Meta title='Button' />
21
+ *
22
+ * <Story name='story'>
23
+ * <Button label="The Button" />
24
+ * </Story>
25
+ * ```
26
+ */
27
+ declare function transformer(file: any, api: any): any;
28
+
29
+ export { transformer as default };
@@ -0,0 +1,3 @@
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_to_mdx_exports={};__export(csf_to_mdx_exports,{default:()=>transformer});module.exports=__toCommonJS(csf_to_mdx_exports);var import_recast=require("recast"),import_csf=require("@storybook/csf");function exportMdx(root,options){return root.__paths[0].node.program.body.map(n=>{let{code}=(0,import_recast.prettyPrint)(n,options);return n.type==="JSXElement"?`${code}
2
+ `:code}).join(`
3
+ `)}function parseIncludeExclude(prop){let{code}=(0,import_recast.prettyPrint)(prop,{});return(0,eval)(code)}function transformer(file,api){let j=api.jscodeshift,root=j(file.source),storyKeyToStory={},meta={};function makeAttr(key,val){return j.jsxAttribute(j.jsxIdentifier(key),val.type==="Literal"?val:j.jsxExpressionContainer(val))}function getStoryContents(node){return node.type==="ArrowFunctionExpression"&&node.body.type==="JSXElement"?node.body:j.jsxExpressionContainer(node)}function getName(storyKey){let story=storyKeyToStory[storyKey];if(story){let name=story.properties.find(prop=>prop.key.name==="name");if(name&&name.value.type==="Literal")return name.value.value}return storyKey}function getStoryAttrs(storyKey){let attrs=[],story=storyKeyToStory[storyKey];return story&&story.properties.forEach(prop=>{let{key,value}=prop;key.name!=="name"&&attrs.push(makeAttr(key.name,value))}),attrs}let defaultExportWithTitle=root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.properties.map(p=>p.key.name).includes("title"));if(defaultExportWithTitle.size()===0)return root.toSource();root.find(j.ImportDeclaration).at(-1).insertAfter(j.emptyStatement()).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("Meta")),j.importSpecifier(j.identifier("Story"))],j.literal("@storybook/addon-docs"))),root.find(j.ImportDeclaration).filter(decl=>decl.node.source.value==="react").remove(),defaultExportWithTitle.forEach(exp=>{exp.node.declaration.properties.forEach(p=>{["includeStories","excludeStories"].includes(p.key.name)&&(meta[p.key.name]=parseIncludeExclude(p.value))})});let namedExports=root.find(j.ExportNamedDeclaration);namedExports.forEach(exp=>{let storyKey=exp.node.declaration.declarations[0].id.name;(0,import_csf.isExportStory)(storyKey,meta)&&(storyKeyToStory[storyKey]=null)});let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.object.name in storyKeyToStory&&left.property.type==="Identifier"&&left.property.name==="story"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;storyKeyToStory[left.object.name]=right}),storyAssignments.remove(),defaultExportWithTitle.replaceWith(exp=>{let jsxId=j.jsxIdentifier("Meta"),attrs=[];exp.node.declaration.properties.forEach(prop=>{let{key,value}=prop;["includeStories","excludeStories"].includes(key.name)||attrs.push(makeAttr(key.name,value))});let opening=j.jsxOpeningElement(jsxId,attrs);return opening.selfClosing=!0,j.jsxElement(opening)}),namedExports.replaceWith(exp=>{let storyKey=exp.node.declaration.declarations[0].id.name;if(!(0,import_csf.isExportStory)(storyKey,meta))return exp.node;let jsxId=j.jsxIdentifier("Story"),name=getName(storyKey),attributes=[makeAttr("name",j.literal(name)),...getStoryAttrs(storyKey)],opening=j.jsxOpeningElement(jsxId,attributes),closing=j.jsxClosingElement(jsxId),children=[getStoryContents(exp.node.declaration.declarations[0].init)];return j.jsxElement(opening,closing,children)}),exportMdx(root,{quote:"single",trailingComma:"true",tabWidth:2})}0&&(module.exports={});
@@ -0,0 +1,3 @@
1
+ import{prettyPrint}from"recast";import{isExportStory}from"@storybook/csf";function exportMdx(root,options){return root.__paths[0].node.program.body.map(n=>{let{code}=prettyPrint(n,options);return n.type==="JSXElement"?`${code}
2
+ `:code}).join(`
3
+ `)}function parseIncludeExclude(prop){let{code}=prettyPrint(prop,{});return(0,eval)(code)}function transformer(file,api){let j=api.jscodeshift,root=j(file.source),storyKeyToStory={},meta={};function makeAttr(key,val){return j.jsxAttribute(j.jsxIdentifier(key),val.type==="Literal"?val:j.jsxExpressionContainer(val))}function getStoryContents(node){return node.type==="ArrowFunctionExpression"&&node.body.type==="JSXElement"?node.body:j.jsxExpressionContainer(node)}function getName(storyKey){let story=storyKeyToStory[storyKey];if(story){let name=story.properties.find(prop=>prop.key.name==="name");if(name&&name.value.type==="Literal")return name.value.value}return storyKey}function getStoryAttrs(storyKey){let attrs=[],story=storyKeyToStory[storyKey];return story&&story.properties.forEach(prop=>{let{key,value}=prop;key.name!=="name"&&attrs.push(makeAttr(key.name,value))}),attrs}let defaultExportWithTitle=root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.properties.map(p=>p.key.name).includes("title"));if(defaultExportWithTitle.size()===0)return root.toSource();root.find(j.ImportDeclaration).at(-1).insertAfter(j.emptyStatement()).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("Meta")),j.importSpecifier(j.identifier("Story"))],j.literal("@storybook/addon-docs"))),root.find(j.ImportDeclaration).filter(decl=>decl.node.source.value==="react").remove(),defaultExportWithTitle.forEach(exp=>{exp.node.declaration.properties.forEach(p=>{["includeStories","excludeStories"].includes(p.key.name)&&(meta[p.key.name]=parseIncludeExclude(p.value))})});let namedExports=root.find(j.ExportNamedDeclaration);namedExports.forEach(exp=>{let storyKey=exp.node.declaration.declarations[0].id.name;isExportStory(storyKey,meta)&&(storyKeyToStory[storyKey]=null)});let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.object.name in storyKeyToStory&&left.property.type==="Identifier"&&left.property.name==="story"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;storyKeyToStory[left.object.name]=right}),storyAssignments.remove(),defaultExportWithTitle.replaceWith(exp=>{let jsxId=j.jsxIdentifier("Meta"),attrs=[];exp.node.declaration.properties.forEach(prop=>{let{key,value}=prop;["includeStories","excludeStories"].includes(key.name)||attrs.push(makeAttr(key.name,value))});let opening=j.jsxOpeningElement(jsxId,attrs);return opening.selfClosing=!0,j.jsxElement(opening)}),namedExports.replaceWith(exp=>{let storyKey=exp.node.declaration.declarations[0].id.name;if(!isExportStory(storyKey,meta))return exp.node;let jsxId=j.jsxIdentifier("Story"),name=getName(storyKey),attributes=[makeAttr("name",j.literal(name)),...getStoryAttrs(storyKey)],opening=j.jsxOpeningElement(jsxId,attributes),closing=j.jsxClosingElement(jsxId),children=[getStoryContents(exp.node.declaration.declarations[0].init)];return j.jsxElement(opening,closing,children)}),exportMdx(root,{quote:"single",trailingComma:"true",tabWidth:2})}export{transformer as default};
@@ -0,0 +1,3 @@
1
+ declare function transformer(file: any, api: any): any;
2
+
3
+ export { transformer as default };
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var move_builtin_addons_exports={};__export(move_builtin_addons_exports,{default:()=>transformer});module.exports=__toCommonJS(move_builtin_addons_exports);function transformer(file,api){let j=api.jscodeshift,createImportDeclaration=(specifiers,source)=>j.importDeclaration(specifiers.map(s=>j.importSpecifier(j.identifier(s))),j.literal(source)),deprecates={action:[["action"],"@storybook/addon-actions"],linkTo:[["linkTo"],"@storybook/addon-links"]};return j(file.source).find(j.ImportDeclaration).filter(i=>i.value.source.value==="@storybook/react").forEach(i=>{let importStatement=i.value;importStatement.specifiers=importStatement.specifiers.filter(specifier=>{let item=deprecates[specifier.local.name];if(item){let[specifiers,moduleName]=item;return i.insertAfter(createImportDeclaration(specifiers,moduleName)),!1}return specifier})}).toSource({quote:"single"})}0&&(module.exports={});
@@ -0,0 +1 @@
1
+ function transformer(file,api){let j=api.jscodeshift,createImportDeclaration=(specifiers,source)=>j.importDeclaration(specifiers.map(s=>j.importSpecifier(j.identifier(s))),j.literal(source)),deprecates={action:[["action"],"@storybook/addon-actions"],linkTo:[["linkTo"],"@storybook/addon-links"]};return j(file.source).find(j.ImportDeclaration).filter(i=>i.value.source.value==="@storybook/react").forEach(i=>{let importStatement=i.value;importStatement.specifiers=importStatement.specifiers.filter(specifier=>{let item=deprecates[specifier.local.name];if(item){let[specifiers,moduleName]=item;return i.insertAfter(createImportDeclaration(specifiers,moduleName)),!1}return specifier})}).toSource({quote:"single"})}export{transformer as default};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Convert a legacy story API to component story format
3
+ *
4
+ * For example:
5
+ *
6
+ * ```
7
+ * input { Button } from './Button';
8
+ * storiesOf('Button', module).add('story', () => <Button label="The Button" />);
9
+ * ```
10
+ *
11
+ * Becomes:
12
+ *
13
+ * ```
14
+ * input { Button } from './Button';
15
+ * export default {
16
+ * title: 'Button'
17
+ * }
18
+ * export const story = () => <Button label="The Button" />;
19
+ *
20
+ * NOTES: only support chained storiesOf() calls
21
+ */
22
+ declare function transformer(file: any, api: any, options: any): any;
23
+
24
+ export { transformer as default };
@@ -0,0 +1 @@
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var storiesof_to_csf_exports={};__export(storiesof_to_csf_exports,{default:()=>transformer});module.exports=__toCommonJS(storiesof_to_csf_exports);var import_prettier=__toESM(require("prettier")),import_node_logger=require("@storybook/node-logger"),import_csf=require("@storybook/csf");var import_camelCase=__toESM(require("lodash/camelCase.js")),import_upperFirst=__toESM(require("lodash/upperFirst.js")),sanitizeName=name=>{let key=(0,import_upperFirst.default)((0,import_camelCase.default)(name));return/^\d/.test(key)&&(key=`_${key}`),/^\d/.test(key)&&(key=`_${key}`),key};function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}function transformer(file,api,options){let LITERAL=["ts","tsx"].includes(options.parser)?"StringLiteral":"Literal",j=api.jscodeshift,root=j(file.source);function extractDecorators(parameters){if(!parameters)return{};if(!parameters.properties)return{storyParams:parameters};let storyDecorators=parameters.properties.find(p=>p.key.name==="decorators");if(!storyDecorators)return{storyParams:parameters};storyDecorators=storyDecorators.value;let storyParams={...parameters};return storyParams.properties=storyParams.properties.filter(p=>p.key.name!=="decorators"),storyParams.properties.length===0?{storyDecorators}:{storyParams,storyDecorators}}function convertToModuleExports(path,originalExports2){let base=j(path),statements=[],extraExports=[],decorators=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addDecorator").forEach(add=>{let decorator=add.node.arguments[0];decorators.push(decorator)}),decorators.length>0&&(decorators.reverse(),extraExports.push(j.property("init",j.identifier("decorators"),j.arrayExpression(decorators))));let parameters=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addParameters").forEach(add=>{let params=[...add.node.arguments[0].properties];params.reverse(),params.forEach(prop=>parameters.push(prop))}),parameters.length>0&&(parameters.reverse(),extraExports.push(j.property("init",j.identifier("parameters"),j.objectExpression(parameters)))),originalExports2.length>0&&extraExports.push(j.property("init",j.identifier("excludeStories"),j.arrayExpression(originalExports2.map(exp=>j.literal(exp))))),base.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type===LITERAL).forEach(storiesOf=>{let title=storiesOf.node.arguments[0].value;statements.push(j.exportDefaultDeclaration(j.objectExpression([j.property("init",j.identifier("title"),j.literal(title)),...extraExports])))});let adds=[];base.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).forEach(add=>adds.push(add)),adds.reverse(),adds.push(path);let identifiers=new Set;root.find(j.Identifier).forEach(({value})=>identifiers.add(value.name)),adds.forEach(add=>{let name=add.node.arguments[0].value,key=sanitizeName(name);for(;identifiers.has(key);)key=`_${key}`;identifiers.add(key),(0,import_csf.storyNameFromExport)(key)===name&&(name=null);let val=add.node.arguments[1];statements.push(j.exportDeclaration(!1,j.variableDeclaration("const",[j.variableDeclarator(j.identifier(key),val)])));let storyAnnotations=[];if(name&&storyAnnotations.push(j.property("init",j.identifier("name"),j.literal(name))),add.node.arguments.length>2){let originalStoryParams=add.node.arguments[2],{storyParams,storyDecorators}=extractDecorators(originalStoryParams);storyParams&&storyAnnotations.push(j.property("init",j.identifier("parameters"),storyParams)),storyDecorators&&storyAnnotations.push(j.property("init",j.identifier("decorators"),storyDecorators))}storyAnnotations.length>0&&statements.push(j.assignmentStatement("=",j.memberExpression(j.identifier(key),j.identifier("story")),j.objectExpression(storyAnnotations)))});let stmt=path.parent.node.type==="VariableDeclarator"?path.parent.parent:path.parent;statements.reverse(),statements.forEach(s=>stmt.insertAfter(s)),j(stmt).remove()}let initialStoriesOf=root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf");if(root.find(j.ExportDefaultDeclaration).size()>0)return initialStoriesOf.size()>0&&import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls but existing default export, SKIPPING: '${file.path}'`),root.toSource();let originalExports=[];root.find(j.ExportNamedDeclaration).forEach(exp=>{let{declaration,specifiers}=exp.node;if(declaration){let{id,declarations}=declaration;declarations?declarations.forEach(decl=>{let{name,properties}=decl.id;name?originalExports.push(name):properties&&properties.forEach(prop=>originalExports.push(prop.key.name))}):id&&originalExports.push(id.name)}else specifiers&&specifiers.forEach(spec=>originalExports.push(spec.exported.name))}),root.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).filter(add=>["ExpressionStatement","VariableDeclarator"].includes(add.parentPath.node.type)).forEach(path=>convertToModuleExports(path,originalExports)),root.find(j.ImportSpecifier).filter(spec=>spec.node.imported.name==="storiesOf"&&spec.parent.node.source.value.startsWith("@storybook/")).forEach(spec=>{let toRemove=spec.parent.node.specifiers.length>1?spec:spec.parent;j(toRemove).remove()});let source=root.toSource({trailingComma:!0,quote:"single",tabWidth:2});if(initialStoriesOf.size()>1)return import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`),source;let prettierConfig=import_prettier.default.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};return import_prettier.default.format(source,{...prettierConfig,parser:jscodeshiftToPrettierParser(options.parser)})}0&&(module.exports={});
@@ -0,0 +1 @@
1
+ import{jscodeshiftToPrettierParser,sanitizeName}from"../chunk-HBPKIMKE.mjs";import prettier from"prettier";import{logger}from"@storybook/node-logger";import{storyNameFromExport}from"@storybook/csf";function transformer(file,api,options){let LITERAL=["ts","tsx"].includes(options.parser)?"StringLiteral":"Literal",j=api.jscodeshift,root=j(file.source);function extractDecorators(parameters){if(!parameters)return{};if(!parameters.properties)return{storyParams:parameters};let storyDecorators=parameters.properties.find(p=>p.key.name==="decorators");if(!storyDecorators)return{storyParams:parameters};storyDecorators=storyDecorators.value;let storyParams={...parameters};return storyParams.properties=storyParams.properties.filter(p=>p.key.name!=="decorators"),storyParams.properties.length===0?{storyDecorators}:{storyParams,storyDecorators}}function convertToModuleExports(path,originalExports2){let base=j(path),statements=[],extraExports=[],decorators=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addDecorator").forEach(add=>{let decorator=add.node.arguments[0];decorators.push(decorator)}),decorators.length>0&&(decorators.reverse(),extraExports.push(j.property("init",j.identifier("decorators"),j.arrayExpression(decorators))));let parameters=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addParameters").forEach(add=>{let params=[...add.node.arguments[0].properties];params.reverse(),params.forEach(prop=>parameters.push(prop))}),parameters.length>0&&(parameters.reverse(),extraExports.push(j.property("init",j.identifier("parameters"),j.objectExpression(parameters)))),originalExports2.length>0&&extraExports.push(j.property("init",j.identifier("excludeStories"),j.arrayExpression(originalExports2.map(exp=>j.literal(exp))))),base.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type===LITERAL).forEach(storiesOf=>{let title=storiesOf.node.arguments[0].value;statements.push(j.exportDefaultDeclaration(j.objectExpression([j.property("init",j.identifier("title"),j.literal(title)),...extraExports])))});let adds=[];base.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).forEach(add=>adds.push(add)),adds.reverse(),adds.push(path);let identifiers=new Set;root.find(j.Identifier).forEach(({value})=>identifiers.add(value.name)),adds.forEach(add=>{let name=add.node.arguments[0].value,key=sanitizeName(name);for(;identifiers.has(key);)key=`_${key}`;identifiers.add(key),storyNameFromExport(key)===name&&(name=null);let val=add.node.arguments[1];statements.push(j.exportDeclaration(!1,j.variableDeclaration("const",[j.variableDeclarator(j.identifier(key),val)])));let storyAnnotations=[];if(name&&storyAnnotations.push(j.property("init",j.identifier("name"),j.literal(name))),add.node.arguments.length>2){let originalStoryParams=add.node.arguments[2],{storyParams,storyDecorators}=extractDecorators(originalStoryParams);storyParams&&storyAnnotations.push(j.property("init",j.identifier("parameters"),storyParams)),storyDecorators&&storyAnnotations.push(j.property("init",j.identifier("decorators"),storyDecorators))}storyAnnotations.length>0&&statements.push(j.assignmentStatement("=",j.memberExpression(j.identifier(key),j.identifier("story")),j.objectExpression(storyAnnotations)))});let stmt=path.parent.node.type==="VariableDeclarator"?path.parent.parent:path.parent;statements.reverse(),statements.forEach(s=>stmt.insertAfter(s)),j(stmt).remove()}let initialStoriesOf=root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf");if(root.find(j.ExportDefaultDeclaration).size()>0)return initialStoriesOf.size()>0&&logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls but existing default export, SKIPPING: '${file.path}'`),root.toSource();let originalExports=[];root.find(j.ExportNamedDeclaration).forEach(exp=>{let{declaration,specifiers}=exp.node;if(declaration){let{id,declarations}=declaration;declarations?declarations.forEach(decl=>{let{name,properties}=decl.id;name?originalExports.push(name):properties&&properties.forEach(prop=>originalExports.push(prop.key.name))}):id&&originalExports.push(id.name)}else specifiers&&specifiers.forEach(spec=>originalExports.push(spec.exported.name))}),root.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).filter(add=>["ExpressionStatement","VariableDeclarator"].includes(add.parentPath.node.type)).forEach(path=>convertToModuleExports(path,originalExports)),root.find(j.ImportSpecifier).filter(spec=>spec.node.imported.name==="storiesOf"&&spec.parent.node.source.value.startsWith("@storybook/")).forEach(spec=>{let toRemove=spec.parent.node.specifiers.length>1?spec:spec.parent;j(toRemove).remove()});let source=root.toSource({trailingComma:!0,quote:"single",tabWidth:2});if(initialStoriesOf.size()>1)return logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`),source;let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};return prettier.format(source,{...prettierConfig,parser:jscodeshiftToPrettierParser(options.parser)})}export{transformer as default};
@@ -0,0 +1,27 @@
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
+ declare function transformer(file: any, api: any): any;
26
+
27
+ export { transformer as default };
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var update_addon_info_exports={};__export(update_addon_info_exports,{default:()=>transformer});module.exports=__toCommonJS(update_addon_info_exports);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}0&&(module.exports={});