@storytype/cli 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,103 +1,136 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ ATOMIC_LEVELS,
4
+ ATOMIC_LEVEL_KEYS,
5
+ BARREL_FILES,
3
6
  analyzeProject,
4
- displayResults
5
- } from "./chunk-WOGXOJML.js";
7
+ atomicLevelDir,
8
+ componentFileSet,
9
+ detectComponents,
10
+ detectProjectLanguage,
11
+ displayResults,
12
+ findComponentsDirectory,
13
+ isIgnoredDirectory,
14
+ toAtomicLevelFromAlias,
15
+ toKebabCase,
16
+ toPascalCase
17
+ } from "./chunk-PNYCPIWD.js";
6
18
 
7
19
  // src/cli.ts
20
+ import chalk from "chalk";
8
21
  import { Command } from "commander";
9
- import path3 from "path";
22
+ import path4 from "path";
10
23
 
11
24
  // package.json
12
- var version = "0.2.5";
25
+ var version = "0.3.0";
13
26
 
14
27
  // src/generate/Generate.ts
28
+ import fs2 from "fs-extra";
29
+ import path2 from "path";
30
+
31
+ // src/component-scaffold.ts
15
32
  import fs from "fs-extra";
33
+ import Handlebars from "handlebars";
16
34
  import path from "path";
17
35
  import { fileURLToPath } from "url";
18
- import Handlebars from "handlebars";
19
- var __filename = fileURLToPath(import.meta.url);
20
- var __dirname = path.dirname(__filename);
21
- function toKebabCase(str) {
22
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
23
- }
24
- function toPascalCase(str) {
25
- if (/^[A-Z][a-zA-Z0-9]*$/.test(str)) {
26
- return str;
27
- }
28
- const withHyphens = str.replace(/([a-z])([A-Z])/g, "$1-$2");
29
- return withHyphens.split(/[-_\s]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
30
- }
31
- Handlebars.registerHelper("kebabCase", (str) => toKebabCase(str));
32
- Handlebars.registerHelper("pascalCase", (str) => toPascalCase(str));
33
- Handlebars.registerHelper("eq", (a, b) => a === b);
34
- function getTemplateDir() {
35
- const possiblePaths = [
36
- // Development (from dist/generate to src/templates)
37
- path.join(__dirname, "..", "templates", "component"),
38
- // Production build (dist/templates adjacent to dist/)
39
- path.join(__dirname, "..", "..", "templates", "component"),
40
- // From src/generate to src/templates
41
- path.join(__dirname, "..", "..", "src", "templates", "component"),
42
- // Global install
43
- path.join(__dirname, "templates", "component")
36
+ var currentDir = path.dirname(fileURLToPath(import.meta.url));
37
+ Handlebars.registerHelper("kebabCase", (value) => toKebabCase(value));
38
+ Handlebars.registerHelper("pascalCase", (value) => toPascalCase(value));
39
+ var ROLE_TEMPLATES = {
40
+ component: "component.vue.hbs",
41
+ types: "types.ts.hbs",
42
+ test: "spec.ts.hbs",
43
+ stories: "stories.ts.hbs",
44
+ mock: "mock.ts.hbs",
45
+ index: "index.ts.hbs"
46
+ };
47
+ function templateDir() {
48
+ const candidates = [
49
+ path.join(currentDir, "templates", "component"),
50
+ path.join(currentDir, "..", "templates", "component"),
51
+ path.join(currentDir, "..", "..", "templates", "component"),
52
+ path.join(currentDir, "..", "..", "src", "templates", "component")
44
53
  ];
45
- for (const templatePath of possiblePaths) {
46
- if (fs.existsSync(templatePath)) {
47
- return templatePath;
48
- }
54
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
55
+ if (!found) {
56
+ throw new Error(`Template directory not found. Searched: ${candidates.join(", ")}`);
49
57
  }
50
- throw new Error(`Template directory not found. Searched paths: ${possiblePaths.join(", ")}`);
51
- }
52
- async function compileTemplate(templateName, data) {
53
- const templateDir = getTemplateDir();
54
- const templatePath = path.join(templateDir, templateName);
55
- const templateContent = await fs.readFile(templatePath, "utf-8");
56
- const template = Handlebars.compile(templateContent);
57
- return template(data);
58
+ return found;
58
59
  }
59
- async function generateVueTemplate(componentName, type) {
60
- return compileTemplate("component.vue.hbs", { name: componentName, type });
60
+ function entrySpecifier(componentName, entryExtension) {
61
+ return entryExtension === ".vue" ? `./${componentName}.vue` : `./${componentName}`;
61
62
  }
62
- async function generateTypesFile(componentName) {
63
- return compileTemplate("types.ts.hbs", { name: componentName });
63
+ async function renderComponentFile(role, context) {
64
+ const templateName = ROLE_TEMPLATES[role];
65
+ if (!templateName) return null;
66
+ const templatePath = path.join(templateDir(), templateName);
67
+ const template = Handlebars.compile(await fs.readFile(templatePath, "utf-8"));
68
+ return template({
69
+ name: context.componentName,
70
+ entry: entrySpecifier(context.componentName, context.entryExtension),
71
+ section: context.section ?? "",
72
+ hasMock: context.presentRoles.includes("mock"),
73
+ hasStories: context.presentRoles.includes("stories"),
74
+ isVue: context.entryExtension === ".vue"
75
+ });
64
76
  }
65
- async function generateStoriesFile(componentName, type) {
66
- return compileTemplate("stories.ts.hbs", { name: componentName, type });
77
+ async function renderComponentFileByName(fileName, context) {
78
+ const spec = componentFileSet(context.componentName).find(
79
+ (candidate) => candidate.accepted.includes(fileName)
80
+ );
81
+ return spec ? renderComponentFile(spec.role, context) : null;
67
82
  }
68
- async function generateMockFile(componentName) {
69
- return compileTemplate("mock.ts.hbs", { name: componentName });
83
+
84
+ // src/generate/Generate.ts
85
+ var ENTRY_EXTENSION = ".vue";
86
+ function resolveTarget(options) {
87
+ const componentsDir = options.path ?? findComponentsDirectory(process.cwd()) ?? path2.join(process.cwd(), "src", "components");
88
+ const language = detectProjectLanguage(componentsDir);
89
+ const levelDir = path2.join(componentsDir, atomicLevelDir(options.type, language));
90
+ return {
91
+ componentsDir,
92
+ levelDir,
93
+ componentDir: path2.join(levelDir, toKebabCase(options.name)),
94
+ language
95
+ };
70
96
  }
71
- async function generateIndexFile(componentName) {
72
- return compileTemplate("index.ts.hbs", { name: componentName });
97
+ var STORYBOOK_SECTIONS = {
98
+ atoms: { en: "Atoms", pt: "\xC1tomos" },
99
+ molecules: { en: "Molecules", pt: "Mol\xE9culas" },
100
+ organisms: { en: "Organisms", pt: "Organismos" },
101
+ templates: { en: "Templates", pt: "Templates" },
102
+ pages: { en: "Pages", pt: "P\xE1ginas" }
103
+ };
104
+ function storybookSection(level, language) {
105
+ const order = String(ATOMIC_LEVELS[level].order).padStart(2, "0");
106
+ return `${order} - ${STORYBOOK_SECTIONS[level][language]}`;
73
107
  }
74
108
  async function generateComponent(options) {
75
109
  try {
76
110
  const componentName = toPascalCase(options.name);
77
- const dirName = toKebabCase(options.name);
78
- const basePath = options.path || process.cwd();
79
- const componentDir = path.join(basePath, options.type, dirName);
80
- await fs.ensureDir(componentDir);
81
- const files = [];
82
- const vueFile = path.join(componentDir, `${componentName}.vue`);
83
- await fs.writeFile(vueFile, await generateVueTemplate(componentName, options.type));
84
- files.push(vueFile);
85
- const typesFile = path.join(componentDir, `${componentName}.types.ts`);
86
- await fs.writeFile(typesFile, await generateTypesFile(componentName));
87
- files.push(typesFile);
88
- const storiesFile = path.join(componentDir, `${componentName}.stories.ts`);
89
- await fs.writeFile(storiesFile, await generateStoriesFile(componentName, options.type));
90
- files.push(storiesFile);
91
- const mockFile = path.join(componentDir, `${componentName}.mock.ts`);
92
- await fs.writeFile(mockFile, await generateMockFile(componentName));
93
- files.push(mockFile);
94
- const indexFile = path.join(componentDir, "index.ts");
95
- await fs.writeFile(indexFile, await generateIndexFile(componentName));
96
- files.push(indexFile);
97
- return {
98
- success: true,
99
- files
111
+ const target = resolveTarget(options);
112
+ await fs2.ensureDir(target.componentDir);
113
+ const fileSet = componentFileSet(componentName);
114
+ const context = {
115
+ componentName,
116
+ entryExtension: ENTRY_EXTENSION,
117
+ section: storybookSection(options.type, target.language),
118
+ presentRoles: ["component", ...fileSet.map((spec) => spec.role)]
100
119
  };
120
+ const entryFileName = `${componentName}${ENTRY_EXTENSION}`;
121
+ const written = [
122
+ { role: "component", fileName: entryFileName },
123
+ ...fileSet.map((spec) => ({ role: spec.role, fileName: spec.fileName }))
124
+ ];
125
+ const files = [];
126
+ for (const { role, fileName } of written) {
127
+ const content = await renderComponentFile(role, context);
128
+ if (content === null) continue;
129
+ const filePath = path2.join(target.componentDir, fileName);
130
+ await fs2.writeFile(filePath, content);
131
+ files.push(filePath);
132
+ }
133
+ return { success: true, files };
101
134
  } catch (error) {
102
135
  return {
103
136
  success: false,
@@ -108,28 +141,25 @@ async function generateComponent(options) {
108
141
  }
109
142
 
110
143
  // src/normalize-components/NormalizeComponents.ts
111
- import fs2 from "fs-extra";
112
- import path2 from "path";
113
144
  import { exec } from "child_process";
145
+ import fs3 from "fs-extra";
146
+ import path3 from "path";
114
147
  import { promisify } from "util";
148
+
149
+ // src/assert-never.ts
150
+ function assertNever(value, context = "value") {
151
+ throw new Error(`Unhandled ${context}: ${JSON.stringify(value)}`);
152
+ }
153
+
154
+ // src/normalize-components/NormalizeComponents.ts
115
155
  var execAsync = promisify(exec);
116
156
  function isCaseOnlyChange(from, to) {
117
157
  return from.toLowerCase() === to.toLowerCase() && from !== to;
118
158
  }
119
- function toKebabCase2(str) {
120
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
121
- }
122
- function toPascalCase2(str) {
123
- if (/^[A-Z][a-zA-Z0-9]*$/.test(str)) {
124
- return str;
125
- }
126
- const withHyphens = str.replace(/([a-z])([A-Z])/g, "$1-$2");
127
- return withHyphens.split(/[-_\s]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
128
- }
129
159
  async function isGitTracked(filePath) {
130
160
  try {
131
161
  const { stdout } = await execAsync(`git ls-files --error-unmatch "${filePath}"`, {
132
- cwd: path2.dirname(filePath)
162
+ cwd: path3.dirname(filePath)
133
163
  });
134
164
  return stdout.trim().length > 0;
135
165
  } catch {
@@ -137,162 +167,239 @@ async function isGitTracked(filePath) {
137
167
  }
138
168
  }
139
169
  async function gitMoveManual(fromPath, toPath, isCaseOnly) {
140
- const cwd = path2.dirname(fromPath);
170
+ const cwd = path3.dirname(fromPath);
141
171
  if (isCaseOnly) {
142
172
  const tempPath = `${toPath}-temp-rename`;
143
- await fs2.move(fromPath, tempPath);
144
- await fs2.move(tempPath, toPath);
173
+ await fs3.move(fromPath, tempPath);
174
+ await fs3.move(tempPath, toPath);
145
175
  } else {
146
- await fs2.move(fromPath, toPath);
176
+ await fs3.move(fromPath, toPath);
147
177
  }
148
178
  try {
149
179
  const repoRoot = (await execAsync("git rev-parse --show-toplevel", { cwd })).stdout.trim();
150
- const relativeFrom = path2.relative(repoRoot, fromPath);
151
- const relativeTo = path2.relative(repoRoot, toPath);
152
- await execAsync(`git rm --cached "${relativeFrom}"`, { cwd: repoRoot });
180
+ const resolve = async (target) => path3.join(await fs3.realpath(path3.dirname(target)), path3.basename(target));
181
+ const relativeFrom = path3.relative(repoRoot, await resolve(fromPath));
182
+ const relativeTo = path3.relative(repoRoot, await resolve(toPath));
183
+ await execAsync(`git rm --cached -r "${relativeFrom}"`, { cwd: repoRoot });
153
184
  await execAsync(`git add "${relativeTo}"`, { cwd: repoRoot });
154
185
  } catch (error) {
155
186
  console.warn(`Aviso: N\xE3o foi poss\xEDvel atualizar o \xEDndice Git para ${fromPath}`);
156
187
  }
157
188
  }
158
- function getComponentBaseName(filePath) {
159
- const fileName = path2.basename(filePath);
160
- return fileName.replace(/\.(types|stories|story|spec|test|mock)\.(ts|tsx|js|jsx)$/, "").replace(/\.(ts|tsx|js|jsx|vue)$/, "");
189
+ var IMPORT_BEARING_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".vue"];
190
+ var RESOLVABLE_EXTENSIONS = [".vue", ".ts", ".tsx", ".js", ".jsx"];
191
+ var RELATIVE_IMPORT_PATTERN = /(from|import)(\s+)(['"])(\.[^'"]*)\3/g;
192
+ async function findImportReferences(components, rootDir) {
193
+ const grouped = /* @__PURE__ */ new Map();
194
+ for (const component of components) {
195
+ grouped.set(component, []);
196
+ }
197
+ const moveIndex = /* @__PURE__ */ new Map();
198
+ for (const component of components) {
199
+ for (const file of component.files) {
200
+ if (file.currentPath !== file.targetPath) {
201
+ moveIndex.set(file.currentPath, { targetPath: file.targetPath, component });
202
+ }
203
+ }
204
+ }
205
+ if (moveIndex.size === 0) return grouped;
206
+ for (const filePath of await collectScannableFiles(rootDir)) {
207
+ let content;
208
+ try {
209
+ content = await fs3.readFile(filePath, "utf-8");
210
+ } catch {
211
+ continue;
212
+ }
213
+ const importerMove = moveIndex.get(filePath);
214
+ const importerTarget = importerMove?.targetPath ?? filePath;
215
+ for (const match of content.matchAll(RELATIVE_IMPORT_PATTERN)) {
216
+ const [statement, keyword, spacing, quote, specifier] = match;
217
+ const resolved = resolveSpecifier(filePath, specifier);
218
+ if (!resolved) continue;
219
+ const targetMove = moveIndex.get(resolved);
220
+ if (!importerMove && !targetMove) continue;
221
+ const newSpecifier = buildSpecifier(
222
+ importerTarget,
223
+ targetMove?.targetPath ?? resolved,
224
+ specifier,
225
+ resolved
226
+ );
227
+ if (newSpecifier === specifier) continue;
228
+ const owner = targetMove?.component ?? importerMove?.component;
229
+ if (!owner) continue;
230
+ grouped.get(owner)?.push({
231
+ filePath,
232
+ line: content.substring(0, match.index).split("\n").length,
233
+ currentImport: statement,
234
+ newImport: `${keyword}${spacing}${quote}${newSpecifier}${quote}`
235
+ });
236
+ }
237
+ }
238
+ return grouped;
239
+ }
240
+ async function collectScannableFiles(rootDir) {
241
+ const files = [];
242
+ async function walk(dirPath) {
243
+ let entries;
244
+ try {
245
+ entries = await fs3.readdir(dirPath, { withFileTypes: true });
246
+ } catch {
247
+ return;
248
+ }
249
+ for (const entry of entries) {
250
+ const entryPath = path3.join(dirPath, entry.name);
251
+ if (entry.isDirectory()) {
252
+ if (!isIgnoredDirectory(entry.name)) await walk(entryPath);
253
+ } else if (entry.isFile() && IMPORT_BEARING_EXTENSIONS.includes(path3.extname(entry.name))) {
254
+ files.push(entryPath);
255
+ }
256
+ }
257
+ }
258
+ await walk(rootDir);
259
+ return files;
161
260
  }
162
- function getFileType(fileName) {
163
- if (fileName === "index.ts" || fileName === "index.js") return "index";
164
- if (fileName.includes(".types.")) return "types";
165
- if (fileName.includes(".spec.") || fileName.includes(".test.")) return "test";
166
- if (fileName.includes(".stories.") || fileName.includes(".story.")) return "stories";
167
- if (fileName.includes(".mock.")) return "mock";
168
- if (fileName.endsWith(".vue")) return "component";
169
- return "other";
261
+ function splitSpecifier(specifier) {
262
+ const suffixStart = specifier.search(/[?#]/);
263
+ return suffixStart === -1 ? { specifierPath: specifier, suffix: "" } : { specifierPath: specifier.slice(0, suffixStart), suffix: specifier.slice(suffixStart) };
264
+ }
265
+ function resolveSpecifier(importerPath, specifier) {
266
+ const { specifierPath } = splitSpecifier(specifier);
267
+ const base = path3.resolve(path3.dirname(importerPath), specifierPath);
268
+ const candidates = [
269
+ base,
270
+ ...RESOLVABLE_EXTENSIONS.map((ext) => `${base}${ext}`),
271
+ ...BARREL_FILES.map((barrel) => path3.join(base, barrel))
272
+ ];
273
+ return candidates.find((candidate) => isFile(candidate)) ?? null;
274
+ }
275
+ function isFile(candidate) {
276
+ try {
277
+ return fs3.statSync(candidate).isFile();
278
+ } catch {
279
+ return false;
280
+ }
281
+ }
282
+ function buildSpecifier(importerTarget, target, specifier, resolvedOld) {
283
+ const { specifierPath, suffix } = splitSpecifier(specifier);
284
+ const extension = path3.extname(resolvedOld);
285
+ const wroteExtension = extension.length > 0 && specifierPath.endsWith(extension);
286
+ const wroteDirectory = BARREL_FILES.includes(path3.basename(resolvedOld)) && !wroteExtension;
287
+ let destination = target;
288
+ if (wroteDirectory) {
289
+ destination = path3.dirname(target);
290
+ } else if (!wroteExtension) {
291
+ destination = target.slice(0, -extension.length);
292
+ }
293
+ const relative = path3.relative(path3.dirname(importerTarget), destination);
294
+ const posix = relative.split(path3.sep).join("/");
295
+ return `${posix.startsWith(".") ? posix : `./${posix}`}${suffix}`;
170
296
  }
171
297
  async function analyzeComponentStructure(options) {
172
- const components = [];
173
- const targetPath = path2.resolve(options.path);
298
+ const skippedDirectories = [];
299
+ const rootDir = path3.resolve(options.path);
174
300
  try {
175
- await analyzeDirectory(targetPath, components, options);
301
+ const detected = detectComponents(rootDir);
302
+ const planned = await Promise.all(
303
+ detected.map(async (component) => {
304
+ const conflict = promotionConflict(component);
305
+ if (conflict) {
306
+ if (options.verbose) {
307
+ console.warn(`[storytype] Ignorado: ${conflict.reason}`);
308
+ }
309
+ skippedDirectories.push(conflict);
310
+ return null;
311
+ }
312
+ return planComponent(component, options);
313
+ })
314
+ );
315
+ const components = planned.filter((c) => c !== null);
316
+ const referencesByComponent = await findImportReferences(components, rootDir);
317
+ for (const component of components) {
318
+ component.importReferences = referencesByComponent.get(component) ?? [];
319
+ }
320
+ const allImportReferences = components.flatMap((c) => c.importReferences);
176
321
  return {
177
322
  components,
178
- directoriesToRename: components.filter((c) => c.needsRename).length,
323
+ directoriesToRename: components.filter((c) => c.action === "rename").length,
324
+ componentsToPromote: components.filter((c) => c.action === "promote").length,
179
325
  filesToRename: components.reduce(
180
326
  (sum, c) => sum + c.files.filter((f) => f.currentPath !== f.targetPath).length,
181
327
  0
182
328
  ),
183
329
  filesToCreate: components.reduce((sum, c) => sum + c.missingFiles.length, 0),
184
- importsToUpdate: 0,
185
- // TODO: Implement import detection
330
+ importsToUpdate: allImportReferences.length,
331
+ importReferences: allImportReferences,
332
+ skippedDirectories,
186
333
  success: true
187
334
  };
188
335
  } catch (error) {
189
336
  return {
190
337
  components: [],
191
338
  directoriesToRename: 0,
339
+ componentsToPromote: 0,
192
340
  filesToRename: 0,
193
341
  filesToCreate: 0,
194
342
  importsToUpdate: 0,
343
+ importReferences: [],
344
+ skippedDirectories: [],
195
345
  success: false,
196
346
  error: error instanceof Error ? error.message : String(error)
197
347
  };
198
348
  }
199
349
  }
200
- async function analyzeDirectory(dirPath, components, options) {
201
- const entries = await fs2.readdir(dirPath, { withFileTypes: true });
202
- const vueFiles = entries.filter((e) => e.isFile() && e.name.endsWith(".vue"));
203
- if (vueFiles.length > 0) {
204
- const componentFile = vueFiles[0];
205
- const componentName = getComponentBaseName(componentFile.name);
206
- const pascalComponentName = toPascalCase2(componentName);
207
- const dirName = path2.basename(dirPath);
208
- const expectedDirName = toKebabCase2(dirName);
209
- const needsRename = dirName !== expectedDirName;
210
- const files = [];
211
- const existingFileNames = /* @__PURE__ */ new Set();
212
- for (const entry of entries) {
213
- if (entry.isFile()) {
214
- const currentPath = path2.join(dirPath, entry.name);
215
- const fileType = getFileType(entry.name);
216
- const baseName = getComponentBaseName(entry.name);
217
- const pascalName = toPascalCase2(baseName);
218
- let targetName = entry.name;
219
- if (fileType === "component" || fileType === "types" || fileType === "test" || fileType === "stories" || fileType === "mock") {
220
- targetName = entry.name.replace(baseName, pascalName);
221
- }
222
- const targetPath = needsRename ? path2.join(path2.dirname(dirPath), expectedDirName, targetName) : path2.join(dirPath, targetName);
223
- files.push({
224
- currentPath,
225
- targetPath,
226
- isGitTracked: await isGitTracked(currentPath),
227
- type: fileType
228
- });
229
- existingFileNames.add(entry.name);
230
- }
231
- }
232
- const missingFiles = [];
233
- if (!existingFileNames.has("index.ts") && !existingFileNames.has("index.js")) {
234
- missingFiles.push("index.ts");
235
- }
236
- if (!existingFileNames.has(`${pascalComponentName}.types.ts`)) {
237
- missingFiles.push(`${pascalComponentName}.types.ts`);
238
- }
239
- if (!existingFileNames.has(`${pascalComponentName}.spec.ts`) && !existingFileNames.has(`${pascalComponentName}.test.ts`)) {
240
- missingFiles.push(`${pascalComponentName}.spec.ts`);
241
- }
242
- components.push({
243
- currentPath: dirPath,
244
- targetPath: needsRename ? path2.join(path2.dirname(dirPath), expectedDirName) : dirPath,
245
- componentName: pascalComponentName,
246
- files,
247
- missingFiles,
248
- needsRename
249
- });
250
- }
251
- for (const entry of entries) {
252
- if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
253
- await analyzeDirectory(path2.join(dirPath, entry.name), components, options);
254
- }
255
- }
256
- }
257
- function generateFileContent(fileName, componentName) {
258
- if (fileName === "index.ts") {
259
- return `export * from './${componentName}.types';
260
- export { default } from './${componentName}.vue';
261
- `;
262
- }
263
- if (fileName.endsWith(".types.ts")) {
264
- return `export interface ${componentName}Type {
265
- models: ${componentName}Models;
266
- props: ${componentName}Props;
267
- emits: ${componentName}Emits;
350
+ function promotionConflict(component) {
351
+ if (component.action !== "promote") return null;
352
+ if (!fs3.existsSync(component.targetDir)) return null;
353
+ return {
354
+ path: component.currentDir,
355
+ reason: `"${component.name}" est\xE1 solto em ${path3.basename(component.currentDir)}/ mas ${path3.basename(component.targetDir)}/ j\xE1 existe \u2014 mova os arquivos manualmente`
356
+ };
268
357
  }
269
-
270
- export interface ${componentName}Models {
271
- //TODO: Add models here
358
+ async function planComponent(component, options) {
359
+ const scope = options.scope ?? "all";
360
+ const movesDirectories = scope !== "files";
361
+ const renamesFiles = scope !== "dirs";
362
+ const targetDir = movesDirectories ? component.targetDir : component.currentDir;
363
+ const files = await Promise.all(
364
+ component.files.map(async (file) => ({
365
+ currentPath: file.path,
366
+ targetPath: path3.join(targetDir, renamesFiles ? file.targetName : file.name),
367
+ isGitTracked: await isGitTracked(file.path),
368
+ type: file.type
369
+ }))
370
+ );
371
+ return {
372
+ currentPath: component.currentDir,
373
+ targetPath: targetDir,
374
+ componentName: component.name,
375
+ files,
376
+ missingFiles: renamesFiles ? findMissingFiles(component) : [],
377
+ action: plannedAction(component, movesDirectories),
378
+ // Filled in once every component's plan is known
379
+ importReferences: []
380
+ };
272
381
  }
273
-
274
- export interface ${componentName}Props {
275
- //TODO: Add props here
382
+ function plannedAction(component, movesDirectories) {
383
+ return movesDirectories ? component.action : "none";
276
384
  }
277
-
278
- export interface ${componentName}Emits {
279
- //TODO: Add emits here
385
+ function findMissingFiles(component) {
386
+ const targetNames = new Set(component.files.map((file) => file.targetName));
387
+ return componentFileSet(component.name).filter((spec) => spec.completesFolder).filter((spec) => !spec.accepted.some((accepted) => targetNames.has(accepted))).map((spec) => spec.fileName);
280
388
  }
281
- `;
282
- }
283
- if (fileName.endsWith(".spec.ts")) {
284
- return `import { describe, it, expect } from 'vitest';
285
- import ${componentName} from './${componentName}.vue';
286
-
287
- describe('${componentName}', () => {
288
- it('should render', () => {
289
- // TODO: Add tests
290
- expect(${componentName}).toBeDefined();
291
- });
292
- });
293
- `;
389
+ async function writeMissingFiles(component) {
390
+ if (component.missingFiles.length === 0) return;
391
+ const entryFile = component.files.find((file) => file.type === "component");
392
+ const presentRoles = component.files.map((file) => file.type);
393
+ const context = {
394
+ componentName: component.componentName,
395
+ entryExtension: entryFile ? path3.extname(entryFile.targetPath) : ".vue",
396
+ presentRoles
397
+ };
398
+ for (const missingFile of component.missingFiles) {
399
+ const content = await renderComponentFileByName(missingFile, context);
400
+ if (content === null) continue;
401
+ await fs3.writeFile(path3.join(component.targetPath, missingFile), content, "utf-8");
294
402
  }
295
- return "";
296
403
  }
297
404
  async function normalizeComponents(options) {
298
405
  const analysis = await analyzeComponentStructure(options);
@@ -300,66 +407,32 @@ async function normalizeComponents(options) {
300
407
  return analysis;
301
408
  }
302
409
  try {
303
- if (!options.dirsOnly) {
304
- for (const component of analysis.components) {
305
- for (const missingFile of component.missingFiles) {
306
- const targetPath = component.needsRename ? path2.join(component.targetPath, missingFile) : path2.join(component.currentPath, missingFile);
307
- const content = generateFileContent(missingFile, component.componentName);
308
- if (component.needsRename) {
309
- continue;
310
- }
311
- await fs2.writeFile(targetPath, content, "utf-8");
312
- }
410
+ for (const component of analysis.components) {
411
+ switch (component.action) {
412
+ case "promote":
413
+ await promoteComponent(component);
414
+ break;
415
+ case "rename":
416
+ await moveDirectory(component);
417
+ break;
418
+ case "none":
419
+ break;
420
+ default:
421
+ assertNever(component.action, "component action");
313
422
  }
314
423
  }
315
- if (!options.filesOnly) {
316
- for (const component of analysis.components) {
317
- if (component.needsRename) {
318
- const hasGitFiles = component.files.some((f) => f.isGitTracked);
319
- const isCaseOnly = isCaseOnlyChange(component.currentPath, component.targetPath);
320
- if (hasGitFiles) {
321
- await gitMoveManual(component.currentPath, component.targetPath, isCaseOnly);
322
- } else {
323
- if (isCaseOnly) {
324
- const tempPath = `${component.targetPath}-temp-rename`;
325
- await fs2.move(component.currentPath, tempPath);
326
- await fs2.move(tempPath, component.targetPath);
327
- } else {
328
- await fs2.move(component.currentPath, component.targetPath);
329
- }
330
- }
331
- for (const missingFile of component.missingFiles) {
332
- const targetPath = path2.join(component.targetPath, missingFile);
333
- const content = generateFileContent(missingFile, component.componentName);
334
- await fs2.writeFile(targetPath, content, "utf-8");
335
- }
336
- }
424
+ for (const component of analysis.components) {
425
+ if (component.action === "promote") continue;
426
+ for (const file of component.files) {
427
+ const currentPath = path3.join(component.targetPath, path3.basename(file.currentPath));
428
+ if (path3.basename(currentPath) === path3.basename(file.targetPath)) continue;
429
+ await moveFile(currentPath, file.targetPath, file.isGitTracked);
337
430
  }
338
431
  }
339
- if (!options.dirsOnly) {
340
- for (const component of analysis.components) {
341
- const currentDir = component.needsRename && !options.filesOnly ? component.targetPath : component.currentPath;
342
- for (const file of component.files) {
343
- const currentFilePath = component.needsRename && !options.filesOnly ? path2.join(currentDir, path2.basename(file.currentPath)) : file.currentPath;
344
- const targetFilePath = component.needsRename && !options.filesOnly ? file.targetPath : path2.join(currentDir, path2.basename(file.targetPath));
345
- if (path2.basename(currentFilePath) === path2.basename(targetFilePath)) {
346
- continue;
347
- }
348
- const isCaseOnly = isCaseOnlyChange(currentFilePath, targetFilePath);
349
- if (file.isGitTracked) {
350
- await gitMoveManual(currentFilePath, targetFilePath, isCaseOnly);
351
- } else {
352
- if (isCaseOnly) {
353
- const tempPath = `${targetFilePath}-temp-rename`;
354
- await fs2.move(currentFilePath, tempPath);
355
- await fs2.move(tempPath, targetFilePath);
356
- } else {
357
- await fs2.move(currentFilePath, targetFilePath);
358
- }
359
- }
360
- }
361
- }
432
+ for (const component of analysis.components) {
433
+ await writeMissingFiles(component);
362
434
  }
435
+ await applyImportReferences(analysis.components);
363
436
  return {
364
437
  ...analysis,
365
438
  success: true
@@ -372,28 +445,75 @@ async function normalizeComponents(options) {
372
445
  };
373
446
  }
374
447
  }
448
+ async function promoteComponent(component) {
449
+ await fs3.ensureDir(component.targetPath);
450
+ for (const file of component.files) {
451
+ await moveFile(file.currentPath, file.targetPath, file.isGitTracked);
452
+ }
453
+ }
454
+ async function moveDirectory(component) {
455
+ const isCaseOnly = isCaseOnlyChange(component.currentPath, component.targetPath);
456
+ if (component.files.some((f) => f.isGitTracked)) {
457
+ await gitMoveManual(component.currentPath, component.targetPath, isCaseOnly);
458
+ return;
459
+ }
460
+ await moveOnDisk(component.currentPath, component.targetPath, isCaseOnly);
461
+ }
462
+ async function moveFile(fromPath, toPath, isGitTracked2) {
463
+ if (fromPath === toPath) return;
464
+ const isCaseOnly = isCaseOnlyChange(fromPath, toPath);
465
+ if (isGitTracked2) {
466
+ await gitMoveManual(fromPath, toPath, isCaseOnly);
467
+ return;
468
+ }
469
+ await moveOnDisk(fromPath, toPath, isCaseOnly);
470
+ }
471
+ async function moveOnDisk(fromPath, toPath, isCaseOnly) {
472
+ if (!isCaseOnly) {
473
+ await fs3.move(fromPath, toPath);
474
+ return;
475
+ }
476
+ const tempPath = `${toPath}-temp-rename`;
477
+ await fs3.move(fromPath, tempPath);
478
+ await fs3.move(tempPath, toPath);
479
+ }
480
+ async function applyImportReferences(components) {
481
+ const finalPaths = /* @__PURE__ */ new Map();
482
+ for (const component of components) {
483
+ for (const file of component.files) {
484
+ finalPaths.set(file.currentPath, file.targetPath);
485
+ }
486
+ }
487
+ for (const component of components) {
488
+ for (const reference of component.importReferences) {
489
+ const referencePath = finalPaths.get(reference.filePath) ?? reference.filePath;
490
+ try {
491
+ const content = await fs3.readFile(referencePath, "utf-8");
492
+ const updated = content.replace(reference.currentImport, reference.newImport);
493
+ if (updated !== content) {
494
+ await fs3.writeFile(referencePath, updated, "utf-8");
495
+ }
496
+ } catch {
497
+ }
498
+ }
499
+ }
500
+ }
375
501
 
376
502
  // src/cli.ts
377
- import chalk from "chalk";
378
503
  var program = new Command();
504
+ function totalChanges(report) {
505
+ return report.directoriesToRename + report.componentsToPromote + report.filesToRename + report.filesToCreate;
506
+ }
379
507
  program.name("storytype").description("Ferramenta CLI para criar componentes Storytype").version(version);
380
- program.command("generate <type> <name>").alias("g").description("Gerar um novo componente (atomo, molecula, organismo, template)").option("-p, --path <path>", "Caminho customizado para o componente").action(async (type, name, options) => {
381
- const typeMap = {
382
- atomo: "atomos",
383
- atomos: "atomos",
384
- molecula: "moleculas",
385
- moleculas: "moleculas",
386
- organismo: "organismos",
387
- organismos: "organismos",
388
- template: "templates",
389
- templates: "templates"
390
- };
391
- const mappedType = typeMap[type.toLowerCase()];
392
- if (!mappedType) {
508
+ program.command("generate <type> <name>").alias("g").description("Gerar um novo componente (atom, molecule, organism, template, page)").option("-p, --path <path>", "Caminho customizado para o componente").action(async (type, name, options) => {
509
+ const level = toAtomicLevelFromAlias(type);
510
+ if (!level) {
393
511
  console.error(chalk.red(`Tipo de componente inv\xE1lido: ${type}`));
394
- console.log(chalk.yellow("Tipos v\xE1lidos: atomo, molecula, organismo, template"));
512
+ console.log(chalk.yellow(`Tipos v\xE1lidos: ${ATOMIC_LEVEL_KEYS.join(", ")}`));
395
513
  console.log(
396
- chalk.gray("(formas plurais tamb\xE9m aceitas: atomos, moleculas, organismos, templates)")
514
+ chalk.gray(
515
+ "(singular, plural e os nomes em portugu\xEAs tamb\xE9m s\xE3o aceitos: atomo, atomos, ...)"
516
+ )
397
517
  );
398
518
  process.exit(1);
399
519
  }
@@ -401,7 +521,7 @@ program.command("generate <type> <name>").alias("g").description("Gerar um novo
401
521
  try {
402
522
  const result = await generateComponent({
403
523
  name,
404
- type: mappedType,
524
+ type: level,
405
525
  path: options.path
406
526
  });
407
527
  if (result.success) {
@@ -423,13 +543,17 @@ program.command("normalize [path]").description(
423
543
  "Normalizar estrutura de componentes (diret\xF3rios em kebab-case, arquivos em PascalCase)"
424
544
  ).option("-d, --dry-run", "Mostrar mudan\xE7as sem execut\xE1-las").option("--dirs-only", "Normalizar apenas nomes de diret\xF3rios").option("--files-only", "Normalizar apenas nomes de arquivos").option("-v, --verbose", "Mostrar sa\xEDda detalhada").action(
425
545
  async (targetPath, options) => {
546
+ if (options?.dirsOnly && options?.filesOnly) {
547
+ console.error(chalk.red("\u2717 --dirs-only e --files-only sao opostos: escolha um."));
548
+ process.exit(1);
549
+ }
550
+ const scope = options?.dirsOnly ? "dirs" : options?.filesOnly ? "files" : "all";
426
551
  try {
427
552
  console.log(chalk.blue("Analisando estrutura de componentes..."));
428
553
  const result = await normalizeComponents({
429
554
  path: targetPath || process.cwd(),
430
555
  dryRun: options?.dryRun || false,
431
- dirsOnly: options?.dirsOnly || false,
432
- filesOnly: options?.filesOnly || false,
556
+ scope,
433
557
  verbose: options?.verbose || false
434
558
  });
435
559
  if (result.success) {
@@ -437,29 +561,44 @@ program.command("normalize [path]").description(
437
561
  console.log(chalk.gray(`
438
562
  Componentes encontrados: ${result.components.length}`));
439
563
  console.log(chalk.gray(`Diret\xF3rios a renomear: ${result.directoriesToRename}`));
564
+ console.log(
565
+ chalk.gray(`Componentes a mover para pasta pr\xF3pria: ${result.componentsToPromote}`)
566
+ );
440
567
  console.log(chalk.gray(`Arquivos a renomear: ${result.filesToRename}`));
441
568
  console.log(chalk.gray(`Arquivos a criar: ${result.filesToCreate}`));
442
- if ((options?.dryRun || options?.verbose) && result.directoriesToRename + result.filesToRename + result.filesToCreate > 0) {
569
+ if (result.importsToUpdate > 0) {
570
+ console.log(chalk.gray(`Imports a atualizar: ${result.importsToUpdate}`));
571
+ }
572
+ if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
573
+ console.log(chalk.gray(`Diret\xF3rios ignorados: ${result.skippedDirectories.length}`));
574
+ }
575
+ const cwd = process.cwd();
576
+ const relativePath = (absolutePath) => {
577
+ const rel = path4.relative(cwd, absolutePath);
578
+ return rel.startsWith("..") ? absolutePath : rel;
579
+ };
580
+ if ((options?.dryRun || options?.verbose) && totalChanges(result) > 0) {
443
581
  console.log(chalk.cyan("\n\u{1F4CB} Mudan\xE7as detalhadas:\n"));
444
- const cwd = process.cwd();
445
- const relativePath = (absolutePath) => {
446
- const rel = path3.relative(cwd, absolutePath);
447
- return rel.startsWith("..") ? absolutePath : rel;
448
- };
449
582
  result.components.forEach((comp) => {
450
- const hasChanges = comp.needsRename || comp.missingFiles.length > 0 || comp.files.some((f) => f.currentPath !== f.targetPath);
583
+ const hasChanges = comp.action !== "none" || comp.missingFiles.length > 0 || comp.files.some((f) => f.currentPath !== f.targetPath);
451
584
  if (hasChanges) {
452
585
  console.log(chalk.bold(`
453
586
  Componente: ${comp.componentName}`));
454
- if (comp.needsRename) {
587
+ if (comp.action === "promote") {
588
+ console.log(chalk.yellow(` \u{1F4E6} Mover para pasta pr\xF3pria:`));
589
+ console.log(chalk.gray(` ${relativePath(comp.currentPath)}/`));
590
+ console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}/`));
591
+ }
592
+ if (comp.action === "rename") {
455
593
  console.log(chalk.yellow(` \u{1F4C1} Renomear diret\xF3rio:`));
456
594
  console.log(chalk.gray(` ${relativePath(comp.currentPath)}`));
457
595
  console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}`));
458
596
  }
459
597
  const filesToRename = comp.files.filter((f) => f.currentPath !== f.targetPath);
460
598
  if (filesToRename.length > 0) {
599
+ const label = comp.action === "promote" ? "Mover" : "Renomear";
461
600
  console.log(
462
- chalk.yellow(` \u{1F4C4} Renomear arquivo${filesToRename.length > 1 ? "s" : ""}:`)
601
+ chalk.yellow(` \u{1F4C4} ${label} arquivo${filesToRename.length > 1 ? "s" : ""}:`)
463
602
  );
464
603
  filesToRename.forEach((file) => {
465
604
  console.log(chalk.gray(` ${relativePath(file.currentPath)}`));
@@ -471,18 +610,30 @@ Componentes encontrados: ${result.components.length}`));
471
610
  chalk.green(` \u2728 Criar arquivo${comp.missingFiles.length > 1 ? "s" : ""}:`)
472
611
  );
473
612
  comp.missingFiles.forEach((fileName) => {
474
- const targetDir = comp.needsRename ? comp.targetPath : comp.currentPath;
613
+ const targetDir = comp.action === "none" ? comp.currentPath : comp.targetPath;
475
614
  const fullPath = `${targetDir}/${fileName}`;
476
615
  console.log(chalk.gray(` ${relativePath(fullPath)}`));
477
616
  });
478
617
  }
479
618
  }
480
619
  });
620
+ result.importReferences.forEach((ref) => {
621
+ console.log(chalk.yellow(` \u{1F517} Atualizar import:`));
622
+ console.log(chalk.gray(` ${relativePath(ref.filePath)}`));
623
+ console.log(chalk.gray(` ${ref.currentImport} \u2192 ${ref.newImport}`));
624
+ });
625
+ }
626
+ if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
627
+ console.log(chalk.yellow("\n\u26A0\uFE0F Diret\xF3rios ignorados:\n"));
628
+ result.skippedDirectories.forEach((skip) => {
629
+ console.log(chalk.gray(` \u2022 ${relativePath(skip.path)}`));
630
+ console.log(chalk.dim(` Motivo: ${skip.reason}`));
631
+ });
481
632
  }
482
633
  if (options?.dryRun) {
483
634
  console.log(chalk.yellow("\n\u26A0\uFE0F Modo dry-run: nenhuma mudan\xE7a foi feita"));
484
635
  console.log(chalk.gray("Execute sem --dry-run para aplicar as mudan\xE7as\n"));
485
- } else if (result.directoriesToRename + result.filesToRename + result.filesToCreate > 0) {
636
+ } else if (totalChanges(result) > 0) {
486
637
  console.log(chalk.green("\n\u2713 Normaliza\xE7\xE3o conclu\xEDda com sucesso!"));
487
638
  } else {
488
639
  console.log(