@nuvler/cli 0.3.1 → 0.4.1

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.
Files changed (53) hide show
  1. package/README.md +258 -38
  2. package/dist/api/client.js.map +1 -1
  3. package/dist/api/theme-registry.js.map +1 -1
  4. package/dist/commands/theme/create.js +74 -18
  5. package/dist/commands/theme/create.js.map +1 -1
  6. package/dist/commands/theme/migrate.js +117 -0
  7. package/dist/commands/theme/migrate.js.map +1 -0
  8. package/dist/config/developer-session.js.map +1 -1
  9. package/dist/index.js +28 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/migrate/analyzer.js +479 -0
  12. package/dist/migrate/analyzer.js.map +1 -0
  13. package/dist/migrate/asset-copier.js +40 -0
  14. package/dist/migrate/asset-copier.js.map +1 -0
  15. package/dist/migrate/classifier.js +107 -0
  16. package/dist/migrate/classifier.js.map +1 -0
  17. package/dist/migrate/generator.js +500 -0
  18. package/dist/migrate/generator.js.map +1 -0
  19. package/dist/migrate/transformer.js +150 -0
  20. package/dist/migrate/transformer.js.map +1 -0
  21. package/dist/migrate/types.js +2 -0
  22. package/dist/migrate/types.js.map +1 -0
  23. package/dist/migrate/validator.js +40 -0
  24. package/dist/migrate/validator.js.map +1 -0
  25. package/dist/nuvler.js +1643 -33
  26. package/dist/nuvler.js.map +1 -1
  27. package/dist/preview/launcher.js.map +1 -1
  28. package/dist/templates/nuvler-atelier/README.md +17 -1
  29. package/dist/templates/nuvler-atelier/nuvler.theme.json +10 -3
  30. package/dist/templates/nuvler-atelier/package.json +3 -3
  31. package/dist/templates/nuvler-atelier/src/definition.tsx +11 -1
  32. package/dist/templates/nuvler-atelier/src/theme.css +26 -26
  33. package/dist/templates/nuvler-atelier/src/theme.tsx +12 -1
  34. package/dist/templates/nuvler-default/README.md +18 -4
  35. package/dist/templates/nuvler-default/nuvler.theme.json +10 -3
  36. package/dist/templates/nuvler-default/package.json +2 -2
  37. package/dist/templates/nuvler-default/src/definition.ts +11 -0
  38. package/dist/templates/nuvler-default/src/theme-component.tsx +11 -0
  39. package/dist/templates/nuvler-default/src/theme.css +27 -16
  40. package/dist/templates/starter/README.md +18 -1
  41. package/dist/templates/starter/nuvler.theme.json +9 -2
  42. package/dist/templates/starter/package.json +2 -2
  43. package/dist/templates/starter/src/definition.tsx +8 -1
  44. package/dist/templates/starter/src/theme.css +10 -10
  45. package/dist/templates/starter/src/theme.tsx +11 -0
  46. package/package.json +4 -3
  47. package/preview-host/index.html +1 -0
  48. package/preview-host/package.json +1 -1
  49. package/preview-host/public/nuvler-icon.ico +0 -0
  50. package/preview-host/public/nuvler-logo-white.png +0 -0
  51. package/preview-host/src/app/globals.css +28 -0
  52. package/preview-host/src/main.tsx +11 -1
  53. package/preview-host/vendor/theme-runtime/default-theme.tsx +24 -2
package/dist/nuvler.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import { existsSync } from "node:fs";
4
- import { access, chmod, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createHash, randomUUID } from "node:crypto";
@@ -13,6 +13,7 @@ import { stdin, stdout } from "node:process";
13
13
  import os, { tmpdir } from "node:os";
14
14
  import { spawn } from "node:child_process";
15
15
  import { create } from "tar";
16
+ import ts from "typescript";
16
17
  //#region \0rolldown/runtime.js
17
18
  var __defProp = Object.defineProperty;
18
19
  var __exportAll = (all, no_symbols) => {
@@ -28,8 +29,8 @@ var __exportAll = (all, no_symbols) => {
28
29
  //#region src/commands/theme/create.ts
29
30
  var THEME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
30
31
  var NEW_THEME_VERSION = "0.1.0";
31
- var CLI_VERSION_RANGE = "^0.3.1";
32
- var SDK_VERSION_RANGE = "^1.1.0";
32
+ var CLI_VERSION_RANGE = "^0.4.1";
33
+ var SDK_VERSION_RANGE = "^1.2.0";
33
34
  var THEME_TEMPLATES = [
34
35
  {
35
36
  id: "starter",
@@ -128,7 +129,60 @@ async function customizeTemplate(directory, id, name, template) {
128
129
  const definition = await readFile(definitionFile, "utf8");
129
130
  await writeFile(definitionFile, definition.replaceAll("__NUVLER_THEME_ID__", id).replaceAll("__NUVLER_THEME_NAME__", name), "utf8");
130
131
  }
131
- const readme = `# ${name}\n\nTema Nuvler criado a partir do template \`${template}\`.\n\n## Desenvolvimento\n\n\`\`\`bash\nnpm install\nnuvler theme configure --key CHAVE_COPIADA_DO_PAINEL\nnpm run validate\nnpm run dev\n\`\`\`\n\nA chave configura a API e a autenticação global. A seleção local de tenant fica em \`.nuvler/config.json\`, ignorada pelo Git e sem segredos. Não é necessário criar ou editar \`.env\`.\n\nEdite \`src/\` e \`nuvler.theme.json\`. Não edite \`dist\` nem \`artifacts\`, pois essas pastas são geradas pela CLI.\n\n## Build e publicação\n\n\`\`\`bash\nnpm run typecheck\nnpm run build\nnpm run pack\nnpm run publish\n\`\`\`\n\nO artefato será gerado em \`artifacts/${id}-${NEW_THEME_VERSION}.nuvler-theme.tgz\`.\n`;
132
+ const readme = [
133
+ `# ${name}`,
134
+ "",
135
+ `Tema Nuvler criado a partir do template \`${template}\`.`,
136
+ "",
137
+ "## Primeiro uso",
138
+ "",
139
+ "```bash",
140
+ "npm install",
141
+ "npx nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL",
142
+ "npm run validate",
143
+ "npm run dev",
144
+ "```",
145
+ "",
146
+ "A chave configura a API e a autenticação global. O projeto salva apenas",
147
+ "id, slug e nome do tenant em `.nuvler/config.json`, ignorado pelo Git. Não",
148
+ "crie um `.env` para API, token ou tenant.",
149
+ "",
150
+ "Edite `src/` e `nuvler.theme.json`. Não edite `dist` nem `artifacts`, pois",
151
+ "essas pastas são geradas pela CLI.",
152
+ "",
153
+ "## Comandos deste projeto",
154
+ "",
155
+ "| Comando | Finalidade |",
156
+ "| --- | --- |",
157
+ "| `npm run dev` | Inicia o preview com dados públicos da loja configurada |",
158
+ "| `npm run validate` | Valida manifesto, SDK, runtime, entrada e estilos |",
159
+ "| `npm run typecheck` | Verifica os tipos TypeScript |",
160
+ "| `npm run build` | Gera `dist/theme.js`, CSS e assets |",
161
+ "| `npm run pack` | Gera o artefato `.nuvler-theme.tgz` |",
162
+ "| `npm run publish` | Compila e envia ao Theme Registry |",
163
+ "",
164
+ "As opções completas estão em `npx nuvler theme <comando> --help`.",
165
+ "",
166
+ "## Build e publicação",
167
+ "",
168
+ "```bash",
169
+ "npm run typecheck",
170
+ "npm run build",
171
+ "npm run pack",
172
+ "npm run publish",
173
+ "```",
174
+ "",
175
+ `O artefato será gerado em \`artifacts/${id}-${NEW_THEME_VERSION}.nuvler-theme.tgz\`.`,
176
+ "Antes de publicar outra versão, incremente `version` em",
177
+ "`nuvler.theme.json`, pois versões publicadas são imutáveis.",
178
+ "",
179
+ "Por padrão, um projeto configurado publica um tema privado do tenant.",
180
+ "Use `npx nuvler theme publish --visibility unlisted` ou",
181
+ "`npx nuvler theme publish --visibility public` para outra visibilidade.",
182
+ "A opção `--official` é",
183
+ "reservada a uma sessão PLATFORM_ADMIN.",
184
+ ""
185
+ ].join("\n");
132
186
  await writeFile(path.join(directory, "README.md"), readme, "utf8");
133
187
  }
134
188
  async function ensureEmptyTarget(directory) {
@@ -160,21 +214,24 @@ async function themeCreate(options) {
160
214
  });
161
215
  await rename(path.join(directory, "gitignore.template"), path.join(directory, ".gitignore"));
162
216
  await customizeTemplate(directory, id, name, template);
163
- console.log("");
164
- console.log(`✓ Tema criado: ${name} (${id})`);
165
- console.log(`✓ Template: ${template}`);
166
- console.log(`✓ Pasta: ${directory}`);
167
- console.log("");
168
- console.log("Próximos passos:");
169
- console.log(` cd ${path.relative(process.cwd(), directory) || "."}`);
170
- console.log(" npm install");
171
- console.log(" nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL");
172
- console.log(" npm run validate");
173
- console.log(" npm run dev");
174
- console.log(" npm run build");
175
- console.log(" npm run pack");
176
- console.log(" npm run publish");
177
- console.log("");
217
+ if (!options.silent) {
218
+ console.log("");
219
+ console.log(`✓ Tema criado: ${name} (${id})`);
220
+ console.log(`✓ Template: ${template}`);
221
+ console.log(`✓ Pasta: ${directory}`);
222
+ console.log("");
223
+ console.log("Próximos passos:");
224
+ console.log(` cd ${path.relative(process.cwd(), directory) || "."}`);
225
+ console.log(" npm install");
226
+ console.log(" npx nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL");
227
+ console.log(" npm run validate");
228
+ console.log(" npm run dev");
229
+ console.log(" npm run typecheck");
230
+ console.log(" npm run build");
231
+ console.log(" npm run pack");
232
+ console.log(" npm run publish");
233
+ console.log("");
234
+ }
178
235
  }
179
236
  //#endregion
180
237
  //#region src/theme/artifact.ts
@@ -6563,15 +6620,28 @@ config(en_default());
6563
6620
  //#endregion
6564
6621
  //#region ../theme-schema/dist/index.js
6565
6622
  var relativeThemeFileSchema = string$1().trim().min(1).max(240).refine((value) => !value.startsWith("/") && !value.startsWith("\\"), { message: "Use um caminho relativo à pasta do tema" }).refine((value) => !value.split(/[\\/]+/).includes(".."), { message: "O caminho não pode sair da pasta do tema" });
6623
+ var hexColorSchema = string$1().regex(/^#[0-9a-f]{6}$/i, "Use uma cor hexadecimal no formato #RRGGBB");
6624
+ var ThemeSiteColorsSchema = object({
6625
+ primary: hexColorSchema,
6626
+ secondary: hexColorSchema,
6627
+ background: hexColorSchema,
6628
+ text: hexColorSchema,
6629
+ primaryText: hexColorSchema.optional(),
6630
+ secondaryText: hexColorSchema.optional(),
6631
+ accent: hexColorSchema.optional(),
6632
+ surface: hexColorSchema.optional(),
6633
+ surfaceAlt: hexColorSchema.optional(),
6634
+ textMuted: hexColorSchema.optional(),
6635
+ border: hexColorSchema.optional(),
6636
+ headerBackground: hexColorSchema.optional(),
6637
+ headerText: hexColorSchema.optional(),
6638
+ footerBackground: hexColorSchema.optional(),
6639
+ footerText: hexColorSchema.optional()
6640
+ }).strict();
6566
6641
  var ThemePresentationSchema = object({
6567
6642
  description: string$1().trim().min(1).max(500),
6568
6643
  templateId: string$1().trim().min(1).max(80).optional(),
6569
- colors: object({
6570
- primary: string$1().regex(/^#[0-9a-f]{6}$/i),
6571
- secondary: string$1().regex(/^#[0-9a-f]{6}$/i),
6572
- background: string$1().regex(/^#[0-9a-f]{6}$/i),
6573
- text: string$1().regex(/^#[0-9a-f]{6}$/i)
6574
- }).strict(),
6644
+ colors: ThemeSiteColorsSchema,
6575
6645
  layout: object({
6576
6646
  containerWidth: number$1().int().min(960).max(1600),
6577
6647
  borderRadius: number$1().int().min(0).max(32)
@@ -6589,7 +6659,6 @@ var ThemeManifestSchema = object({
6589
6659
  presentation: ThemePresentationSchema.optional()
6590
6660
  }).strict();
6591
6661
  var nullableStringSchema = string$1().nullable();
6592
- var hexColorSchema = string$1().regex(/^#[0-9a-f]{6}$/i, "Use uma cor hexadecimal no formato #RRGGBB");
6593
6662
  var ThemeImageSchema = object({
6594
6663
  url: nullableStringSchema,
6595
6664
  alt: nullableStringSchema,
@@ -6638,12 +6707,7 @@ var ThemeSiteSchema = object({
6638
6707
  }).strict().optional(),
6639
6708
  theme: object({
6640
6709
  id: string$1().trim().min(1).optional(),
6641
- colors: object({
6642
- primary: hexColorSchema,
6643
- secondary: hexColorSchema,
6644
- background: hexColorSchema,
6645
- text: hexColorSchema
6646
- }).strict(),
6710
+ colors: ThemeSiteColorsSchema,
6647
6711
  layout: object({
6648
6712
  containerWidth: number$1().int().min(960).max(1600),
6649
6713
  borderRadius: number$1().int().min(0).max(32)
@@ -7836,6 +7900,1536 @@ async function themePublish(options) {
7836
7900
  console.log("");
7837
7901
  }
7838
7902
  //#endregion
7903
+ //#region src/migrate/analyzer.ts
7904
+ var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
7905
+ ".git",
7906
+ ".next",
7907
+ ".nuxt",
7908
+ ".output",
7909
+ ".turbo",
7910
+ "artifacts",
7911
+ "build",
7912
+ "coverage",
7913
+ "dist",
7914
+ "node_modules",
7915
+ "out"
7916
+ ]);
7917
+ var STYLE_EXTENSIONS = /* @__PURE__ */ new Set([
7918
+ ".css",
7919
+ ".scss",
7920
+ ".sass",
7921
+ ".less"
7922
+ ]);
7923
+ var ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
7924
+ ".avif",
7925
+ ".bmp",
7926
+ ".eot",
7927
+ ".gif",
7928
+ ".ico",
7929
+ ".jpeg",
7930
+ ".jpg",
7931
+ ".mp4",
7932
+ ".ogg",
7933
+ ".otf",
7934
+ ".png",
7935
+ ".svg",
7936
+ ".ttf",
7937
+ ".webm",
7938
+ ".webp",
7939
+ ".woff",
7940
+ ".woff2"
7941
+ ]);
7942
+ var MAX_SOURCE_FILES = 2e3;
7943
+ var MAX_SOURCE_BYTES = 2097152;
7944
+ function portable$2(file) {
7945
+ return file.split(path.sep).join("/");
7946
+ }
7947
+ function inside$1(root, candidate) {
7948
+ const relative = path.relative(root, candidate);
7949
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
7950
+ }
7951
+ async function walk(directory) {
7952
+ const files = [];
7953
+ async function visit(current) {
7954
+ const entries = await readdir(current, { withFileTypes: true });
7955
+ for (const entry of entries) {
7956
+ if (entry.isSymbolicLink()) continue;
7957
+ if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) continue;
7958
+ const absolute = path.join(current, entry.name);
7959
+ if (entry.isDirectory()) await visit(absolute);
7960
+ else if (entry.isFile()) files.push(absolute);
7961
+ if (files.length > MAX_SOURCE_FILES) throw new Error(`O projeto excede o limite da V1 de ${MAX_SOURCE_FILES} arquivos analisáveis.`);
7962
+ }
7963
+ }
7964
+ await visit(directory);
7965
+ return files;
7966
+ }
7967
+ async function jsonFile(file) {
7968
+ try {
7969
+ return JSON.parse(await readFile(file, "utf8"));
7970
+ } catch (error) {
7971
+ throw new Error(`package.json inválido: ${file}`, { cause: error });
7972
+ }
7973
+ }
7974
+ function dependenciesOf(packageJson) {
7975
+ const result = {};
7976
+ for (const key of [
7977
+ "dependencies",
7978
+ "devDependencies",
7979
+ "peerDependencies"
7980
+ ]) {
7981
+ const values = packageJson[key];
7982
+ if (!values || typeof values !== "object" || Array.isArray(values)) continue;
7983
+ for (const [name, version] of Object.entries(values)) if (typeof version === "string") result[name] = version;
7984
+ }
7985
+ return result;
7986
+ }
7987
+ function detectFramework(files, dependencies) {
7988
+ if (dependencies.next || files.some((file) => /^next\.config\./.test(path.basename(file)))) return "next";
7989
+ if (dependencies.vite || files.some((file) => /^vite\.config\./.test(path.basename(file)))) return "vite";
7990
+ throw new Error("Projeto não suportado pela V1: não foi possível identificar Next.js ou Vite.");
7991
+ }
7992
+ function detectSourceRoots(sourceDirectory, files) {
7993
+ const candidates = [
7994
+ "src",
7995
+ "app",
7996
+ "pages",
7997
+ "components"
7998
+ ].filter((candidate) => files.some((file) => inside$1(path.join(sourceDirectory, candidate), file)));
7999
+ return candidates.length ? candidates : ["."];
8000
+ }
8001
+ function assetKind(extension) {
8002
+ if ([
8003
+ ".woff",
8004
+ ".woff2",
8005
+ ".ttf",
8006
+ ".otf",
8007
+ ".eot"
8008
+ ].includes(extension)) return "font";
8009
+ if ([
8010
+ ".mp4",
8011
+ ".webm",
8012
+ ".ogg"
8013
+ ].includes(extension)) return "media";
8014
+ if (extension === ".svg") return "svg";
8015
+ if (extension === ".ico") return "icon";
8016
+ return "image";
8017
+ }
8018
+ async function resolveImport(sourceFile, specifier, sourceDirectory) {
8019
+ if (!specifier.startsWith(".")) return null;
8020
+ const base = path.resolve(path.dirname(sourceFile), specifier);
8021
+ const candidates = [
8022
+ base,
8023
+ ...[
8024
+ ".ts",
8025
+ ".tsx",
8026
+ ".js",
8027
+ ".jsx",
8028
+ ".css",
8029
+ ".scss",
8030
+ ".sass",
8031
+ ".less",
8032
+ ...ASSET_EXTENSIONS
8033
+ ].map((extension) => `${base}${extension}`),
8034
+ ...[
8035
+ "index.ts",
8036
+ "index.tsx",
8037
+ "index.js",
8038
+ "index.jsx",
8039
+ "index.css"
8040
+ ].map((entry) => path.join(base, entry))
8041
+ ];
8042
+ for (const candidate of candidates) {
8043
+ if (!inside$1(sourceDirectory, candidate)) continue;
8044
+ try {
8045
+ if ((await stat(candidate)).isFile()) return candidate;
8046
+ } catch {}
8047
+ }
8048
+ return null;
8049
+ }
8050
+ function expressionClasses(expression) {
8051
+ if (ts.isStringLiteralLike(expression)) return expression.text.split(/\s+/).filter(Boolean);
8052
+ if (ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text.split(/\s+/).filter(Boolean);
8053
+ if (ts.isPropertyAccessExpression(expression)) return [expression.name.text];
8054
+ if (ts.isCallExpression(expression)) return expression.arguments.flatMap(expressionClasses);
8055
+ if (ts.isConditionalExpression(expression)) return [...expressionClasses(expression.whenTrue), ...expressionClasses(expression.whenFalse)];
8056
+ if (ts.isBinaryExpression(expression)) return [...expressionClasses(expression.left), ...expressionClasses(expression.right)];
8057
+ if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((item) => ts.isExpression(item) ? expressionClasses(item) : []);
8058
+ return [];
8059
+ }
8060
+ function jsxClasses(attributes) {
8061
+ const classes = [];
8062
+ for (const property of attributes.properties) {
8063
+ if (!ts.isJsxAttribute(property) || property.name.getText() !== "className" || !property.initializer) continue;
8064
+ if (ts.isStringLiteral(property.initializer)) classes.push(...property.initializer.text.split(/\s+/));
8065
+ else if (ts.isJsxExpression(property.initializer) && property.initializer.expression) classes.push(...expressionClasses(property.initializer.expression));
8066
+ }
8067
+ return [...new Set(classes.filter(Boolean))];
8068
+ }
8069
+ function jsxTag(node) {
8070
+ return (ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName).getText();
8071
+ }
8072
+ function jsxAttributes(node) {
8073
+ return ts.isJsxElement(node) ? node.openingElement.attributes : node.attributes;
8074
+ }
8075
+ function analyzeJsx(root) {
8076
+ const result = [];
8077
+ function visit(node, depth) {
8078
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
8079
+ const attributes = jsxAttributes(node);
8080
+ const text = [];
8081
+ if (ts.isJsxElement(node)) {
8082
+ for (const child of node.children) if (ts.isJsxText(child) && child.text.trim()) text.push(child.text.trim().replace(/\s+/g, " "));
8083
+ }
8084
+ result.push({
8085
+ tag: jsxTag(node),
8086
+ depth,
8087
+ classes: jsxClasses(attributes),
8088
+ text,
8089
+ attributes: attributes.properties.filter(ts.isJsxAttribute).map((attribute) => attribute.name.getText())
8090
+ });
8091
+ ts.forEachChild(node, (child) => visit(child, depth + 1));
8092
+ return;
8093
+ }
8094
+ ts.forEachChild(node, (child) => visit(child, depth));
8095
+ }
8096
+ visit(root, 0);
8097
+ return result;
8098
+ }
8099
+ function containsJsx(node) {
8100
+ let found = false;
8101
+ function visit(child) {
8102
+ if (found) return;
8103
+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child)) {
8104
+ found = true;
8105
+ return;
8106
+ }
8107
+ ts.forEachChild(child, visit);
8108
+ }
8109
+ visit(node);
8110
+ return found;
8111
+ }
8112
+ function componentNodes(source) {
8113
+ const result = [];
8114
+ const defaultNames = /* @__PURE__ */ new Set();
8115
+ for (const statement of source.statements) if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) defaultNames.add(statement.expression.text);
8116
+ for (const statement of source.statements) {
8117
+ if (ts.isFunctionDeclaration(statement) && statement.body && containsJsx(statement)) {
8118
+ const modifiers = statement.modifiers ?? [];
8119
+ const fallback = path.basename(source.fileName, path.extname(source.fileName));
8120
+ const name = statement.name?.text || fallback;
8121
+ result.push({
8122
+ name,
8123
+ node: statement,
8124
+ exported: modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword),
8125
+ defaultExport: modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) || defaultNames.has(name)
8126
+ });
8127
+ }
8128
+ if (!ts.isVariableStatement(statement)) continue;
8129
+ const exported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
8130
+ for (const declaration of statement.declarationList.declarations) {
8131
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;
8132
+ const initializer = declaration.initializer;
8133
+ if (!(ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) || !containsJsx(initializer)) continue;
8134
+ result.push({
8135
+ name: declaration.name.text,
8136
+ node: initializer,
8137
+ exported,
8138
+ defaultExport: defaultNames.has(declaration.name.text)
8139
+ });
8140
+ }
8141
+ }
8142
+ return result;
8143
+ }
8144
+ function importsOf(source) {
8145
+ return source.statements.filter(ts.isImportDeclaration).map((statement) => {
8146
+ const clause = statement.importClause;
8147
+ const names = [];
8148
+ if (clause?.name) names.push(clause.name.text);
8149
+ if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) names.push(...clause.namedBindings.elements.map((item) => item.name.text));
8150
+ if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings)) names.push(clause.namedBindings.name.text);
8151
+ return {
8152
+ module: statement.moduleSpecifier.text,
8153
+ names,
8154
+ typeOnly: clause?.isTypeOnly ?? false
8155
+ };
8156
+ });
8157
+ }
8158
+ function businessSignals(source, imports) {
8159
+ const signals = /* @__PURE__ */ new Set();
8160
+ for (const item of imports) {
8161
+ const module = item.module.toLowerCase();
8162
+ if (module.includes("axios")) signals.add("Axios/API externa");
8163
+ if (module.includes("react-router")) signals.add("React Router");
8164
+ if (module.includes("redux")) signals.add("Redux/store própria");
8165
+ if (module.includes("zustand")) signals.add("Zustand/store própria");
8166
+ if (module.includes("auth")) signals.add("autenticação");
8167
+ if (module.includes("checkout")) signals.add("checkout próprio");
8168
+ if (module.includes("cart") || module.includes("carrinho")) signals.add("carrinho próprio");
8169
+ }
8170
+ function visit(node) {
8171
+ if (ts.isCallExpression(node)) {
8172
+ const name = node.expression.getText(source).toLowerCase();
8173
+ if (name === "fetch" || name.endsWith(".fetch")) signals.add("fetch/API externa");
8174
+ if (name.includes("useselector") || name.includes("usedispatch")) signals.add("Redux/store própria");
8175
+ if (name.includes("usestore")) signals.add("store própria");
8176
+ if (name.includes("useauth")) signals.add("autenticação");
8177
+ if (name.includes("usecart") || name.includes("usecarrinho")) signals.add("carrinho próprio");
8178
+ }
8179
+ ts.forEachChild(node, visit);
8180
+ }
8181
+ visit(source);
8182
+ return [...signals];
8183
+ }
8184
+ function publicAssetFromAttribute(node, sourceDirectory) {
8185
+ if (![
8186
+ "src",
8187
+ "href",
8188
+ "poster"
8189
+ ].includes(node.name.getText())) return null;
8190
+ if (!node.initializer || !ts.isStringLiteral(node.initializer)) return null;
8191
+ const value = node.initializer.text;
8192
+ if (!value.startsWith("/") || value.startsWith("//")) return null;
8193
+ return path.join(sourceDirectory, "public", value.replace(/^\/+/, ""));
8194
+ }
8195
+ function pageFile(relativeFile, framework) {
8196
+ if (framework === "next") return /(^|\/)app\/.*\/(?:page|layout)\.tsx$/.test(relativeFile) || /(^|\/)app\/(?:page|layout)\.tsx$/.test(relativeFile) || /(^|\/)pages\/(?!_)[^/]+\.tsx$/.test(relativeFile);
8197
+ return /(^|\/)(?:App|Home|Index|Landing)\.tsx$/i.test(relativeFile) || /(^|\/)pages\//.test(relativeFile);
8198
+ }
8199
+ async function analyzeComponentFile(absoluteFile, sourceDirectory, framework) {
8200
+ if ((await stat(absoluteFile)).size > MAX_SOURCE_BYTES) return {
8201
+ components: [],
8202
+ assets: [],
8203
+ styles: []
8204
+ };
8205
+ const content = await readFile(absoluteFile, "utf8");
8206
+ const source = ts.createSourceFile(absoluteFile, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
8207
+ const imports = importsOf(source);
8208
+ const relativeFile = portable$2(path.relative(sourceDirectory, absoluteFile));
8209
+ const styles = [];
8210
+ const assets = [];
8211
+ for (const item of imports) {
8212
+ const extension = path.extname(item.module).toLowerCase();
8213
+ const resolved = await resolveImport(absoluteFile, item.module, sourceDirectory);
8214
+ if (!resolved) continue;
8215
+ if (STYLE_EXTENSIONS.has(extension)) styles.push(resolved);
8216
+ if (ASSET_EXTENSIONS.has(extension)) assets.push(resolved);
8217
+ }
8218
+ function findPublicAssets(node) {
8219
+ if (ts.isJsxAttribute(node)) {
8220
+ const asset = publicAssetFromAttribute(node, sourceDirectory);
8221
+ if (asset) assets.push(asset);
8222
+ }
8223
+ ts.forEachChild(node, findPublicAssets);
8224
+ }
8225
+ findPublicAssets(source);
8226
+ const signals = businessSignals(source, imports);
8227
+ return {
8228
+ components: componentNodes(source).map(({ name, node, exported, defaultExport }, index) => {
8229
+ const jsx = analyzeJsx(node);
8230
+ return {
8231
+ id: `${relativeFile}#${name}-${index}`,
8232
+ name,
8233
+ file: relativeFile,
8234
+ exported,
8235
+ defaultExport,
8236
+ page: pageFile(relativeFile, framework),
8237
+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
8238
+ imports,
8239
+ styleImports: styles.map((file) => portable$2(path.relative(sourceDirectory, file))),
8240
+ assetImports: assets.map((file) => portable$2(path.relative(sourceDirectory, file))),
8241
+ jsx,
8242
+ rootClasses: jsx.find(({ depth }) => depth === 0)?.classes ?? jsx[0]?.classes ?? [],
8243
+ text: [...new Set(jsx.flatMap((item) => item.text))].slice(0, 30),
8244
+ businessSignals: signals,
8245
+ roles: []
8246
+ };
8247
+ }),
8248
+ assets,
8249
+ styles
8250
+ };
8251
+ }
8252
+ function tailwindAnalysis(files, dependencies, sourceDirectory) {
8253
+ const version = dependencies.tailwindcss ?? null;
8254
+ const match = version?.match(/(\d+)/);
8255
+ const config = files.find((file) => /^tailwind\.config\./.test(path.basename(file))) ?? null;
8256
+ const postcss = files.find((file) => /^postcss\.config\./.test(path.basename(file))) ?? null;
8257
+ return {
8258
+ detected: Boolean(version || config),
8259
+ version,
8260
+ major: match ? Number(match[1]) : null,
8261
+ configFile: config ? portable$2(path.relative(sourceDirectory, config)) : null,
8262
+ postcssFile: postcss ? portable$2(path.relative(sourceDirectory, postcss)) : null
8263
+ };
8264
+ }
8265
+ function addAsset(target, absolutePath, sourceDirectory, referencedBy) {
8266
+ if (!inside$1(sourceDirectory, absolutePath) || !ASSET_EXTENSIONS.has(path.extname(absolutePath).toLowerCase())) return;
8267
+ const key = path.resolve(absolutePath);
8268
+ const existing = target.get(key);
8269
+ if (existing) {
8270
+ if (!existing.referencedBy.includes(referencedBy)) existing.referencedBy.push(referencedBy);
8271
+ return;
8272
+ }
8273
+ target.set(key, {
8274
+ file: portable$2(path.relative(sourceDirectory, key)),
8275
+ absolutePath: key,
8276
+ kind: assetKind(path.extname(key).toLowerCase()),
8277
+ referencedBy: [referencedBy]
8278
+ });
8279
+ }
8280
+ function cssAssetReferences(content) {
8281
+ return [...content.matchAll(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi)].map((match) => match[2]).filter((value) => !/^(?:data:|https?:|#)/i.test(value));
8282
+ }
8283
+ async function analyzeReactProject(inputDirectory) {
8284
+ const sourceDirectory = path.resolve(inputDirectory);
8285
+ let details;
8286
+ try {
8287
+ details = await stat(sourceDirectory);
8288
+ } catch {
8289
+ throw new Error(`Projeto de origem não encontrado: ${sourceDirectory}`);
8290
+ }
8291
+ if (!details.isDirectory()) throw new Error(`A origem não é uma pasta: ${sourceDirectory}`);
8292
+ const packageJson = await jsonFile(path.join(sourceDirectory, "package.json"));
8293
+ const dependencies = dependenciesOf(packageJson);
8294
+ if (!dependencies.react) throw new Error("O projeto não declara React nas dependências.");
8295
+ const files = await walk(sourceDirectory);
8296
+ const framework = detectFramework(files, dependencies);
8297
+ const tsxFiles = files.filter((file) => file.endsWith(".tsx"));
8298
+ if (!tsxFiles.length) throw new Error("Nenhum componente TSX foi encontrado. A V1 exige React com TypeScript.");
8299
+ const components = [];
8300
+ const ignoredFiles = [];
8301
+ const referencedStyles = /* @__PURE__ */ new Set();
8302
+ const assetMap = /* @__PURE__ */ new Map();
8303
+ for (const file of tsxFiles) {
8304
+ const analyzed = await analyzeComponentFile(file, sourceDirectory, framework);
8305
+ components.push(...analyzed.components);
8306
+ analyzed.styles.forEach((style) => referencedStyles.add(path.resolve(style)));
8307
+ analyzed.assets.forEach((asset) => addAsset(assetMap, asset, sourceDirectory, portable$2(path.relative(sourceDirectory, file))));
8308
+ }
8309
+ for (const file of files.filter((candidate) => candidate.endsWith(".ts") && !candidate.endsWith(".d.ts"))) {
8310
+ if ((await stat(file)).size > MAX_SOURCE_BYTES) continue;
8311
+ const content = await readFile(file, "utf8");
8312
+ const source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
8313
+ const signals = businessSignals(source, importsOf(source));
8314
+ if (!signals.length) continue;
8315
+ ignoredFiles.push({
8316
+ file: portable$2(path.relative(sourceDirectory, file)),
8317
+ reason: signals.join(", ")
8318
+ });
8319
+ }
8320
+ const styles = [];
8321
+ for (const file of files.filter((candidate) => STYLE_EXTENSIONS.has(path.extname(candidate).toLowerCase()))) {
8322
+ const content = await readFile(file, "utf8");
8323
+ const relativeFile = portable$2(path.relative(sourceDirectory, file));
8324
+ styles.push({
8325
+ file: relativeFile,
8326
+ absolutePath: file,
8327
+ module: /\.module\.(?:css|scss|sass|less)$/.test(file),
8328
+ imported: referencedStyles.has(path.resolve(file)) || /(^|\/)(?:global|globals|index|app)\.(?:css|scss|sass|less)$/.test(relativeFile),
8329
+ content
8330
+ });
8331
+ for (const reference of cssAssetReferences(content)) addAsset(assetMap, reference.startsWith("/") ? path.join(sourceDirectory, "public", reference.replace(/^\/+/, "")) : path.resolve(path.dirname(file), reference), sourceDirectory, relativeFile);
8332
+ }
8333
+ return {
8334
+ sourceDirectory,
8335
+ projectName: typeof packageJson.name === "string" && packageJson.name.trim() ? packageJson.name.trim() : path.basename(sourceDirectory),
8336
+ framework,
8337
+ sourceRoots: detectSourceRoots(sourceDirectory, files),
8338
+ packageJson,
8339
+ dependencies,
8340
+ components,
8341
+ styles,
8342
+ assets: [...assetMap.values()],
8343
+ tailwind: tailwindAnalysis(files, dependencies, sourceDirectory),
8344
+ ignoredFiles,
8345
+ warnings: styles.some(({ file }) => /\.(?:scss|sass|less)$/.test(file)) ? ["A V1 detecta Sass/Less, mas preserva automaticamente apenas CSS e CSS Modules."] : []
8346
+ };
8347
+ }
8348
+ //#endregion
8349
+ //#region src/migrate/classifier.ts
8350
+ var RULES = [
8351
+ {
8352
+ role: "HEADER",
8353
+ keywords: [
8354
+ "header",
8355
+ "navbar",
8356
+ "navigation",
8357
+ "menu",
8358
+ "cabecalho"
8359
+ ],
8360
+ tags: ["header", "nav"],
8361
+ minimum: 5
8362
+ },
8363
+ {
8364
+ role: "FOOTER",
8365
+ keywords: ["footer", "rodape"],
8366
+ tags: ["footer"],
8367
+ minimum: 5
8368
+ },
8369
+ {
8370
+ role: "HERO",
8371
+ keywords: [
8372
+ "hero",
8373
+ "banner",
8374
+ "jumbotron",
8375
+ "masthead",
8376
+ "destaque"
8377
+ ],
8378
+ tags: ["section"],
8379
+ minimum: 5
8380
+ },
8381
+ {
8382
+ role: "PRODUCT_CARD",
8383
+ keywords: [
8384
+ "productcard",
8385
+ "product-card",
8386
+ "produto-card",
8387
+ "cardproduto",
8388
+ "productitem"
8389
+ ],
8390
+ tags: ["article"],
8391
+ minimum: 6
8392
+ },
8393
+ {
8394
+ role: "PRODUCT_GRID",
8395
+ keywords: [
8396
+ "productgrid",
8397
+ "product-grid",
8398
+ "products-grid",
8399
+ "produtos-grid",
8400
+ "productlist",
8401
+ "catalog"
8402
+ ],
8403
+ minimum: 6
8404
+ },
8405
+ {
8406
+ role: "PRODUCT_DETAIL",
8407
+ keywords: [
8408
+ "productdetail",
8409
+ "product-detail",
8410
+ "produto-detalhe",
8411
+ "productpage",
8412
+ "produto/",
8413
+ "product/"
8414
+ ],
8415
+ minimum: 6
8416
+ },
8417
+ {
8418
+ role: "HOME",
8419
+ keywords: [
8420
+ "homepage",
8421
+ "home-page",
8422
+ "landing",
8423
+ "inicio",
8424
+ "app.tsx",
8425
+ "page.tsx"
8426
+ ],
8427
+ tags: ["main"],
8428
+ minimum: 6
8429
+ },
8430
+ {
8431
+ role: "SECTION",
8432
+ keywords: [
8433
+ "section",
8434
+ "features",
8435
+ "benefits",
8436
+ "services",
8437
+ "about",
8438
+ "cta"
8439
+ ],
8440
+ tags: ["section"],
8441
+ minimum: 6
8442
+ },
8443
+ {
8444
+ role: "PAGE",
8445
+ keywords: [
8446
+ "page",
8447
+ "screen",
8448
+ "view"
8449
+ ],
8450
+ tags: ["main"],
8451
+ minimum: 6
8452
+ }
8453
+ ];
8454
+ function normalized$1(value) {
8455
+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
8456
+ }
8457
+ function componentCorpus(component) {
8458
+ return normalized$1([
8459
+ component.name,
8460
+ component.file,
8461
+ ...component.rootClasses,
8462
+ ...component.jsx.flatMap(({ classes, text }) => [...classes, ...text])
8463
+ ].join(" "));
8464
+ }
8465
+ function roleScore(component, rule) {
8466
+ const corpus = componentCorpus(component);
8467
+ const name = normalized$1(component.name);
8468
+ const file = normalized$1(component.file);
8469
+ const reasons = [];
8470
+ let score = 0;
8471
+ for (const keyword of rule.keywords) {
8472
+ const term = normalized$1(keyword);
8473
+ if (name.includes(term)) {
8474
+ score += 7;
8475
+ reasons.push(`nome contém "${keyword}"`);
8476
+ } else if (file.includes(term)) {
8477
+ score += 5;
8478
+ reasons.push(`caminho contém "${keyword}"`);
8479
+ } else if (corpus.includes(term)) {
8480
+ score += 3;
8481
+ reasons.push(`JSX/classes contêm "${keyword}"`);
8482
+ }
8483
+ }
8484
+ for (const tag of rule.tags ?? []) if (component.jsx.some((node) => normalized$1(node.tag) === tag)) {
8485
+ score += 6;
8486
+ reasons.push(`usa <${tag}>`);
8487
+ }
8488
+ if (component.page && rule.role === "HOME" && /(^|\/)(?:app\/)?page\.tsx$/.test(component.file)) {
8489
+ score += 7;
8490
+ reasons.push("página inicial do framework");
8491
+ }
8492
+ if (component.page && rule.role === "PAGE") {
8493
+ score += 4;
8494
+ reasons.push("arquivo de página");
8495
+ }
8496
+ if (rule.role === "PRODUCT_CARD") {
8497
+ const hasProduct = corpus.includes("product") || corpus.includes("produto");
8498
+ const hasCard = corpus.includes("card") || component.jsx.some(({ tag }) => tag === "article");
8499
+ if (hasProduct && hasCard) {
8500
+ score += 7;
8501
+ reasons.push("combina produto e card/article");
8502
+ }
8503
+ }
8504
+ if (rule.role === "PRODUCT_GRID") {
8505
+ if (component.jsx.some(({ classes }) => classes.some((item) => /grid|list/.test(normalized$1(item))))) {
8506
+ score += 5;
8507
+ reasons.push("possui estrutura de grid/lista");
8508
+ }
8509
+ }
8510
+ if (rule.role === "PRODUCT_DETAIL") {
8511
+ if (corpus.includes("price") || corpus.includes("preco") || corpus.includes("sku")) {
8512
+ score += 4;
8513
+ reasons.push("exibe campos de detalhe de produto");
8514
+ }
8515
+ }
8516
+ if (rule.role === "HERO" && component.text.some((text) => text.length > 20)) {
8517
+ score += 2;
8518
+ reasons.push("possui chamada textual de destaque");
8519
+ }
8520
+ if (component.defaultExport) score += 1;
8521
+ return {
8522
+ role: rule.role,
8523
+ score,
8524
+ reasons
8525
+ };
8526
+ }
8527
+ function classifyProject(input) {
8528
+ const components = input.components.map((component) => ({
8529
+ ...component,
8530
+ roles: RULES.map((rule) => roleScore(component, rule)).filter((candidate) => candidate.score >= (RULES.find(({ role }) => role === candidate.role)?.minimum ?? 6)).sort((left, right) => right.score - left.score)
8531
+ }));
8532
+ const ignoredFiles = [...input.ignoredFiles];
8533
+ for (const component of components) {
8534
+ if (!component.businessSignals.length || component.roles.length) continue;
8535
+ if (ignoredFiles.some(({ file }) => file === component.file)) continue;
8536
+ ignoredFiles.push({
8537
+ file: component.file,
8538
+ reason: component.businessSignals.join(", ")
8539
+ });
8540
+ }
8541
+ return {
8542
+ ...input,
8543
+ components,
8544
+ ignoredFiles
8545
+ };
8546
+ }
8547
+ //#endregion
8548
+ //#region src/migrate/asset-copier.ts
8549
+ function portable$1(file) {
8550
+ return file.split(path.sep).join("/");
8551
+ }
8552
+ function safeRelative(file) {
8553
+ return portable$1(file).split("/").filter((part) => part && part !== "." && part !== "..").map((part) => part.replace(/[^a-zA-Z0-9._-]/g, "-")).join("/");
8554
+ }
8555
+ async function copyMigrationAssets(plan, outputDirectory) {
8556
+ const copied = [];
8557
+ const destinationRoot = path.join(outputDirectory, "src", "assets");
8558
+ for (const asset of plan.assets) {
8559
+ try {
8560
+ if (!(await stat(asset.absolutePath)).isFile()) continue;
8561
+ } catch {
8562
+ plan.warnings.push(`Asset não encontrado e ignorado: ${asset.file}`);
8563
+ continue;
8564
+ }
8565
+ const relative = safeRelative(asset.file.startsWith("public/") ? asset.file.slice(7) : asset.file);
8566
+ if (!relative) continue;
8567
+ const destination = path.join(destinationRoot, relative);
8568
+ await mkdir(path.dirname(destination), { recursive: true });
8569
+ await copyFile(asset.absolutePath, destination);
8570
+ copied.push({
8571
+ sourceFile: asset.absolutePath,
8572
+ outputFile: destination,
8573
+ importPath: `../assets/${portable$1(relative)}`,
8574
+ kind: asset.kind
8575
+ });
8576
+ }
8577
+ return copied;
8578
+ }
8579
+ //#endregion
8580
+ //#region src/migrate/generator.ts
8581
+ function portable(file) {
8582
+ return file.split(path.sep).join("/");
8583
+ }
8584
+ function classes(base, source = "") {
8585
+ return JSON.stringify([base, source].filter(Boolean).join(" "));
8586
+ }
8587
+ function profile(plan, role) {
8588
+ return plan.selected[role]?.classes ?? {
8589
+ root: "",
8590
+ brand: "",
8591
+ navigation: "",
8592
+ title: "",
8593
+ text: "",
8594
+ action: "",
8595
+ media: "",
8596
+ grid: "",
8597
+ card: "",
8598
+ content: ""
8599
+ };
8600
+ }
8601
+ function sourceText(plan, role, fallback) {
8602
+ return plan.selected[role]?.component.text.find((candidate) => candidate.length >= 3 && candidate.length <= 140) || fallback;
8603
+ }
8604
+ function headerSource(plan) {
8605
+ const style = profile(plan, "HEADER");
8606
+ return `import type { HeaderProps } from "@nuvler/theme-sdk";
8607
+
8608
+ export function Header({ site, categories, pages }: HeaderProps) {
8609
+ const name = site.settings?.siteName || site.tenant.name;
8610
+ return <header className=${classes("nuvler-migrated-header", style.root)}>
8611
+ <div className=${classes("nuvler-migrated-header-inner", style.content)}>
8612
+ <a className=${classes("nuvler-migrated-brand", style.brand)} href="/">
8613
+ {site.settings?.logo?.url ? <img src={site.settings.logo.url} alt={site.settings.logo.alt || name} /> : <span>{name}</span>}
8614
+ </a>
8615
+ <nav className=${classes("nuvler-migrated-nav", style.navigation)} aria-label="Navegação principal">
8616
+ <a href="/">Início</a>
8617
+ {site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
8618
+ {categories.slice(0, 6).map((category) => <a href={\`/categoria/\${category.slug}\`} key={category.slug}>{category.name}</a>)}
8619
+ {pages.slice(0, 4).map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
8620
+ </nav>
8621
+ {site.modules.includes("PRODUCTS") && <form className="nuvler-migrated-search" action="/produtos">
8622
+ <input name="busca" type="search" placeholder="Buscar produtos" />
8623
+ <button className=${classes("nuvler-migrated-action", style.action)} type="submit">Buscar</button>
8624
+ </form>}
8625
+ </div>
8626
+ </header>;
8627
+ }
8628
+ `;
8629
+ }
8630
+ function footerSource(plan) {
8631
+ const style = profile(plan, "FOOTER");
8632
+ return `import type { FooterProps } from "@nuvler/theme-sdk";
8633
+
8634
+ export function Footer({ site, pages, template }: FooterProps) {
8635
+ const name = site.settings?.siteName || site.tenant.name;
8636
+ return <footer className=${classes("nuvler-migrated-footer", style.root)}>
8637
+ <div className=${classes("nuvler-migrated-footer-inner", style.content)}>
8638
+ <div><strong className=${classes("nuvler-migrated-footer-brand", style.brand)}>{name}</strong><p className=${classes("nuvler-migrated-copy", style.text)}>{site.settings?.description || template.footerTagline}</p></div>
8639
+ <nav className=${classes("nuvler-migrated-footer-nav", style.navigation)} aria-label={template.footerNavigationLabel}>
8640
+ <a href="/">Início</a>
8641
+ {site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
8642
+ {pages.map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
8643
+ </nav>
8644
+ <div className="nuvler-migrated-contact">
8645
+ {site.settings?.contact.phone && <a href={\`tel:\${site.settings.contact.phone}\`}>{site.settings.contact.phone}</a>}
8646
+ {site.settings?.contact.email && <a href={\`mailto:\${site.settings.contact.email}\`}>{site.settings.contact.email}</a>}
8647
+ </div>
8648
+ </div>
8649
+ <small>{template.footerNote}</small>
8650
+ </footer>;
8651
+ }
8652
+ `;
8653
+ }
8654
+ function productCardSource(plan) {
8655
+ const style = profile(plan, "PRODUCT_CARD");
8656
+ return `import type { ThemeProduct } from "@nuvler/theme-sdk";
8657
+
8658
+ function money(value: number | null): string {
8659
+ return value === null ? "Consulte" : new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
8660
+ }
8661
+
8662
+ export function ProductCard({ product, showCategory = true, showDescription = true }: { product: ThemeProduct; showCategory?: boolean; showDescription?: boolean }) {
8663
+ const price = product.promotionalPrice ?? product.price;
8664
+ return <article className=${classes("nuvler-migrated-product-card", style.root || style.card)}>
8665
+ <a className=${classes("nuvler-migrated-product-media", style.media)} href={\`/produto/\${product.slug}\`}>
8666
+ {product.image?.url ? <img src={product.image.url} alt={product.image.alt || product.title} /> : <span aria-hidden="true" />}
8667
+ </a>
8668
+ <div className=${classes("nuvler-migrated-product-content", style.content)}>
8669
+ {showCategory && <small>{product.categories[0]?.name || product.brand || "Produto"}</small>}
8670
+ <h3 className=${classes("nuvler-migrated-product-title", style.title)}><a href={\`/produto/\${product.slug}\`}>{product.title}</a></h3>
8671
+ {showDescription && product.description && <p className=${classes("nuvler-migrated-copy", style.text)}>{product.description}</p>}
8672
+ <strong>{money(price)}</strong>
8673
+ <a className=${classes("nuvler-migrated-action", style.action)} href={\`/produto/\${product.slug}\`}>Ver produto</a>
8674
+ </div>
8675
+ </article>;
8676
+ }
8677
+ `;
8678
+ }
8679
+ function productGridSource(plan) {
8680
+ const style = profile(plan, "PRODUCT_GRID");
8681
+ return `import type { ProductGridProps } from "@nuvler/theme-sdk";
8682
+ import { ProductCard } from "./ProductCard.js";
8683
+
8684
+ export function ProductGrid({ products, columns = 3, showCategory, showDescription }: ProductGridProps) {
8685
+ return <div className=${classes("nuvler-migrated-product-grid", style.root || style.grid)} data-columns={columns}>
8686
+ {products.map((product) => <ProductCard product={product} showCategory={showCategory} showDescription={showDescription} key={product.slug} />)}
8687
+ </div>;
8688
+ }
8689
+ `;
8690
+ }
8691
+ function productDetailSource(plan) {
8692
+ const style = profile(plan, "PRODUCT_DETAIL");
8693
+ return `import type { ProductDetailProps } from "@nuvler/theme-sdk";
8694
+
8695
+ function money(value: number | null): string {
8696
+ return value === null ? "Consulte" : new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
8697
+ }
8698
+
8699
+ export function ProductDetail({ product, descriptionContent, onAddToCart }: ProductDetailProps) {
8700
+ const image = product.images[0] ?? product.image;
8701
+ return <article className=${classes("nuvler-migrated-product-detail", style.root)}>
8702
+ <div className=${classes("nuvler-migrated-detail-media", style.media)}>{image?.url ? <img src={image.url} alt={image.alt || product.title} /> : <span aria-hidden="true" />}</div>
8703
+ <div className=${classes("nuvler-migrated-detail-content", style.content)}>
8704
+ <small>{product.categories[0]?.name || product.brand || "Produto"}</small>
8705
+ <h1 className=${classes("nuvler-migrated-detail-title", style.title)}>{product.title}</h1>
8706
+ <strong className="nuvler-migrated-price">{money(product.promotionalPrice ?? product.price)}</strong>
8707
+ <div className=${classes("nuvler-migrated-copy", style.text)}>{descriptionContent}</div>
8708
+ <button className=${classes("nuvler-migrated-action", style.action)} type="button" onClick={() => onAddToCart?.({ productSlug: product.slug, title: product.title, sku: product.sku, image: product.image, unitPrice: product.promotionalPrice ?? product.price })}>Adicionar ao orçamento</button>
8709
+ </div>
8710
+ </article>;
8711
+ }
8712
+ `;
8713
+ }
8714
+ function homeSource(plan, assets) {
8715
+ const home = profile(plan, "HOME");
8716
+ const hero = profile(plan, "HERO");
8717
+ const section = profile(plan, "SECTION");
8718
+ const heroText = sourceText(plan, "HERO", "Uma experiência criada para sua marca");
8719
+ const visual = assets.find(({ kind }) => ["image", "svg"].includes(kind));
8720
+ return `import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
8721
+ import { ProductGrid } from "../components/ProductGrid.js";
8722
+
8723
+ ${visual ? `const migratedHeroAsset = new URL(${JSON.stringify(visual.importPath)}, import.meta.url).href;` : "const migratedHeroAsset: string | null = null;"}
8724
+
8725
+ function value(section: ThemeHomeSection | undefined, key: string): string {
8726
+ const candidate = section?.data[key];
8727
+ return typeof candidate === "string" ? candidate : "";
8728
+ }
8729
+
8730
+ export function Home({ sections, products, site, template }: HomeProps) {
8731
+ const enabled = sections.filter((item) => item.enabled).sort((left, right) => left.order - right.order);
8732
+ const heroSection = enabled.find((item) => item.type === "hero" || item.type === "banner-carousel");
8733
+ const productSection = enabled.find((item) => item.type === "products-grid" || item.type === "products-carousel");
8734
+ const name = site.settings?.siteName || site.tenant.name;
8735
+ const action = template.primaryAction(site.modules);
8736
+ return <main className=${classes("nuvler-migrated-home", home.root)}>
8737
+ <section className=${classes("nuvler-migrated-hero", hero.root || home.content)}>
8738
+ <div className=${classes("nuvler-migrated-hero-content", hero.content)}>
8739
+ <span>{${JSON.stringify(heroText)}}</span>
8740
+ <h1 className=${classes("nuvler-migrated-hero-title", hero.title)}>{value(heroSection, "title") || name}</h1>
8741
+ <p className=${classes("nuvler-migrated-copy", hero.text)}>{value(heroSection, "description") || site.settings?.description || "Conheça nossos produtos e soluções."}</p>
8742
+ <a className=${classes("nuvler-migrated-action", hero.action)} href={value(heroSection, "buttonUrl") || action.href}>{value(heroSection, "buttonLabel") || action.label}</a>
8743
+ </div>
8744
+ {migratedHeroAsset && <div className=${classes("nuvler-migrated-hero-media", hero.media)}><img src={migratedHeroAsset} alt="" /></div>}
8745
+ </section>
8746
+ {site.modules.includes("PRODUCTS") && <section className=${classes("nuvler-migrated-section", section.root)}>
8747
+ <header><span>Destaques</span><h2 className=${classes("nuvler-migrated-section-title", section.title)}>{value(productSection, "title") || "Produtos em destaque"}</h2></header>
8748
+ <ProductGrid products={products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
8749
+ </section>}
8750
+ {enabled.filter((item) => ["image-text", "rich-text", "cta"].includes(item.type)).map((item) => <section className=${classes("nuvler-migrated-section nuvler-migrated-generic", section.content)} key={item.id || \`\${item.type}-\${item.order}\`}><h2>{value(item, "title")}</h2><p>{value(item, "description") || value(item, "content")}</p>{value(item, "buttonUrl") && <a className="nuvler-migrated-action" href={value(item, "buttonUrl")}>{value(item, "buttonLabel") || "Saiba mais"}</a>}</section>)}
8751
+ </main>;
8752
+ }
8753
+ `;
8754
+ }
8755
+ function definitionSource(plan) {
8756
+ const tokens = plan.tokens;
8757
+ return `import manifestData from "../nuvler.theme.json" with { type: "json" };
8758
+ import { defineTheme, type ThemeHomeSection, type ThemeManifest } from "@nuvler/theme-sdk";
8759
+ import { Footer } from "./components/Footer.js";
8760
+ import { Header } from "./components/Header.js";
8761
+ import { ProductDetail } from "./components/ProductDetail.js";
8762
+ import { ProductGrid } from "./components/ProductGrid.js";
8763
+ import { Home } from "./sections/Home.js";
8764
+
8765
+ function section(id: string, type: ThemeHomeSection["type"], order: number): ThemeHomeSection {
8766
+ return { id, type, enabled: true, order, data: {} };
8767
+ }
8768
+
8769
+ export const manifest = manifestData as ThemeManifest;
8770
+ export const themeDefinition = defineTheme({
8771
+ manifest,
8772
+ tokens: {
8773
+ colors: ${JSON.stringify({
8774
+ primary: tokens.primary,
8775
+ primaryText: tokens.primaryText,
8776
+ secondary: tokens.secondary,
8777
+ secondaryText: tokens.secondaryText,
8778
+ accent: tokens.accent,
8779
+ background: tokens.background,
8780
+ surface: tokens.surface,
8781
+ surfaceAlt: tokens.surfaceAlt,
8782
+ text: tokens.text,
8783
+ textMuted: tokens.textMuted,
8784
+ border: tokens.border,
8785
+ headerBackground: tokens.headerBackground,
8786
+ headerText: tokens.headerText,
8787
+ footerBackground: tokens.footerBackground,
8788
+ footerText: tokens.footerText
8789
+ })},
8790
+ layout: ${JSON.stringify({
8791
+ containerWidth: tokens.containerWidth,
8792
+ borderRadius: tokens.borderRadius
8793
+ })},
8794
+ },
8795
+ template: {
8796
+ announcement: ${JSON.stringify(plan.themeName)},
8797
+ footerTagline: "Experiência visual migrada para a plataforma Nuvler.",
8798
+ footerNavigationLabel: "Navegação",
8799
+ footerNote: ${JSON.stringify(plan.themeName)},
8800
+ socialLabel: "Redes sociais",
8801
+ benefits: [],
8802
+ fallbackSections: () => [section("migrated-hero", "hero", 0), section("migrated-products", "products-grid", 1)],
8803
+ primaryAction: (modules) => modules.includes("PRODUCTS") ? { label: "Ver produtos", href: "/produtos" } : { label: "Saiba mais", href: "/" },
8804
+ },
8805
+ components: { Header, Footer, Home, ProductGrid, ProductDetail },
8806
+ });
8807
+ `;
8808
+ }
8809
+ function catalogPageSource() {
8810
+ return `import type { ThemeRoute, ThemeSite } from "@nuvler/theme-sdk";
8811
+ import { ProductGrid } from "../components/ProductGrid.js";
8812
+
8813
+ type CatalogRoute = Extract<ThemeRoute, { type: "catalog" }>;
8814
+
8815
+ export function CatalogPage({ route, site }: { route: CatalogRoute; site: ThemeSite }) {
8816
+ return <main className="nuvler-migrated-section nuvler-migrated-catalog">
8817
+ <header><span>Catálogo</span><h1>{route.search ? \`Busca: \${route.search}\` : "Produtos"}</h1><p>{route.pagination.total} produto(s)</p></header>
8818
+ <ProductGrid products={route.products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
8819
+ </main>;
8820
+ }
8821
+ `;
8822
+ }
8823
+ function productPageSource() {
8824
+ return `import type { ThemeRoute, ThemeRuntimeSdk, ThemeSite } from "@nuvler/theme-sdk";
8825
+ import { ProductDetail } from "../components/ProductDetail.js";
8826
+
8827
+ type ProductRoute = Extract<ThemeRoute, { type: "product" }>;
8828
+
8829
+ export function ProductPage({ route, site, cart }: { route: ProductRoute; site: ThemeSite; cart?: ThemeRuntimeSdk["cart"] }) {
8830
+ return <main className="nuvler-migrated-section"><ProductDetail product={route.product} contact={site.settings?.contact} productUrl={null} descriptionContent={<p>{route.product.description}</p>} onAddToCart={cart?.add} /></main>;
8831
+ }
8832
+ `;
8833
+ }
8834
+ function editorialPageSource() {
8835
+ return `import type { ThemeRoute } from "@nuvler/theme-sdk";
8836
+
8837
+ type EditorialRoute = Extract<ThemeRoute, { type: "editorial-list" | "editorial-detail" }>;
8838
+
8839
+ export function EditorialPage({ route }: { route: EditorialRoute }) {
8840
+ if (route.type === "editorial-detail") return <main className="nuvler-migrated-section"><article><span>Conteúdo</span><h1>{route.item.title}</h1><p>{route.item.description}</p></article></main>;
8841
+ return <main className="nuvler-migrated-section"><h1>{route.title}</h1><div className="nuvler-migrated-editorial-grid">{route.items.map((item) => <article key={item.slug}><h2><a href={\`\${route.basePath}/\${item.slug}\`}>{item.title}</a></h2><p>{item.description}</p></article>)}</div></main>;
8842
+ }
8843
+ `;
8844
+ }
8845
+ function statePageSource() {
8846
+ return `export function StatePage({ title, pathname }: { title: string; pathname?: string }) {
8847
+ return <main className="nuvler-migrated-section nuvler-migrated-state"><span>{pathname || "Nuvler"}</span><h1>{title}</h1></main>;
8848
+ }
8849
+ `;
8850
+ }
8851
+ function themeSource() {
8852
+ return `import type { CSSProperties } from "react";
8853
+ import type { NuvlerThemeProps, ThemeSite } from "@nuvler/theme-sdk";
8854
+ import { themeDefinition } from "./definition.js";
8855
+ import { CatalogPage } from "./pages/CatalogPage.js";
8856
+ import { EditorialPage } from "./pages/EditorialPage.js";
8857
+ import { ProductPage } from "./pages/ProductPage.js";
8858
+ import { StatePage } from "./pages/StatePage.js";
8859
+ import "./styles/theme.css";
8860
+
8861
+ export { manifest, themeDefinition } from "./definition.js";
8862
+
8863
+ export default function Theme({ context, route = { type: "home" }, sdk }: NuvlerThemeProps) {
8864
+ const { Header, Footer, Home } = themeDefinition.components;
8865
+ const site: ThemeSite = { tenant: context.store, ...context.site };
8866
+ const configured = site.settings?.theme;
8867
+ const tokens = {
8868
+ colors: { ...themeDefinition.tokens.colors, ...configured?.colors },
8869
+ layout: { ...themeDefinition.tokens.layout, ...configured?.layout },
8870
+ };
8871
+ const style = {
8872
+ "--theme-primary": tokens.colors.primary,
8873
+ "--theme-primary-text": tokens.colors.primaryText,
8874
+ "--theme-secondary": tokens.colors.secondary,
8875
+ "--theme-secondary-text": tokens.colors.secondaryText,
8876
+ "--theme-accent": tokens.colors.accent,
8877
+ "--theme-background": tokens.colors.background,
8878
+ "--theme-surface": tokens.colors.surface,
8879
+ "--theme-surface-alt": tokens.colors.surfaceAlt,
8880
+ "--theme-text": tokens.colors.text,
8881
+ "--theme-text-muted": tokens.colors.textMuted,
8882
+ "--theme-border": tokens.colors.border,
8883
+ "--theme-header-background": tokens.colors.headerBackground,
8884
+ "--theme-header-text": tokens.colors.headerText,
8885
+ "--theme-footer-background": tokens.colors.footerBackground,
8886
+ "--theme-footer-text": tokens.colors.footerText,
8887
+ "--theme-radius": \`\${tokens.layout.borderRadius}px\`,
8888
+ "--theme-container": \`\${tokens.layout.containerWidth}px\`,
8889
+ } as CSSProperties;
8890
+ let content;
8891
+ if (route.type === "home") content = <Home sections={context.home.content.sections} products={context.catalog.products} posts={context.editorial.posts} services={context.editorial.services} cases={context.editorial.cases} site={site} template={themeDefinition.template} />;
8892
+ else if (route.type === "catalog") content = <CatalogPage route={route} site={site} />;
8893
+ else if (route.type === "product") content = <ProductPage route={route} site={site} cart={sdk?.cart} />;
8894
+ else if (route.type === "editorial-list" || route.type === "editorial-detail") content = <EditorialPage route={route} />;
8895
+ else content = <StatePage title={route.type === "loading" ? "Carregando…" : route.type === "page" ? route.title : "Conteúdo não encontrado"} pathname={"pathname" in route ? route.pathname : undefined} />;
8896
+ return <div className="nuvler-migrated-theme" style={style}><Header site={site} categories={context.navigation.categories} pages={context.navigation.pages} template={themeDefinition.template} /><div className="nuvler-migrated-page">{content}</div><Footer site={site} pages={context.navigation.pages} template={themeDefinition.template} /></div>;
8897
+ }
8898
+ `;
8899
+ }
8900
+ function baseCss(plan) {
8901
+ return `/* Fallback estrutural do adaptador Nuvler. Os estilos extraídos vêm depois deste bloco. */
8902
+ * { box-sizing: border-box; }
8903
+ body { margin: 0; }
8904
+ .nuvler-migrated-theme { min-height: 100vh; background: var(--theme-background); color: var(--theme-text); font-family: Inter, system-ui, sans-serif; }
8905
+ .nuvler-migrated-header-inner, .nuvler-migrated-footer-inner, .nuvler-migrated-section, .nuvler-migrated-hero { width: min(calc(100% - 32px), var(--theme-container)); margin-inline: auto; }
8906
+ .nuvler-migrated-header { background: var(--theme-header-background); color: var(--theme-header-text); }
8907
+ .nuvler-migrated-header-inner { min-height: 72px; display: flex; align-items: center; gap: 24px; justify-content: space-between; }
8908
+ .nuvler-migrated-brand img { display: block; width: auto; max-width: 200px; max-height: 56px; }
8909
+ .nuvler-migrated-nav { display: flex; flex-wrap: wrap; gap: 18px; }
8910
+ .nuvler-migrated-nav a, .nuvler-migrated-brand, .nuvler-migrated-footer a { color: inherit; text-decoration: none; }
8911
+ .nuvler-migrated-search { display: flex; gap: 8px; }
8912
+ .nuvler-migrated-search input { min-width: 220px; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); color: var(--theme-header-text); padding: 10px 13px; }
8913
+ .nuvler-migrated-action { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: var(--theme-radius); background: var(--theme-primary); color: var(--theme-primary-text); padding: 12px 18px; text-decoration: none; cursor: pointer; }
8914
+ .nuvler-migrated-hero { display: grid; min-height: 520px; grid-template-columns: minmax(0, 1fr) minmax(320px, .9fr); align-items: center; gap: 40px; padding-block: 64px; }
8915
+ .nuvler-migrated-hero-title { margin: 12px 0; font-size: clamp(42px, 7vw, 82px); line-height: .98; }
8916
+ .nuvler-migrated-hero-media, .nuvler-migrated-product-media, .nuvler-migrated-detail-media { overflow: hidden; border-radius: var(--theme-radius); }
8917
+ .nuvler-migrated-hero-media img, .nuvler-migrated-product-media img, .nuvler-migrated-detail-media img { display: block; width: 100%; height: 100%; object-fit: cover; }
8918
+ .nuvler-migrated-section { padding-block: 56px; }
8919
+ .nuvler-migrated-product-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
8920
+ .nuvler-migrated-product-grid[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
8921
+ .nuvler-migrated-product-card { overflow: hidden; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); }
8922
+ .nuvler-migrated-product-media { display: block; aspect-ratio: 1; background: var(--theme-surface-alt); }
8923
+ .nuvler-migrated-product-content { display: grid; gap: 12px; padding: 20px; }
8924
+ .nuvler-migrated-product-content p { overflow: hidden; display: -webkit-box; color: var(--theme-text-muted); -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
8925
+ .nuvler-migrated-product-detail { display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, .8fr); gap: 48px; }
8926
+ .nuvler-migrated-price { display: block; margin-block: 18px; color: var(--theme-accent); font-size: 28px; }
8927
+ .nuvler-migrated-footer { margin-top: 64px; background: var(--theme-footer-background); color: var(--theme-footer-text); padding: 56px max(16px, calc((100% - var(--theme-container)) / 2)); }
8928
+ .nuvler-migrated-footer-inner { width: 100%; display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 40px; }
8929
+ .nuvler-migrated-footer-nav, .nuvler-migrated-contact { display: grid; gap: 8px; }
8930
+ @media (max-width: 850px) { .nuvler-migrated-header-inner, .nuvler-migrated-hero { grid-template-columns: 1fr; flex-direction: column; align-items: stretch; } .nuvler-migrated-nav { overflow-x: auto; flex-wrap: nowrap; } .nuvler-migrated-search input { width: 100%; min-width: 0; } .nuvler-migrated-product-grid, .nuvler-migrated-product-grid[data-columns="4"], .nuvler-migrated-product-detail, .nuvler-migrated-footer-inner { grid-template-columns: 1fr; } }
8931
+
8932
+ :root {
8933
+ --theme-primary: ${plan.tokens.primary};
8934
+ --theme-primary-text: ${plan.tokens.primaryText};
8935
+ --theme-secondary: ${plan.tokens.secondary};
8936
+ --theme-secondary-text: ${plan.tokens.secondaryText};
8937
+ --theme-accent: ${plan.tokens.accent};
8938
+ --theme-background: ${plan.tokens.background};
8939
+ --theme-surface: ${plan.tokens.surface};
8940
+ --theme-surface-alt: ${plan.tokens.surfaceAlt};
8941
+ --theme-text: ${plan.tokens.text};
8942
+ --theme-text-muted: ${plan.tokens.textMuted};
8943
+ --theme-border: ${plan.tokens.border};
8944
+ --theme-header-background: ${plan.tokens.headerBackground};
8945
+ --theme-header-text: ${plan.tokens.headerText};
8946
+ --theme-footer-background: ${plan.tokens.footerBackground};
8947
+ --theme-footer-text: ${plan.tokens.footerText};
8948
+ --theme-radius: ${plan.tokens.borderRadius}px;
8949
+ --theme-container: ${plan.tokens.containerWidth}px;
8950
+ }
8951
+ `;
8952
+ }
8953
+ function copiedAssetFor(style, reference, plan, copied) {
8954
+ const absolute = reference.startsWith("/") ? path.join(plan.analysis.sourceDirectory, "public", reference.replace(/^\/+/, "")) : path.resolve(path.dirname(style.absolutePath), reference);
8955
+ return copied.find((asset) => path.resolve(asset.sourceFile) === path.resolve(absolute));
8956
+ }
8957
+ function preservedCss(plan, copied) {
8958
+ return plan.styles.map((style) => {
8959
+ let content = style.content;
8960
+ content = content.replace(/@import\s+(["'])(?!https?:)(?!tailwindcss)([^"']+)\1\s*;?/gi, "");
8961
+ content = content.replace(/@tailwind\s+(?:base|components|utilities)\s*;?/gi, "");
8962
+ content = content.replace(/@import\s+["']tailwindcss["']\s*;?/gi, "");
8963
+ content = content.replace(/:global\(([^)]+)\)/g, "$1");
8964
+ content = content.replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (full, _quote, reference) => {
8965
+ if (/^(?:data:|https?:|#)/i.test(reference)) return full;
8966
+ const asset = copiedAssetFor(style, reference, plan, copied);
8967
+ if (!asset) return full;
8968
+ const output = portable(asset.outputFile);
8969
+ const markerIndex = output.lastIndexOf("/src/assets/");
8970
+ if (markerIndex < 0) return full;
8971
+ return `url(${JSON.stringify(`../assets/${output.slice(markerIndex + 12)}`)})`;
8972
+ });
8973
+ return `/* Origem: ${style.file}${style.module ? " (CSS Module convertido para CSS comum)" : ""} */\n${content}`;
8974
+ }).join("\n\n");
8975
+ }
8976
+ async function configureTailwind(plan, directory) {
8977
+ if (!plan.analysis.tailwind.detected) return "";
8978
+ const packageFile = path.join(directory, "package.json");
8979
+ const metadata = JSON.parse(await readFile(packageFile, "utf8"));
8980
+ metadata.devDependencies ??= {};
8981
+ const major = plan.analysis.tailwind.major ?? 3;
8982
+ metadata.devDependencies.tailwindcss = plan.analysis.tailwind.version || (major >= 4 ? "^4.0.0" : "^3.4.0");
8983
+ metadata.devDependencies.postcss = plan.analysis.dependencies.postcss || "^8.4.0";
8984
+ if (major >= 4) {
8985
+ metadata.devDependencies["@tailwindcss/postcss"] = plan.analysis.dependencies["@tailwindcss/postcss"] || "^4.0.0";
8986
+ await writeFile(path.join(directory, "postcss.config.mjs"), "export default { plugins: { \"@tailwindcss/postcss\": {} } };\n", "utf8");
8987
+ await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
8988
+ return "@import \"tailwindcss\";\n";
8989
+ }
8990
+ metadata.devDependencies.autoprefixer = plan.analysis.dependencies.autoprefixer || "^10.4.0";
8991
+ await writeFile(path.join(directory, "tailwind.config.cjs"), "module.exports = { content: [\"./src/**/*.{ts,tsx}\"], theme: { extend: {} }, plugins: [] };\n", "utf8");
8992
+ await writeFile(path.join(directory, "postcss.config.cjs"), "module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };\n", "utf8");
8993
+ await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
8994
+ return "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n";
8995
+ }
8996
+ async function generateMigratedTheme(plan, directory) {
8997
+ await themeCreate({
8998
+ directory,
8999
+ id: plan.themeId,
9000
+ name: plan.themeName,
9001
+ template: "starter",
9002
+ silent: true
9003
+ });
9004
+ await rm(path.join(directory, "src"), {
9005
+ recursive: true,
9006
+ force: true
9007
+ });
9008
+ await Promise.all([
9009
+ mkdir(path.join(directory, "src", "components"), { recursive: true }),
9010
+ mkdir(path.join(directory, "src", "sections"), { recursive: true }),
9011
+ mkdir(path.join(directory, "src", "styles"), { recursive: true }),
9012
+ mkdir(path.join(directory, "src", "pages"), { recursive: true })
9013
+ ]);
9014
+ const copiedAssets = await copyMigrationAssets(plan, directory);
9015
+ const tailwindHeader = await configureTailwind(plan, directory);
9016
+ await Promise.all([
9017
+ writeFile(path.join(directory, "src/components/Header.tsx"), headerSource(plan), "utf8"),
9018
+ writeFile(path.join(directory, "src/components/Footer.tsx"), footerSource(plan), "utf8"),
9019
+ writeFile(path.join(directory, "src/components/ProductCard.tsx"), productCardSource(plan), "utf8"),
9020
+ writeFile(path.join(directory, "src/components/ProductGrid.tsx"), productGridSource(plan), "utf8"),
9021
+ writeFile(path.join(directory, "src/components/ProductDetail.tsx"), productDetailSource(plan), "utf8"),
9022
+ writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan, copiedAssets), "utf8"),
9023
+ writeFile(path.join(directory, "src/pages/CatalogPage.tsx"), catalogPageSource(), "utf8"),
9024
+ writeFile(path.join(directory, "src/pages/ProductPage.tsx"), productPageSource(), "utf8"),
9025
+ writeFile(path.join(directory, "src/pages/EditorialPage.tsx"), editorialPageSource(), "utf8"),
9026
+ writeFile(path.join(directory, "src/pages/StatePage.tsx"), statePageSource(), "utf8"),
9027
+ writeFile(path.join(directory, "src/definition.tsx"), definitionSource(plan), "utf8"),
9028
+ writeFile(path.join(directory, "src/theme.tsx"), themeSource(), "utf8"),
9029
+ writeFile(path.join(directory, "src/styles/theme.css"), `${tailwindHeader}${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
9030
+ writeFile(path.join(directory, "src/styles.d.ts"), "declare module \"*.css\";\ndeclare module \"*.svg\";\n", "utf8")
9031
+ ]);
9032
+ const manifestFile = path.join(directory, "nuvler.theme.json");
9033
+ const manifest = JSON.parse(await readFile(manifestFile, "utf8"));
9034
+ manifest.entry = "src/theme.tsx";
9035
+ manifest.styles = ["src/styles/theme.css"];
9036
+ manifest.presentation = {
9037
+ description: `Tema ${plan.themeName} migrado de um projeto React + ${plan.analysis.framework === "next" ? "Next.js" : "Vite"}.`,
9038
+ templateId: "starter",
9039
+ colors: {
9040
+ primary: plan.tokens.primary,
9041
+ primaryText: plan.tokens.primaryText,
9042
+ secondary: plan.tokens.secondary,
9043
+ secondaryText: plan.tokens.secondaryText,
9044
+ accent: plan.tokens.accent,
9045
+ background: plan.tokens.background,
9046
+ surface: plan.tokens.surface,
9047
+ surfaceAlt: plan.tokens.surfaceAlt,
9048
+ text: plan.tokens.text,
9049
+ textMuted: plan.tokens.textMuted,
9050
+ border: plan.tokens.border,
9051
+ headerBackground: plan.tokens.headerBackground,
9052
+ headerText: plan.tokens.headerText,
9053
+ footerBackground: plan.tokens.footerBackground,
9054
+ footerText: plan.tokens.footerText
9055
+ },
9056
+ layout: {
9057
+ containerWidth: plan.tokens.containerWidth,
9058
+ borderRadius: plan.tokens.borderRadius
9059
+ }
9060
+ };
9061
+ await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
9062
+ const selectedComponents = {};
9063
+ for (const [role, selected] of Object.entries(plan.selected)) if (selected) selectedComponents[role] = {
9064
+ name: selected.component.name,
9065
+ file: selected.component.file
9066
+ };
9067
+ return {
9068
+ copiedAssets,
9069
+ report: {
9070
+ framework: plan.analysis.framework,
9071
+ sourceRoots: plan.analysis.sourceRoots,
9072
+ componentsAnalyzed: plan.analysis.components.length,
9073
+ selectedComponents,
9074
+ assetsCopied: copiedAssets.length,
9075
+ styleFilesPreserved: plan.styles.length,
9076
+ tailwind: plan.analysis.tailwind,
9077
+ ignoredFiles: plan.analysis.ignoredFiles,
9078
+ warnings: [...new Set(plan.warnings)],
9079
+ validation: {
9080
+ manifest: false,
9081
+ typecheck: false,
9082
+ build: false
9083
+ }
9084
+ }
9085
+ };
9086
+ }
9087
+ async function writeMigrationReport(directory, report) {
9088
+ await writeFile(path.join(directory, "migration-report.json"), `${JSON.stringify(report, null, 2)}\n`, "utf8");
9089
+ }
9090
+ //#endregion
9091
+ //#region src/migrate/transformer.ts
9092
+ var ROLES = [
9093
+ "HEADER",
9094
+ "FOOTER",
9095
+ "HERO",
9096
+ "HOME",
9097
+ "PRODUCT_CARD",
9098
+ "PRODUCT_GRID",
9099
+ "PRODUCT_DETAIL",
9100
+ "SECTION",
9101
+ "PAGE"
9102
+ ];
9103
+ function normalized(value) {
9104
+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
9105
+ }
9106
+ function joinClasses(classes) {
9107
+ return [...new Set(classes)].join(" ");
9108
+ }
9109
+ function matchingNode(component, terms, tags = []) {
9110
+ return component.jsx.find((node) => {
9111
+ const corpus = normalized(`${node.tag} ${node.classes.join(" ")} ${node.text.join(" ")}`);
9112
+ return tags.includes(normalized(node.tag)) || terms.some((term) => corpus.includes(term));
9113
+ });
9114
+ }
9115
+ function classesFor(component, terms, fallback = "", tags = []) {
9116
+ return joinClasses(matchingNode(component, terms, tags)?.classes ?? []) || fallback;
9117
+ }
9118
+ function classProfile(component) {
9119
+ return {
9120
+ root: joinClasses(component.rootClasses),
9121
+ brand: classesFor(component, [
9122
+ "brand",
9123
+ "logo",
9124
+ "marca"
9125
+ ]),
9126
+ navigation: classesFor(component, [
9127
+ "nav",
9128
+ "menu",
9129
+ "navigation"
9130
+ ], "", ["nav"]),
9131
+ title: classesFor(component, [
9132
+ "title",
9133
+ "heading",
9134
+ "headline",
9135
+ "titulo"
9136
+ ], "", ["h1", "h2"]),
9137
+ text: classesFor(component, [
9138
+ "description",
9139
+ "subtitle",
9140
+ "copy",
9141
+ "text",
9142
+ "descricao"
9143
+ ], "", ["p"]),
9144
+ action: classesFor(component, [
9145
+ "button",
9146
+ "btn",
9147
+ "cta",
9148
+ "action"
9149
+ ], "", ["button"]),
9150
+ media: classesFor(component, [
9151
+ "image",
9152
+ "media",
9153
+ "photo",
9154
+ "picture",
9155
+ "imagem"
9156
+ ], "", ["img", "picture"]),
9157
+ grid: classesFor(component, [
9158
+ "grid",
9159
+ "list",
9160
+ "collection",
9161
+ "products"
9162
+ ]),
9163
+ card: classesFor(component, [
9164
+ "card",
9165
+ "item",
9166
+ "product"
9167
+ ], "", ["article"]),
9168
+ content: classesFor(component, [
9169
+ "content",
9170
+ "body",
9171
+ "inner",
9172
+ "container",
9173
+ "wrapper"
9174
+ ])
9175
+ };
9176
+ }
9177
+ function selectedFor(analysis, role) {
9178
+ return analysis.components.filter((component) => component.roles.some((candidate) => candidate.role === role)).sort((left, right) => {
9179
+ const leftScore = left.roles.find((candidate) => candidate.role === role)?.score ?? 0;
9180
+ return (right.roles.find((candidate) => candidate.role === role)?.score ?? 0) - leftScore || Number(right.exported) - Number(left.exported);
9181
+ })[0];
9182
+ }
9183
+ function customProperty(css, terms) {
9184
+ for (const match of css.matchAll(/--([\w-]+)\s*:\s*(#[0-9a-f]{6})\b/gi)) {
9185
+ const name = normalized(match[1]);
9186
+ if (terms.some((term) => name.includes(term))) return match[2].toLowerCase();
9187
+ }
9188
+ return null;
9189
+ }
9190
+ function frequentColors(css) {
9191
+ const counts = /* @__PURE__ */ new Map();
9192
+ for (const match of css.matchAll(/#[0-9a-f]{6}\b/gi)) {
9193
+ const color = match[0].toLowerCase();
9194
+ counts.set(color, (counts.get(color) ?? 0) + 1);
9195
+ }
9196
+ return [...counts.entries()].sort((left, right) => right[1] - left[1]).map(([color]) => color);
9197
+ }
9198
+ function inferredTokens(analysis) {
9199
+ const css = analysis.styles.filter(({ imported }) => imported).map(({ content }) => content).join("\n");
9200
+ const nonNeutral = frequentColors(css).filter((color) => ![
9201
+ "#ffffff",
9202
+ "#000000",
9203
+ "#f8fafc",
9204
+ "#f9fafb",
9205
+ "#111827",
9206
+ "#0f172a"
9207
+ ].includes(color));
9208
+ const widths = [...css.matchAll(/max-width\s*:\s*(\d{3,4})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 960 && value <= 1600);
9209
+ const radii = [...css.matchAll(/border-radius\s*:\s*(\d{1,2})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 0 && value <= 32);
9210
+ const primary = customProperty(css, [
9211
+ "primary",
9212
+ "brand",
9213
+ "principal"
9214
+ ]) ?? nonNeutral[0] ?? "#1d4ed8";
9215
+ const secondary = customProperty(css, ["secondary", "destaque"]) ?? nonNeutral[1] ?? "#f59e0b";
9216
+ const background = customProperty(css, [
9217
+ "background",
9218
+ "fundo",
9219
+ "bg"
9220
+ ]) ?? "#f8fafc";
9221
+ const text = customProperty(css, [
9222
+ "foreground",
9223
+ "text",
9224
+ "texto"
9225
+ ]) ?? "#0f172a";
9226
+ const surface = customProperty(css, [
9227
+ "surface",
9228
+ "card",
9229
+ "panel"
9230
+ ]) ?? "#ffffff";
9231
+ return {
9232
+ primary,
9233
+ primaryText: customProperty(css, ["on-primary", "primary-text"]) ?? "#ffffff",
9234
+ secondary,
9235
+ secondaryText: customProperty(css, ["on-secondary", "secondary-text"]) ?? text,
9236
+ accent: customProperty(css, ["accent", "destaque"]) ?? secondary,
9237
+ background,
9238
+ surface,
9239
+ surfaceAlt: customProperty(css, [
9240
+ "surface-alt",
9241
+ "surface-muted",
9242
+ "subtle"
9243
+ ]) ?? background,
9244
+ text,
9245
+ textMuted: customProperty(css, [
9246
+ "muted",
9247
+ "text-secondary",
9248
+ "subtle-text"
9249
+ ]) ?? "#64748b",
9250
+ border: customProperty(css, [
9251
+ "border",
9252
+ "line",
9253
+ "divider"
9254
+ ]) ?? "#e2e8f0",
9255
+ headerBackground: customProperty(css, ["header-background", "header-bg"]) ?? surface,
9256
+ headerText: customProperty(css, ["header-text", "header-foreground"]) ?? text,
9257
+ footerBackground: customProperty(css, ["footer-background", "footer-bg"]) ?? text,
9258
+ footerText: customProperty(css, ["footer-text", "footer-foreground"]) ?? background,
9259
+ containerWidth: widths[0] ?? 1200,
9260
+ borderRadius: radii[0] ?? 16
9261
+ };
9262
+ }
9263
+ function safeThemeId(value) {
9264
+ const id = value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
9265
+ return id.length >= 2 ? id : "tema-migrado";
9266
+ }
9267
+ function themeName(value) {
9268
+ return value.replace(/^@[^/]+\//, "").split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ").slice(0, 120) || "Tema Migrado";
9269
+ }
9270
+ function createMigrationPlan(analysis, options) {
9271
+ const selected = {};
9272
+ for (const role of ROLES) {
9273
+ const component = selectedFor(analysis, role);
9274
+ if (component) selected[role] = {
9275
+ role,
9276
+ component,
9277
+ classes: classProfile(component)
9278
+ };
9279
+ }
9280
+ const warnings = [...analysis.warnings];
9281
+ for (const item of Object.values(selected)) {
9282
+ if (!item?.component.businessSignals.length) continue;
9283
+ warnings.push(`${item.component.file}: ${item.component.businessSignals.join(", ")} removido(a); apenas a apresentação foi adaptada.`);
9284
+ }
9285
+ if (!selected.HEADER) warnings.push("Header não identificado; será usada a estrutura visual segura do tema base.");
9286
+ if (!selected.FOOTER) warnings.push("Footer não identificado; será usada a estrutura visual segura do tema base.");
9287
+ if (!selected.PRODUCT_CARD) warnings.push("ProductCard não identificado; será usado o card do tema base.");
9288
+ if (analysis.tailwind.detected) warnings.push("Tailwind detectado: classes observadas serão preservadas e recompiladas no tema gerado.");
9289
+ const outputName = path.basename(path.resolve(options.outputDirectory));
9290
+ return {
9291
+ analysis,
9292
+ themeId: safeThemeId(options.id?.trim() || outputName),
9293
+ themeName: options.name?.trim() || themeName(analysis.projectName),
9294
+ selected,
9295
+ styles: analysis.styles.filter(({ imported, file }) => imported && file.endsWith(".css")),
9296
+ assets: analysis.assets,
9297
+ tokens: inferredTokens(analysis),
9298
+ warnings: [...new Set(warnings)]
9299
+ };
9300
+ }
9301
+ //#endregion
9302
+ //#region src/migrate/validator.ts
9303
+ function diagnosticsMessage(diagnostics) {
9304
+ return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
9305
+ getCanonicalFileName: (file) => file,
9306
+ getCurrentDirectory: () => process.cwd(),
9307
+ getNewLine: () => "\n"
9308
+ });
9309
+ }
9310
+ async function typecheck(directory) {
9311
+ const configFile = path.join(directory, "tsconfig.json");
9312
+ const config = ts.readConfigFile(configFile, ts.sys.readFile);
9313
+ if (config.error) throw new Error(`tsconfig inválido:\n${diagnosticsMessage([config.error])}`);
9314
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, directory, { noEmit: true }, configFile);
9315
+ if (parsed.errors.length) throw new Error(`tsconfig inválido:\n${diagnosticsMessage(parsed.errors)}`);
9316
+ const program = ts.createProgram({
9317
+ rootNames: parsed.fileNames,
9318
+ options: parsed.options
9319
+ });
9320
+ const errors = ts.getPreEmitDiagnostics(program).filter(({ category }) => category === ts.DiagnosticCategory.Error);
9321
+ if (errors.length) throw new Error(`O tema gerado não passou no typecheck:\n${diagnosticsMessage(errors.slice(0, 30))}`);
9322
+ }
9323
+ async function validateMigratedTheme(directory, options) {
9324
+ await loadThemeProject(directory);
9325
+ const result = {
9326
+ manifest: true,
9327
+ typecheck: false,
9328
+ build: false
9329
+ };
9330
+ if (!options.runChecks) return result;
9331
+ await typecheck(directory);
9332
+ result.typecheck = true;
9333
+ await themeBuild({ themeDirectory: directory });
9334
+ result.build = true;
9335
+ return result;
9336
+ }
9337
+ //#endregion
9338
+ //#region src/commands/theme/migrate.ts
9339
+ function inside(root, candidate) {
9340
+ const relative = path.relative(root, candidate);
9341
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
9342
+ }
9343
+ async function ensureTargetAvailable(directory) {
9344
+ try {
9345
+ if (!(await stat(directory)).isDirectory()) throw new Error(`O destino já existe e não é uma pasta: ${directory}`);
9346
+ if ((await readdir(directory)).length) throw new Error(`A pasta de destino precisa estar vazia: ${directory}`);
9347
+ return true;
9348
+ } catch (error) {
9349
+ if (error.code === "ENOENT") return false;
9350
+ throw error;
9351
+ }
9352
+ }
9353
+ async function installDependencies(directory) {
9354
+ await new Promise((resolve, reject) => {
9355
+ const child = spawn("npm", [
9356
+ "install",
9357
+ "--ignore-scripts",
9358
+ "--no-audit",
9359
+ "--no-fund"
9360
+ ], {
9361
+ cwd: directory,
9362
+ stdio: "inherit",
9363
+ shell: false
9364
+ });
9365
+ child.once("error", reject);
9366
+ child.once("exit", (code, signal) => {
9367
+ if (code === 0) resolve();
9368
+ else reject(/* @__PURE__ */ new Error(`npm install falhou${signal ? ` (${signal})` : ` com código ${code ?? "desconhecido"}`}.`));
9369
+ });
9370
+ });
9371
+ }
9372
+ var ROLE_LABELS = {
9373
+ HEADER: "Header migrado",
9374
+ FOOTER: "Footer migrado",
9375
+ HERO: "Hero/Banner migrado",
9376
+ HOME: "Home recriada",
9377
+ PRODUCT_CARD: "ProductCard adaptado",
9378
+ PRODUCT_GRID: "ProductGrid adaptado",
9379
+ PRODUCT_DETAIL: "ProductDetail adaptado",
9380
+ SECTION: "Sections genéricas adaptadas"
9381
+ };
9382
+ function printReport(report, outputDirectory) {
9383
+ const framework = report.framework === "next" ? "Next.js" : "Vite";
9384
+ console.log("");
9385
+ console.log(`✓ React + ${framework} identificado`);
9386
+ for (const [role, label] of Object.entries(ROLE_LABELS)) if (report.selectedComponents[role]) console.log(`✓ ${label}`);
9387
+ console.log(`✓ ${report.assetsCopied} asset(s) copiado(s)`);
9388
+ console.log(`✓ ${report.styleFilesPreserved} arquivo(s) de estilo preservado(s)`);
9389
+ if (report.tailwind.detected) console.log("✓ Tailwind detectado e configurado");
9390
+ for (const ignored of report.ignoredFiles) console.log(`⚠ ${ignored.file} ignorado: ${ignored.reason}`);
9391
+ for (const warning of report.warnings) console.log(`⚠ ${warning}`);
9392
+ console.log("");
9393
+ console.log("✓ Manifesto Nuvler validado");
9394
+ if (report.validation.typecheck) console.log("✓ Typecheck concluído");
9395
+ if (report.validation.build) console.log("✓ Build do tema concluído");
9396
+ console.log(`✓ Tema Nuvler gerado em ${outputDirectory}`);
9397
+ console.log("");
9398
+ }
9399
+ async function themeMigrate(options) {
9400
+ const sourceDirectory = path.resolve(options.sourceDirectory);
9401
+ const outputDirectory = path.resolve(options.outputDirectory);
9402
+ if (inside(sourceDirectory, outputDirectory) || inside(outputDirectory, sourceDirectory)) throw new Error("A origem e o destino não podem conter uma à outra. Use uma pasta irmã para preservar o projeto original.");
9403
+ const existingEmptyTarget = await ensureTargetAvailable(outputDirectory);
9404
+ const parent = path.dirname(outputDirectory);
9405
+ const temporary = await mkdtemp(path.join(parent, `.${path.basename(outputDirectory)}.nuvler-migrate-`));
9406
+ try {
9407
+ console.log("");
9408
+ console.log(`Analisando projeto React em ${sourceDirectory}...`);
9409
+ const generated = await generateMigratedTheme(createMigrationPlan(classifyProject(await analyzeReactProject(sourceDirectory)), {
9410
+ outputDirectory,
9411
+ id: options.id,
9412
+ name: options.name
9413
+ }), temporary);
9414
+ if (options.installDependencies !== false) {
9415
+ console.log("Instalando dependências do tema gerado...");
9416
+ await installDependencies(temporary);
9417
+ }
9418
+ generated.report.validation = await validateMigratedTheme(temporary, { runChecks: options.runChecks !== false });
9419
+ await writeMigrationReport(temporary, generated.report);
9420
+ if (existingEmptyTarget) await rmdir(outputDirectory);
9421
+ await rename(temporary, outputDirectory);
9422
+ printReport(generated.report, outputDirectory);
9423
+ return generated.report;
9424
+ } catch (error) {
9425
+ await rm(temporary, {
9426
+ recursive: true,
9427
+ force: true
9428
+ });
9429
+ throw error;
9430
+ }
9431
+ }
9432
+ //#endregion
7839
9433
  //#region src/commands/theme/validate.ts
7840
9434
  async function themeValidate(options) {
7841
9435
  const project = await loadThemeProject(options.themeDirectory);
@@ -7878,7 +9472,7 @@ async function authLogout() {
7878
9472
  //#endregion
7879
9473
  //#region src/index.ts
7880
9474
  var program = new Command();
7881
- program.name("nuvler").description("Nuvler Theme Development CLI").version("0.3.1");
9475
+ program.name("nuvler").description("Nuvler Theme Development CLI").version("0.4.1");
7882
9476
  var theme = program.command("theme").description("Manage Nuvler themes");
7883
9477
  var auth = program.command("auth").description("Manage developer authentication");
7884
9478
  auth.command("login").requiredOption("--token <token>", "Developer token").option("--api-url <url>", "Nuvler API base URL (or use NUVLER_API_URL)").action(async (options) => {
@@ -7905,6 +9499,22 @@ auth.command("logout").action(async () => {
7905
9499
  process.exitCode = 1;
7906
9500
  }
7907
9501
  });
9502
+ theme.command("migrate").description("Analyze a React TypeScript project and generate a Nuvler theme").argument("<source>", "Existing Vite or Next.js project").requiredOption("--output <directory>", "New directory that will receive the Nuvler theme").option("--id <id>", "Generated theme id (defaults to the output directory name)").option("--name <name>", "Generated theme name (defaults to the source project name)").option("--skip-install", "Do not install dependencies in the generated project").option("--skip-checks", "Validate only the manifest; skip typecheck and build").action(async (source, options) => {
9503
+ try {
9504
+ await themeMigrate({
9505
+ sourceDirectory: source,
9506
+ outputDirectory: options.output,
9507
+ id: options.id,
9508
+ name: options.name,
9509
+ installDependencies: !options.skipInstall,
9510
+ runChecks: !options.skipChecks
9511
+ });
9512
+ } catch (error) {
9513
+ const message = error instanceof Error ? error.message : "Erro desconhecido.";
9514
+ console.error(`Erro: ${message}`);
9515
+ process.exitCode = 1;
9516
+ }
9517
+ });
7908
9518
  theme.command("create").description("Create a new theme project from an official template").argument("<directory>", "Directory that will receive the theme").option("--id <id>", "Theme id (defaults to the directory name)").option("--name <name>", "Public theme name").option("--template <template>", "Base template: starter, nuvler-default or nuvler-atelier", "starter").action(async (directory, options) => {
7909
9519
  try {
7910
9520
  await themeCreate({