Socket
Socket
Sign inDemoInstall

@storybook/csf-tools

Package Overview
Dependencies
Maintainers
11
Versions
1087
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@storybook/csf-tools - npm Package Compare versions

Comparing version 8.2.0-alpha.7 to 8.2.0-alpha.8

2

dist/index.js

@@ -17,3 +17,3 @@ "use strict";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,{ConfigFile:()=>ConfigFile,CsfFile:()=>CsfFile,NoMetaError:()=>NoMetaError,babelParse:()=>babelParse,babelParseExpression:()=>babelParseExpression,babelPrint:()=>babelPrint,enrichCsf:()=>enrichCsf,enrichCsfMeta:()=>enrichCsfMeta,enrichCsfStory:()=>enrichCsfStory,extractDescription:()=>extractDescription,extractSource:()=>extractSource,formatConfig:()=>formatConfig,formatCsf:()=>formatCsf,getStorySortParameter:()=>getStorySortParameter,loadConfig:()=>loadConfig,loadCsf:()=>loadCsf,parserOptions:()=>parserOptions,printConfig:()=>printConfig,printCsf:()=>printCsf,readConfig:()=>readConfig,readCsf:()=>readCsf,writeConfig:()=>writeConfig,writeCsf:()=>writeCsf});module.exports=__toCommonJS(src_exports);var import_fs_extra=__toESM(require("fs-extra")),import_ts_dedent=require("ts-dedent"),t2=__toESM(require("@babel/types")),generate=__toESM(require("@babel/generator")),recast2=__toESM(require("recast")),traverse=__toESM(require("@babel/traverse")),import_csf=require("@storybook/csf");var babelParser=__toESM(require("@babel/parser")),recast=__toESM(require("recast"));function parseWithFlowOrTypescript(source,parserOptions2){let parserPlugins=/^\s*\/\/\s*@flow/.test(source)?["flow"]:["typescript"],mergedParserOptions={...parserOptions2,plugins:[...parserOptions2.plugins??[],...parserPlugins]};return babelParser.parse(source,mergedParserOptions)}var parserOptions={sourceType:"module",plugins:["jsx","decorators-legacy","classProperties"],tokens:!0},babelParse=code=>recast.parse(code,{parser:{parse(source){return parseWithFlowOrTypescript(source,parserOptions)}}}),babelPrint=ast=>recast.print(ast,{quote:"single",trailingComma:!0,tabWidth:2,wrapColumn:80,arrowParensAlways:!0}).code,babelParseExpression=code=>babelParser.parseExpression(code,parserOptions);var t=__toESM(require("@babel/types")),findVarInitialization=(identifier3,program)=>{let init=null,declarations=null;return program.body.find(node=>(t.isVariableDeclaration(node)?declarations=node.declarations:t.isExportNamedDeclaration(node)&&t.isVariableDeclaration(node.declaration)&&(declarations=node.declaration.declarations),declarations&&declarations.find(decl=>t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id)&&decl.id.name===identifier3?(init=decl.init,!0):!1))),init};var logger=console;function parseIncludeExclude(prop){if(t2.isArrayExpression(prop))return prop.elements.map(e=>{if(t2.isStringLiteral(e))return e.value;throw new Error(`Expected string literal: ${e}`)});if(t2.isStringLiteral(prop))return new RegExp(prop.value);if(t2.isRegExpLiteral(prop))return new RegExp(prop.pattern,prop.flags);throw new Error(`Unknown include/exclude: ${prop}`)}function parseTags(prop){if(!t2.isArrayExpression(prop))throw new Error("CSF: Expected tags array");return prop.elements.map(e=>{if(t2.isStringLiteral(e))return e.value;throw new Error("CSF: Expected tag to be string literal")})}var formatLocation=(node,fileName)=>{let{line,column}=node.loc?.start||{};return`${fileName||""} (line ${line}, col ${column})`.trim()},isArgsStory=(init,parent,csf)=>{let storyFn=init;if(t2.isCallExpression(init)){let{callee,arguments:bindArguments}=init;if(t2.isProgram(parent)&&t2.isMemberExpression(callee)&&t2.isIdentifier(callee.object)&&t2.isIdentifier(callee.property)&&callee.property.name==="bind"&&(bindArguments.length===0||bindArguments.length===1&&t2.isObjectExpression(bindArguments[0])&&bindArguments[0].properties.length===0)){let boundIdentifier=callee.object.name,template=findVarInitialization(boundIdentifier,parent);template&&(csf._templates[boundIdentifier]=template,storyFn=template)}}return t2.isArrowFunctionExpression(storyFn)||t2.isFunctionDeclaration(storyFn)?storyFn.params.length>0:!1},parseExportsOrder=init=>{if(t2.isArrayExpression(init))return init.elements.map(item=>{if(t2.isStringLiteral(item))return item.value;throw new Error(`Expected string literal named export: ${item}`)});throw new Error(`Expected array of string literals: ${init}`)},sortExports=(exportByName,order)=>order.reduce((acc,name)=>{let namedExport=exportByName[name];return namedExport&&(acc[name]=namedExport),acc},{}),NoMetaError=class extends Error{constructor(message,ast,fileName){super(import_ts_dedent.dedent`

${nodeInfo}
`},propKey=p=>t3.isIdentifier(p.key)?p.key.name:t3.isStringLiteral(p.key)?p.key.value:null,_getPath=(path,node)=>{if(path.length===0)return node;if(t3.isObjectExpression(node)){let[first,...rest]=path,field=node.properties.find(p=>propKey(p)===first);if(field)return _getPath(rest,field.value)}},_getPathProperties=(path,node)=>{if(path.length===0){if(t3.isObjectExpression(node))return node.properties;throw new Error("Expected object expression")}if(t3.isObjectExpression(node)){let[first,...rest]=path,field=node.properties.find(p=>propKey(p)===first);if(field)return rest.length===0?node.properties:_getPathProperties(rest,field.value)}},_findVarDeclarator=(identifier3,program)=>{let declarator=null,declarations=null;return program.body.find(node=>(t3.isVariableDeclaration(node)?declarations=node.declarations:t3.isExportNamedDeclaration(node)&&t3.isVariableDeclaration(node.declaration)&&(declarations=node.declaration.declarations),declarations&&declarations.find(decl=>t3.isVariableDeclarator(decl)&&t3.isIdentifier(decl.id)&&decl.id.name===identifier3?(declarator=decl,!0):!1))),declarator},_findVarInitialization=(identifier3,program)=>_findVarDeclarator(identifier3,program)?.init,_makeObjectExpression=(path,value)=>{if(path.length===0)return value;let[first,...rest]=path,innerExpression=_makeObjectExpression(rest,value);return t3.objectExpression([t3.objectProperty(t3.identifier(first),innerExpression)])},_updateExportNode=(path,expr,existing)=>{let[first,...rest]=path,existingField=existing.properties.find(p=>propKey(p)===first);existingField?t3.isObjectExpression(existingField.value)&&rest.length>0?_updateExportNode(rest,expr,existingField.value):existingField.value=_makeObjectExpression(rest,expr):existing.properties.push(t3.objectProperty(t3.identifier(first),_makeObjectExpression(rest,expr)))},ConfigFile=class{constructor(ast,code,fileName){this._exports={};this._exportDecls={};this.hasDefaultExport=!1;this._ast=ast,this._code=code,this.fileName=fileName}parse(){let self=this;return traverse2.default(this._ast,{ExportDefaultDeclaration:{enter({node,parent}){self.hasDefaultExport=!0;let decl=t3.isIdentifier(node.declaration)&&t3.isProgram(parent)?_findVarInitialization(node.declaration.name,parent):node.declaration;(t3.isTSAsExpression(decl)||t3.isTSSatisfiesExpression(decl))&&(decl=decl.expression),t3.isObjectExpression(decl)?(self._exportsObject=decl,decl.properties.forEach(p=>{let exportName=propKey(p);if(exportName){let exportVal=p.value;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal}})):logger2.warn(getCsfParsingErrorMessage({expectedType:"ObjectExpression",foundType:decl?.type,node:decl||node.declaration}))}},ExportNamedDeclaration:{enter({node,parent}){t3.isVariableDeclaration(node.declaration)?node.declaration.declarations.forEach(decl=>{if(t3.isVariableDeclarator(decl)&&t3.isIdentifier(decl.id)){let{name:exportName}=decl.id,exportVal=decl.init;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal,self._exportDecls[exportName]=decl}}):node.specifiers?node.specifiers.forEach(spec=>{if(t3.isExportSpecifier(spec)&&t3.isIdentifier(spec.local)&&t3.isIdentifier(spec.exported)){let{name:localName}=spec.local,{name:exportName}=spec.exported,decl=_findVarDeclarator(localName,parent);self._exports[exportName]=decl.init,self._exportDecls[exportName]=decl}}):logger2.warn(getCsfParsingErrorMessage({expectedType:"VariableDeclaration",foundType:node.declaration?.type,node:node.declaration}))}},ExpressionStatement:{enter({node,parent}){if(t3.isAssignmentExpression(node.expression)&&node.expression.operator==="="){let{left,right}=node.expression;if(t3.isMemberExpression(left)&&t3.isIdentifier(left.object)&&left.object.name==="module"&&t3.isIdentifier(left.property)&&left.property.name==="exports"){let exportObject=right;t3.isIdentifier(right)&&(exportObject=_findVarInitialization(right.name,parent)),(t3.isTSAsExpression(exportObject)||t3.isTSSatisfiesExpression(exportObject))&&(exportObject=exportObject.expression),t3.isObjectExpression(exportObject)?(self._exportsObject=exportObject,exportObject.properties.forEach(p=>{let exportName=propKey(p);if(exportName){let exportVal=p.value;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal}})):logger2.warn(getCsfParsingErrorMessage({expectedType:"ObjectExpression",foundType:exportObject?.type,node:exportObject}))}}}}}),self}getFieldNode(path){let[root,...rest]=path,exported=this._exports[root];if(exported)return _getPath(rest,exported)}getFieldProperties(path){let[root,...rest]=path,exported=this._exports[root];if(exported)return _getPathProperties(rest,exported)}getFieldValue(path){let node=this.getFieldNode(path);if(node){let{code}=generate2.default(node,{});return(0,eval)(`(() => (${code}))()`)}}getSafeFieldValue(path){try{return this.getFieldValue(path)}catch{}}setFieldNode(path,expr){let[first,...rest]=path,exportNode=this._exports[first];if(this._exportsObject)_updateExportNode(path,expr,this._exportsObject),this._exports[path[0]]=expr;else if(exportNode&&t3.isObjectExpression(exportNode)&&rest.length>0)_updateExportNode(rest,expr,exportNode);else if(exportNode&&rest.length===0&&this._exportDecls[path[0]]){let decl=this._exportDecls[path[0]];decl.init=_makeObjectExpression([],expr)}else{if(this.hasDefaultExport)throw new Error(`Could not set the "${path.join(".")}" field as the default export is not an object in this file.`);{let exportObj=_makeObjectExpression(rest,expr),newExport=t3.exportNamedDeclaration(t3.variableDeclaration("const",[t3.variableDeclarator(t3.identifier(first),exportObj)]));this._exports[first]=exportObj,this._ast.program.body.push(newExport)}}}getNameFromPath(path){let node=this.getFieldNode(path);if(node)return this._getPresetValue(node,"name")}getNamesFromPath(path){let node=this.getFieldNode(path);if(!node)return;let pathNames=[];return t3.isArrayExpression(node)&&node.elements.forEach(element=>{pathNames.push(this._getPresetValue(element,"name"))}),pathNames}_getPnpWrappedValue(node){if(t3.isCallExpression(node)){let arg=node.arguments[0];if(t3.isStringLiteral(arg))return arg.value}}_getPresetValue(node,fallbackProperty){let value;if(t3.isStringLiteral(node)?value=node.value:t3.isObjectExpression(node)&&node.properties.forEach(prop=>{t3.isObjectProperty(prop)&&t3.isIdentifier(prop.key)&&prop.key.name===fallbackProperty&&(t3.isStringLiteral(prop.value)?value=prop.value.value:value=this._getPnpWrappedValue(prop.value)),t3.isObjectProperty(prop)&&t3.isStringLiteral(prop.key)&&prop.key.value==="name"&&t3.isStringLiteral(prop.value)&&(value=prop.value.value)}),!value)throw new Error(`The given node must be a string literal or an object expression with a "${fallbackProperty}" property that is a string literal.`);return value}removeField(path){let removeProperty=(properties2,prop)=>{let index=properties2.findIndex(p=>t3.isIdentifier(p.key)&&p.key.name===prop||t3.isStringLiteral(p.key)&&p.key.value===prop);index>=0&&properties2.splice(index,1)};if(path.length===1){let removedRootProperty=!1;if(this._ast.program.body.forEach(node=>{if(t3.isExportNamedDeclaration(node)&&t3.isVariableDeclaration(node.declaration)){let decl=node.declaration.declarations[0];t3.isIdentifier(decl.id)&&decl.id.name===path[0]&&(this._ast.program.body.splice(this._ast.program.body.indexOf(node),1),removedRootProperty=!0)}if(t3.isExportDefaultDeclaration(node)&&t3.isObjectExpression(node.declaration)){let properties2=node.declaration.properties;removeProperty(properties2,path[0]),removedRootProperty=!0}if(t3.isExpressionStatement(node)&&t3.isAssignmentExpression(node.expression)&&t3.isMemberExpression(node.expression.left)&&t3.isIdentifier(node.expression.left.object)&&node.expression.left.object.name==="module"&&t3.isIdentifier(node.expression.left.property)&&node.expression.left.property.name==="exports"&&t3.isObjectExpression(node.expression.right)){let properties2=node.expression.right.properties;removeProperty(properties2,path[0]),removedRootProperty=!0}}),removedRootProperty)return}let properties=this.getFieldProperties(path);if(properties){let lastPath=path.at(-1);removeProperty(properties,lastPath)}}appendValueToArray(path,value){let node=this.valueToNode(value);node&&this.appendNodeToArray(path,node)}appendNodeToArray(path,node){let current=this.getFieldNode(path);if(!current)this.setFieldNode(path,t3.arrayExpression([node]));else if(t3.isArrayExpression(current))current.elements.push(node);else throw new Error(`Expected array at '${path.join(".")}', got '${current.type}'`)}removeEntryFromArray(path,value){let current=this.getFieldNode(path);if(current)if(t3.isArrayExpression(current)){let index=current.elements.findIndex(element=>t3.isStringLiteral(element)?element.value===value:t3.isObjectExpression(element)?this._getPresetValue(element,"name")===value:this._getPnpWrappedValue(element)===value);if(index>=0)current.elements.splice(index,1);else throw new Error(`Could not find '${value}' in array at '${path.join(".")}'`)}else throw new Error(`Expected array at '${path.join(".")}', got '${current.type}'`)}_inferQuotes(){if(!this._quotes){let occurrences=(this._ast.tokens||[]).slice(0,500).reduce((acc,token)=>(token.type.label==="string"&&(acc[this._code[token.start]]+=1),acc),{"'":0,'"':0});this._quotes=occurrences["'"]>occurrences['"']?"single":"double"}return this._quotes}valueToNode(value){let quotes=this._inferQuotes(),valueNode;if(quotes==="single"){let{code}=generate2.default(t3.valueToNode(value),{jsescOption:{quotes}}),program=babelParse(`const __x = ${code}`);traverse2.default(program,{VariableDeclaration:{enter({node}){node.declarations.length===1&&t3.isVariableDeclarator(node.declarations[0])&&t3.isIdentifier(node.declarations[0].id)&&node.declarations[0].id.name==="__x"&&(valueNode=node.declarations[0].init)}}})}else valueNode=t3.valueToNode(value);return valueNode}setFieldValue(path,value){let valueNode=this.valueToNode(value);if(!valueNode)throw new Error(`Unexpected value ${JSON.stringify(value)}`);this.setFieldNode(path,valueNode)}getBodyDeclarations(){return this._ast.program.body}setBodyDeclaration(declaration){this._ast.program.body.push(declaration)}setRequireImport(importSpecifier2,fromImport){let requireDeclaration=this._ast.program.body.find(node=>t3.isVariableDeclaration(node)&&node.declarations.length===1&&t3.isVariableDeclarator(node.declarations[0])&&t3.isCallExpression(node.declarations[0].init)&&t3.isIdentifier(node.declarations[0].init.callee)&&node.declarations[0].init.callee.name==="require"&&t3.isStringLiteral(node.declarations[0].init.arguments[0])&&node.declarations[0].init.arguments[0].value===fromImport),hasRequireSpecifier=name=>t3.isObjectPattern(requireDeclaration?.declarations[0].id)&&requireDeclaration?.declarations[0].id.properties.find(specifier=>t3.isObjectProperty(specifier)&&t3.isIdentifier(specifier.key)&&specifier.key.name===name),hasDefaultRequireSpecifier=(declaration,name)=>declaration.declarations.length===1&&t3.isVariableDeclarator(declaration.declarations[0])&&t3.isIdentifier(declaration.declarations[0].id)&&declaration.declarations[0].id.name===name;if(typeof importSpecifier2=="string"){let addDefaultRequireSpecifier=()=>{this._ast.program.body.unshift(t3.variableDeclaration("const",[t3.variableDeclarator(t3.identifier(importSpecifier2),t3.callExpression(t3.identifier("require"),[t3.stringLiteral(fromImport)]))]))};requireDeclaration&&hasDefaultRequireSpecifier(requireDeclaration,importSpecifier2)||addDefaultRequireSpecifier()}else requireDeclaration?importSpecifier2.forEach(specifier=>{hasRequireSpecifier(specifier)||requireDeclaration.declarations[0].id.properties.push(t3.objectProperty(t3.identifier(specifier),t3.identifier(specifier),void 0,!0))}):this._ast.program.body.unshift(t3.variableDeclaration("const",[t3.variableDeclarator(t3.objectPattern(importSpecifier2.map(specifier=>t3.objectProperty(t3.identifier(specifier),t3.identifier(specifier),void 0,!0))),t3.callExpression(t3.identifier("require"),[t3.stringLiteral(fromImport)]))]))}setImport(importSpecifier2,fromImport){let getNewImportSpecifier=specifier=>t3.importSpecifier(t3.identifier(specifier),t3.identifier(specifier)),hasImportSpecifier=(declaration,name)=>declaration.specifiers.find(specifier=>t3.isImportSpecifier(specifier)&&t3.isIdentifier(specifier.imported)&&specifier.imported.name===name),hasDefaultImportSpecifier=(declaration,name)=>declaration.specifiers.find(specifier=>t3.isImportDefaultSpecifier(specifier)),importDeclaration2=this._ast.program.body.find(node=>t3.isImportDeclaration(node)&&node.source.value===fromImport);typeof importSpecifier2=="string"?importDeclaration2?hasDefaultImportSpecifier(importDeclaration2,importSpecifier2)||importDeclaration2.specifiers.push(t3.importDefaultSpecifier(t3.identifier(importSpecifier2))):this._ast.program.body.unshift(t3.importDeclaration([t3.importDefaultSpecifier(t3.identifier(importSpecifier2))],t3.stringLiteral(fromImport))):importDeclaration2?importSpecifier2.forEach(specifier=>{hasImportSpecifier(importDeclaration2,specifier)||importDeclaration2.specifiers.push(getNewImportSpecifier(specifier))}):this._ast.program.body.unshift(t3.importDeclaration(importSpecifier2.map(specifier=>t3.importSpecifier(t3.identifier(specifier),t3.identifier(specifier))),t3.stringLiteral(fromImport)))}},loadConfig=(code,fileName)=>{let ast=babelParse(code);return new ConfigFile(ast,code,fileName)},formatConfig=config=>printConfig(config).code,printConfig=(config,options={})=>recast3.print(config._ast,options),readConfig=async fileName=>{let code=(await import_fs_extra2.default.readFile(fileName,"utf-8")).toString();return loadConfig(code,fileName).parse()},writeConfig=async(config,fileName)=>{let fname=fileName||config.fileName;if(!fname)throw new Error("Please specify a fileName for writeConfig");await import_fs_extra2.default.writeFile(fname,formatConfig(config))};var t4=__toESM(require("@babel/types")),traverse3=__toESM(require("@babel/traverse")),generate3=__toESM(require("@babel/generator")),import_ts_dedent3=require("ts-dedent");var logger3=console,getValue=(obj,key)=>{let value;return obj.properties.forEach(p=>{t4.isIdentifier(p.key)&&p.key.name===key&&(value=p.value)}),value},parseValue=value=>{let expr=stripTSModifiers(value);if(t4.isArrayExpression(expr))return expr.elements.map(o=>parseValue(o));if(t4.isObjectExpression(expr))return expr.properties.reduce((acc,p)=>(t4.isIdentifier(p.key)&&(acc[p.key.name]=parseValue(p.value)),acc),{});if(t4.isLiteral(expr))return expr.value;if(t4.isIdentifier(expr))return unsupported(expr.name,!0);throw new Error(`Unknown node type ${expr.type}`)},unsupported=(unexpectedVar,isError)=>{let message=import_ts_dedent3.dedent`
`},propKey=p=>t3.isIdentifier(p.key)?p.key.name:t3.isStringLiteral(p.key)?p.key.value:null,_getPath=(path,node)=>{if(path.length===0)return node;if(t3.isObjectExpression(node)){let[first,...rest]=path,field=node.properties.find(p=>propKey(p)===first);if(field)return _getPath(rest,field.value)}},_getPathProperties=(path,node)=>{if(path.length===0){if(t3.isObjectExpression(node))return node.properties;throw new Error("Expected object expression")}if(t3.isObjectExpression(node)){let[first,...rest]=path,field=node.properties.find(p=>propKey(p)===first);if(field)return rest.length===0?node.properties:_getPathProperties(rest,field.value)}},_findVarDeclarator=(identifier3,program)=>{let declarator=null,declarations=null;return program.body.find(node=>(t3.isVariableDeclaration(node)?declarations=node.declarations:t3.isExportNamedDeclaration(node)&&t3.isVariableDeclaration(node.declaration)&&(declarations=node.declaration.declarations),declarations&&declarations.find(decl=>t3.isVariableDeclarator(decl)&&t3.isIdentifier(decl.id)&&decl.id.name===identifier3?(declarator=decl,!0):!1))),declarator},_findVarInitialization=(identifier3,program)=>_findVarDeclarator(identifier3,program)?.init,_makeObjectExpression=(path,value)=>{if(path.length===0)return value;let[first,...rest]=path,innerExpression=_makeObjectExpression(rest,value);return t3.objectExpression([t3.objectProperty(t3.identifier(first),innerExpression)])},_updateExportNode=(path,expr,existing)=>{let[first,...rest]=path,existingField=existing.properties.find(p=>propKey(p)===first);existingField?t3.isObjectExpression(existingField.value)&&rest.length>0?_updateExportNode(rest,expr,existingField.value):existingField.value=_makeObjectExpression(rest,expr):existing.properties.push(t3.objectProperty(t3.identifier(first),_makeObjectExpression(rest,expr)))},ConfigFile=class{constructor(ast,code,fileName){this._exports={};this._exportDecls={};this.hasDefaultExport=!1;this._ast=ast,this._code=code,this.fileName=fileName}parse(){let self=this;return traverse2.default(this._ast,{ExportDefaultDeclaration:{enter({node,parent}){self.hasDefaultExport=!0;let decl=t3.isIdentifier(node.declaration)&&t3.isProgram(parent)?_findVarInitialization(node.declaration.name,parent):node.declaration;(t3.isTSAsExpression(decl)||t3.isTSSatisfiesExpression(decl))&&(decl=decl.expression),t3.isObjectExpression(decl)?(self._exportsObject=decl,decl.properties.forEach(p=>{let exportName=propKey(p);if(exportName){let exportVal=p.value;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal}})):logger2.warn(getCsfParsingErrorMessage({expectedType:"ObjectExpression",foundType:decl?.type,node:decl||node.declaration}))}},ExportNamedDeclaration:{enter({node,parent}){t3.isVariableDeclaration(node.declaration)?node.declaration.declarations.forEach(decl=>{if(t3.isVariableDeclarator(decl)&&t3.isIdentifier(decl.id)){let{name:exportName}=decl.id,exportVal=decl.init;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal,self._exportDecls[exportName]=decl}}):node.specifiers?node.specifiers.forEach(spec=>{if(t3.isExportSpecifier(spec)&&t3.isIdentifier(spec.local)&&t3.isIdentifier(spec.exported)){let{name:localName}=spec.local,{name:exportName}=spec.exported,decl=_findVarDeclarator(localName,parent);self._exports[exportName]=decl.init,self._exportDecls[exportName]=decl}}):logger2.warn(getCsfParsingErrorMessage({expectedType:"VariableDeclaration",foundType:node.declaration?.type,node:node.declaration}))}},ExpressionStatement:{enter({node,parent}){if(t3.isAssignmentExpression(node.expression)&&node.expression.operator==="="){let{left,right}=node.expression;if(t3.isMemberExpression(left)&&t3.isIdentifier(left.object)&&left.object.name==="module"&&t3.isIdentifier(left.property)&&left.property.name==="exports"){let exportObject=right;t3.isIdentifier(right)&&(exportObject=_findVarInitialization(right.name,parent)),(t3.isTSAsExpression(exportObject)||t3.isTSSatisfiesExpression(exportObject))&&(exportObject=exportObject.expression),t3.isObjectExpression(exportObject)?(self._exportsObject=exportObject,exportObject.properties.forEach(p=>{let exportName=propKey(p);if(exportName){let exportVal=p.value;t3.isIdentifier(exportVal)&&(exportVal=_findVarInitialization(exportVal.name,parent)),self._exports[exportName]=exportVal}})):logger2.warn(getCsfParsingErrorMessage({expectedType:"ObjectExpression",foundType:exportObject?.type,node:exportObject}))}}}}}),self}getFieldNode(path){let[root,...rest]=path,exported=this._exports[root];if(exported)return _getPath(rest,exported)}getFieldProperties(path){let[root,...rest]=path,exported=this._exports[root];if(exported)return _getPathProperties(rest,exported)}getFieldValue(path){let node=this.getFieldNode(path);if(node){let{code}=generate2.default(node,{});return(0,eval)(`(() => (${code}))()`)}}getSafeFieldValue(path){try{return this.getFieldValue(path)}catch{}}setFieldNode(path,expr){let[first,...rest]=path,exportNode=this._exports[first];if(this._exportsObject)_updateExportNode(path,expr,this._exportsObject),this._exports[path[0]]=expr;else if(exportNode&&t3.isObjectExpression(exportNode)&&rest.length>0)_updateExportNode(rest,expr,exportNode);else if(exportNode&&rest.length===0&&this._exportDecls[path[0]]){let decl=this._exportDecls[path[0]];decl.init=_makeObjectExpression([],expr)}else{if(this.hasDefaultExport)throw new Error(`Could not set the "${path.join(".")}" field as the default export is not an object in this file.`);{let exportObj=_makeObjectExpression(rest,expr),newExport=t3.exportNamedDeclaration(t3.variableDeclaration("const",[t3.variableDeclarator(t3.identifier(first),exportObj)]));this._exports[first]=exportObj,this._ast.program.body.push(newExport)}}}getNameFromPath(path){let node=this.getFieldNode(path);if(node)return this._getPresetValue(node,"name")}getNamesFromPath(path){let node=this.getFieldNode(path);if(!node)return;let pathNames=[];return t3.isArrayExpression(node)&&node.elements.forEach(element=>{pathNames.push(this._getPresetValue(element,"name"))}),pathNames}_getPnpWrappedValue(node){if(t3.isCallExpression(node)){let arg=node.arguments[0];if(t3.isStringLiteral(arg))return arg.value}}_getPresetValue(node,fallbackProperty){let value;if(t3.isStringLiteral(node)?value=node.value:t3.isObjectExpression(node)&&node.properties.forEach(prop=>{t3.isObjectProperty(prop)&&t3.isIdentifier(prop.key)&&prop.key.name===fallbackProperty&&(t3.isStringLiteral(prop.value)?value=prop.value.value:value=this._getPnpWrappedValue(prop.value)),t3.isObjectProperty(prop)&&t3.isStringLiteral(prop.key)&&prop.key.value==="name"&&t3.isStringLiteral(prop.value)&&(value=prop.value.value)}),!value)throw new Error(`The given node must be a string literal or an object expression with a "${fallbackProperty}" property that is a string literal.`);return value}removeField(path){let removeProperty=(properties2,prop)=>{let index=properties2.findIndex(p=>t3.isIdentifier(p.key)&&p.key.name===prop||t3.isStringLiteral(p.key)&&p.key.value===prop);index>=0&&properties2.splice(index,1)};if(path.length===1){let removedRootProperty=!1;if(this._ast.program.body.forEach(node=>{if(t3.isExportNamedDeclaration(node)&&t3.isVariableDeclaration(node.declaration)){let decl=node.declaration.declarations[0];t3.isIdentifier(decl.id)&&decl.id.name===path[0]&&(this._ast.program.body.splice(this._ast.program.body.indexOf(node),1),removedRootProperty=!0)}if(t3.isExportDefaultDeclaration(node)){let decl=node.declaration;if(t3.isIdentifier(decl)&&(decl=_findVarInitialization(decl.name,this._ast.program)),(t3.isTSAsExpression(decl)||t3.isTSSatisfiesExpression(decl))&&(decl=decl.expression),t3.isObjectExpression(decl)){let properties2=decl.properties;removeProperty(properties2,path[0]),removedRootProperty=!0}}if(t3.isExpressionStatement(node)&&t3.isAssignmentExpression(node.expression)&&t3.isMemberExpression(node.expression.left)&&t3.isIdentifier(node.expression.left.object)&&node.expression.left.object.name==="module"&&t3.isIdentifier(node.expression.left.property)&&node.expression.left.property.name==="exports"&&t3.isObjectExpression(node.expression.right)){let properties2=node.expression.right.properties;removeProperty(properties2,path[0]),removedRootProperty=!0}}),removedRootProperty)return}let properties=this.getFieldProperties(path);if(properties){let lastPath=path.at(-1);removeProperty(properties,lastPath)}}appendValueToArray(path,value){let node=this.valueToNode(value);node&&this.appendNodeToArray(path,node)}appendNodeToArray(path,node){let current=this.getFieldNode(path);if(!current)this.setFieldNode(path,t3.arrayExpression([node]));else if(t3.isArrayExpression(current))current.elements.push(node);else throw new Error(`Expected array at '${path.join(".")}', got '${current.type}'`)}removeEntryFromArray(path,value){let current=this.getFieldNode(path);if(current)if(t3.isArrayExpression(current)){let index=current.elements.findIndex(element=>t3.isStringLiteral(element)?element.value===value:t3.isObjectExpression(element)?this._getPresetValue(element,"name")===value:this._getPnpWrappedValue(element)===value);if(index>=0)current.elements.splice(index,1);else throw new Error(`Could not find '${value}' in array at '${path.join(".")}'`)}else throw new Error(`Expected array at '${path.join(".")}', got '${current.type}'`)}_inferQuotes(){if(!this._quotes){let occurrences=(this._ast.tokens||[]).slice(0,500).reduce((acc,token)=>(token.type.label==="string"&&(acc[this._code[token.start]]+=1),acc),{"'":0,'"':0});this._quotes=occurrences["'"]>occurrences['"']?"single":"double"}return this._quotes}valueToNode(value){let quotes=this._inferQuotes(),valueNode;if(quotes==="single"){let{code}=generate2.default(t3.valueToNode(value),{jsescOption:{quotes}}),program=babelParse(`const __x = ${code}`);traverse2.default(program,{VariableDeclaration:{enter({node}){node.declarations.length===1&&t3.isVariableDeclarator(node.declarations[0])&&t3.isIdentifier(node.declarations[0].id)&&node.declarations[0].id.name==="__x"&&(valueNode=node.declarations[0].init)}}})}else valueNode=t3.valueToNode(value);return valueNode}setFieldValue(path,value){let valueNode=this.valueToNode(value);if(!valueNode)throw new Error(`Unexpected value ${JSON.stringify(value)}`);this.setFieldNode(path,valueNode)}getBodyDeclarations(){return this._ast.program.body}setBodyDeclaration(declaration){this._ast.program.body.push(declaration)}setRequireImport(importSpecifier2,fromImport){let requireDeclaration=this._ast.program.body.find(node=>t3.isVariableDeclaration(node)&&node.declarations.length===1&&t3.isVariableDeclarator(node.declarations[0])&&t3.isCallExpression(node.declarations[0].init)&&t3.isIdentifier(node.declarations[0].init.callee)&&node.declarations[0].init.callee.name==="require"&&t3.isStringLiteral(node.declarations[0].init.arguments[0])&&node.declarations[0].init.arguments[0].value===fromImport),hasRequireSpecifier=name=>t3.isObjectPattern(requireDeclaration?.declarations[0].id)&&requireDeclaration?.declarations[0].id.properties.find(specifier=>t3.isObjectProperty(specifier)&&t3.isIdentifier(specifier.key)&&specifier.key.name===name),hasDefaultRequireSpecifier=(declaration,name)=>declaration.declarations.length===1&&t3.isVariableDeclarator(declaration.declarations[0])&&t3.isIdentifier(declaration.declarations[0].id)&&declaration.declarations[0].id.name===name;if(typeof importSpecifier2=="string"){let addDefaultRequireSpecifier=()=>{this._ast.program.body.unshift(t3.variableDeclaration("const",[t3.variableDeclarator(t3.identifier(importSpecifier2),t3.callExpression(t3.identifier("require"),[t3.stringLiteral(fromImport)]))]))};requireDeclaration&&hasDefaultRequireSpecifier(requireDeclaration,importSpecifier2)||addDefaultRequireSpecifier()}else requireDeclaration?importSpecifier2.forEach(specifier=>{hasRequireSpecifier(specifier)||requireDeclaration.declarations[0].id.properties.push(t3.objectProperty(t3.identifier(specifier),t3.identifier(specifier),void 0,!0))}):this._ast.program.body.unshift(t3.variableDeclaration("const",[t3.variableDeclarator(t3.objectPattern(importSpecifier2.map(specifier=>t3.objectProperty(t3.identifier(specifier),t3.identifier(specifier),void 0,!0))),t3.callExpression(t3.identifier("require"),[t3.stringLiteral(fromImport)]))]))}setImport(importSpecifier2,fromImport){let getNewImportSpecifier=specifier=>t3.importSpecifier(t3.identifier(specifier),t3.identifier(specifier)),hasImportSpecifier=(declaration,name)=>declaration.specifiers.find(specifier=>t3.isImportSpecifier(specifier)&&t3.isIdentifier(specifier.imported)&&specifier.imported.name===name),hasDefaultImportSpecifier=(declaration,name)=>declaration.specifiers.find(specifier=>t3.isImportDefaultSpecifier(specifier)),importDeclaration2=this._ast.program.body.find(node=>t3.isImportDeclaration(node)&&node.source.value===fromImport);typeof importSpecifier2=="string"?importDeclaration2?hasDefaultImportSpecifier(importDeclaration2,importSpecifier2)||importDeclaration2.specifiers.push(t3.importDefaultSpecifier(t3.identifier(importSpecifier2))):this._ast.program.body.unshift(t3.importDeclaration([t3.importDefaultSpecifier(t3.identifier(importSpecifier2))],t3.stringLiteral(fromImport))):importDeclaration2?importSpecifier2.forEach(specifier=>{hasImportSpecifier(importDeclaration2,specifier)||importDeclaration2.specifiers.push(getNewImportSpecifier(specifier))}):this._ast.program.body.unshift(t3.importDeclaration(importSpecifier2.map(specifier=>t3.importSpecifier(t3.identifier(specifier),t3.identifier(specifier))),t3.stringLiteral(fromImport)))}},loadConfig=(code,fileName)=>{let ast=babelParse(code);return new ConfigFile(ast,code,fileName)},formatConfig=config=>printConfig(config).code,printConfig=(config,options={})=>recast3.print(config._ast,options),readConfig=async fileName=>{let code=(await import_fs_extra2.default.readFile(fileName,"utf-8")).toString();return loadConfig(code,fileName).parse()},writeConfig=async(config,fileName)=>{let fname=fileName||config.fileName;if(!fname)throw new Error("Please specify a fileName for writeConfig");await import_fs_extra2.default.writeFile(fname,formatConfig(config))};var t4=__toESM(require("@babel/types")),traverse3=__toESM(require("@babel/traverse")),generate3=__toESM(require("@babel/generator")),import_ts_dedent3=require("ts-dedent");var logger3=console,getValue=(obj,key)=>{let value;return obj.properties.forEach(p=>{t4.isIdentifier(p.key)&&p.key.name===key&&(value=p.value)}),value},parseValue=value=>{let expr=stripTSModifiers(value);if(t4.isArrayExpression(expr))return expr.elements.map(o=>parseValue(o));if(t4.isObjectExpression(expr))return expr.properties.reduce((acc,p)=>(t4.isIdentifier(p.key)&&(acc[p.key.name]=parseValue(p.value)),acc),{});if(t4.isLiteral(expr))return expr.value;if(t4.isIdentifier(expr))return unsupported(expr.name,!0);throw new Error(`Unknown node type ${expr.type}`)},unsupported=(unexpectedVar,isError)=>{let message=import_ts_dedent3.dedent`
Unexpected '${unexpectedVar}'. Parameter 'options.storySort' should be defined inline e.g.:

@@ -20,0 +20,0 @@

{
"name": "@storybook/csf-tools",
"version": "8.2.0-alpha.7",
"version": "8.2.0-alpha.8",
"description": "Parse and manipulate CSF and Storybook config files",

@@ -49,4 +49,4 @@ "keywords": [

"@babel/types": "^7.24.0",
"@storybook/csf": "^0.1.7",
"@storybook/types": "8.2.0-alpha.7",
"@storybook/csf": "^0.1.8",
"@storybook/types": "8.2.0-alpha.8",
"fs-extra": "^11.1.0",

@@ -73,3 +73,3 @@ "recast": "^0.23.5",

},
"gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae17"
"gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae16"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc