-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·98 lines (76 loc) · 3.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env node
import fs from 'fs/promises';
import path from 'path';
import { Command } from 'commander';
import OpenAI from 'openai';
import * as dotenv from 'dotenv';
dotenv.config();
const program = new Command();
program
.version('1.0.0')
.description('Generates Storybook stories from a component file.')
.argument('<input>', 'Path to the component file (e.g., example.ts)')
.action(async (input) => {
try {
const sourceCode = await fs.readFile(input, 'utf-8');
const filename = path.basename(input);
const outputFilename = `${path.parse(filename).name}.stories.ts`;
const outputFilePath = path.join(path.dirname(input), outputFilename);
const inputDir = path.dirname(input);
if (!process.env.OPENAI_API_KEY) {
throw new Error('OPENAI_API_KEY environment variable is required.');
}
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Read existing stories files
let existingStoriesContent = "";
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.endsWith('.stories.ts') && file !== outputFilename) {
try {
const filePath = path.join(inputDir, file);
const fileContent = await fs.readFile(filePath, 'utf-8');
const firstTenLines = fileContent.split('\n').slice(0, 10).join('\n');
existingStoriesContent += `\n// File ${inputDir}/${file}:\n${firstTenLines}\n`;
} catch (readError) {
console.error(`Error reading existing stories file ${file}:`, readError.message);
}
}
}
// console.log("Existing Stories Snippets:\n", existingStoriesContent);
const prompt = `
You are a Storybook expert and TypeScript developer. Your task is to generate a complete stories.ts file for the following component:
${sourceCode}
Here are snippets from existing stories files in the same directory that might be helpful to resolve and create correct imports:
${existingStoriesContent}
Requirements:
1. Write the stories in TypeScript.
2. Ensure the stories cover a wide range of use cases, including content-rich edge cases for the component.
3. Output only the raw code for the stories.ts file—no explanations, comments, or markdown formatting.
4. The response must be a valid and functional TypeScript file ready for use in a Storybook environment.
5. The response should not be formatted using markdown or anything similar.
`;
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: prompt }],
});
let generatedStories = completion.choices[0].message.content;
if (!generatedStories) {
throw new Error("No stories were generated by OpenAI")
}
// Remove ```ts from the beginning and ``` from the end
if (generatedStories.startsWith('```ts')) {
generatedStories = generatedStories.substring(5); // Remove ```ts
}
if (generatedStories.endsWith('```')) {
generatedStories = generatedStories.slice(0, -3); // Remove ```
}
await fs.writeFile(outputFilePath, generatedStories, 'utf-8');
console.log(`Stories generated successfully: ${outputFilePath}`);
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
});
program.parse(process.argv);