or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

config-management.mdcsf-processing.mdindex.mdstory-enhancement.mdtesting-integration.md

csf-processing.mddocs/

0

# CSF File Processing

1

2

Core functionality for parsing, analyzing, and manipulating Component Story Format files. This module provides the essential tools for working with Storybook story files programmatically.

3

4

## Capabilities

5

6

### Loading CSF Files

7

8

Parse CSF code into a structured CsfFile object for analysis and manipulation.

9

10

```typescript { .api }

11

/**

12

* Parse CSF code into a CsfFile instance

13

* @param code - The CSF source code as a string

14

* @param options - Configuration options for parsing

15

* @returns CsfFile instance ready for parsing

16

*/

17

function loadCsf(code: string, options: CsfOptions): CsfFile;

18

19

interface CsfOptions {

20

/** Optional file name for error reporting and source maps */

21

fileName?: string;

22

/** Function to generate story titles, receives user title and returns final title */

23

makeTitle: (userTitle: string) => string;

24

/** Transform inline meta exports to constant declarations for better tooling support */

25

transformInlineMeta?: boolean;

26

}

27

```

28

29

**Usage Examples:**

30

31

```typescript

32

import { loadCsf } from "@storybook/csf-tools";

33

34

// Basic CSF parsing

35

const csfCode = `

36

export default { title: 'Components/Button' };

37

export const Primary = { args: { primary: true } };

38

export const Secondary = { args: { primary: false } };

39

`;

40

41

const csfFile = loadCsf(csfCode, {

42

fileName: 'Button.stories.ts',

43

makeTitle: (userTitle) => userTitle || 'Unknown'

44

});

45

46

// Parse the file to extract stories and metadata

47

const parsed = csfFile.parse();

48

```

49

50

### Reading CSF Files

51

52

Read and parse CSF files directly from the filesystem.

53

54

```typescript { .api }

55

/**

56

* Read and parse a CSF file from the filesystem

57

* @param fileName - Path to the CSF file

58

* @param options - Configuration options for parsing

59

* @returns Promise resolving to parsed CsfFile

60

*/

61

function readCsf(fileName: string, options: CsfOptions): Promise<CsfFile>;

62

```

63

64

**Usage Examples:**

65

66

```typescript

67

import { readCsf } from "@storybook/csf-tools";

68

69

// Read and parse a story file

70

const csfFile = await readCsf('./src/Button.stories.ts', {

71

makeTitle: (userTitle) => `Components/${userTitle}`

72

});

73

74

console.log(csfFile.meta.title); // Access parsed metadata

75

console.log(csfFile.stories); // Access parsed stories

76

```

77

78

### Writing CSF Files

79

80

Write CsfFile objects back to the filesystem as formatted code.

81

82

```typescript { .api }

83

/**

84

* Write a CsfFile to the filesystem

85

* @param csf - The CsfFile instance to write

86

* @param fileName - Optional output file path (uses csf._options.fileName if not provided)

87

* @returns Promise that resolves when file is written

88

*/

89

function writeCsf(csf: CsfFile, fileName?: string): Promise<void>;

90

```

91

92

### Code Generation

93

94

Generate formatted code from CsfFile instances with various formatting options.

95

96

```typescript { .api }

97

/**

98

* Generate formatted code from a CsfFile

99

* @param csf - The CsfFile instance to format

100

* @param options - Babel generator options including source map support

101

* @param code - Optional original code for source map generation

102

* @returns Generated code string or object with source maps

103

*/

104

function formatCsf(

105

csf: CsfFile,

106

options?: GeneratorOptions & { inputSourceMap?: any },

107

code?: string

108

): ReturnType<typeof generate> | string;

109

110

/**

111

* Generate code with style preservation using recast

112

* @param csf - The CsfFile instance to print

113

* @param options - Recast formatting options

114

* @returns Object with code and optional source map

115

*/

116

function printCsf(csf: CsfFile, options?: RecastOptions): PrintResultType;

117

```

118

119

**Usage Examples:**

120

121

```typescript

122

import { formatCsf, printCsf } from "@storybook/csf-tools";

123

124

// Generate clean formatted code

125

const formattedCode = formatCsf(csfFile);

126

127

// Generate code preserving original formatting

128

const { code } = printCsf(csfFile, {

129

tabWidth: 2,

130

useTabs: false

131

});

132

133

// Write to file

134

await writeCsf(csfFile, './output/Button.stories.ts');

135

```

136

137

### CsfFile Class

138

139

The core class for representing and manipulating CSF files.

140

141

```typescript { .api }

142

class CsfFile {

143

/** Babel AST representation of the file */

144

readonly _ast: t.File;

145

/** Parsed metadata from default export */

146

readonly _meta?: StaticMeta;

147

/** Parsed stories keyed by export name */

148

readonly _stories: Record<string, StaticStory>;

149

/** Story export AST nodes */

150

readonly _storyExports: Record<string, t.VariableDeclarator | t.FunctionDeclaration>;

151

/** Import paths found in the file */

152

readonly imports: string[];

153

154

constructor(ast: t.File, options: CsfOptions, file: BabelFile);

155

156

/**

157

* Parse the AST to extract stories and metadata

158

* @returns Parsed CsfFile with IndexedCSFFile interface

159

*/

160

parse(): CsfFile & IndexedCSFFile;

161

162

/**

163

* Get the AST node for a specific story export

164

* @param key - Export name of the story

165

* @returns AST node for the story

166

*/

167

getStoryExport(key: string): t.Node;

168

169

/** Get parsed metadata object */

170

get meta(): StaticMeta | undefined;

171

172

/** Get array of parsed stories */

173

get stories(): StaticStory[];

174

175

/** Get index input objects for all stories */

176

get indexInputs(): IndexInput[];

177

}

178

```

179

180

### Utility Functions

181

182

Helper functions for working with CSF files and AST parsing.

183

184

```typescript { .api }

185

/**

186

* Check if file path matches Storybook preview file pattern

187

* @param filepath - File path to check

188

* @returns True if path is a valid preview file

189

*/

190

function isValidPreviewPath(filepath: string): boolean;

191

192

/**

193

* Parse JavaScript/TypeScript code into Babel AST

194

* Re-exported from @storybook/core/babel for convenience

195

* @param code - Source code to parse

196

* @returns Babel AST representation

197

*/

198

function babelParse(code: string): t.File;

199

```

200

201

## Error Handling

202

203

The CSF processing module defines several error types for different parsing scenarios:

204

205

```typescript { .api }

206

class NoMetaError extends Error {

207

constructor(message: string, ast: t.Node, fileName?: string);

208

}

209

210

class MultipleMetaError extends Error {

211

constructor(message: string, ast: t.Node, fileName?: string);

212

}

213

214

class MixedFactoryError extends Error {

215

constructor(message: string, ast: t.Node, fileName?: string);

216

}

217

218

class BadMetaError extends Error {

219

constructor(message: string, ast: t.Node, fileName?: string);

220

}

221

```

222

223

These errors provide detailed information about parsing failures and include source location data when available.