create-rubrica 1.1.0 → 1.2.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.
Files changed (3) hide show
  1. package/README.md +62 -10
  2. package/dist/index.js +1134 -647
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,79 +1,116 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { intro as intro3 } from "@clack/prompts";
4
+ import { intro as intro2, log as log6 } from "@clack/prompts";
5
5
 
6
6
  // src/commands/create.ts
7
- import { outro, select as select3, multiselect, confirm as confirm2 } from "@clack/prompts";
8
- import * as nodeFsPromises10 from "fs/promises";
7
+ import { outro as outro2, select as select4, confirm as confirm3, isCancel as isCancel5, cancel as cancel4, log as log2, note } from "@clack/prompts";
8
+ import * as nodeFsPromises12 from "fs/promises";
9
9
 
10
10
  // src/prompts/identityPrompt.ts
11
11
  import { text, select, isCancel, cancel } from "@clack/prompts";
12
+
13
+ // src/utils/normalize.ts
14
+ var LOCAL_HOST = /^(localhost|127\.0\.0\.1)(:|\/|$)/i;
15
+ function normalizeUrl(input) {
16
+ const trimmed = input.trim();
17
+ if (!trimmed) return "";
18
+ const scheme = /^(https?):\/\//i.exec(trimmed);
19
+ const withScheme = scheme ? `${scheme[1].toLowerCase()}://${trimmed.slice(scheme[0].length)}` : `${LOCAL_HOST.test(trimmed) ? "http" : "https"}://${trimmed}`;
20
+ return withScheme.replace(/\/+$/, "");
21
+ }
22
+ var URL_EXAMPLE = "N\xE3o parece um endere\xE7o de site. Exemplo: meusite.com";
23
+ function validateUrl(input) {
24
+ if (!input.trim()) return "Informe o endere\xE7o do site (ex: meusite.com)";
25
+ const url = normalizeUrl(input);
26
+ let host;
27
+ try {
28
+ host = new URL(url).hostname;
29
+ } catch {
30
+ return URL_EXAMPLE;
31
+ }
32
+ if (host !== "localhost" && !host.includes(".")) return URL_EXAMPLE;
33
+ return void 0;
34
+ }
35
+ function normalizeHandle(input) {
36
+ const trimmed = input.trim().replace(/[?#].*/, "").replace(/\/+$/, "");
37
+ const lastSegment = trimmed.slice(trimmed.lastIndexOf("/") + 1);
38
+ return lastSegment.replace(/^@/, "");
39
+ }
40
+ function normalizeEmail(input) {
41
+ return input.trim().toLowerCase();
42
+ }
43
+ function validateEmail(input) {
44
+ if (!/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(input.trim())) {
45
+ return "Informe um e-mail v\xE1lido (ex: nome@meusite.com)";
46
+ }
47
+ return void 0;
48
+ }
49
+
50
+ // src/prompts/identityPrompt.ts
12
51
  function assertNotCancelled(value) {
13
52
  if (isCancel(value)) {
14
53
  cancel("Opera\xE7\xE3o cancelada.");
15
54
  throw new Error("Prompt cancelado pelo usu\xE1rio.");
16
55
  }
17
56
  }
18
- async function identityPrompt(defaults) {
19
- const siteName = await text({
20
- message: "Nome do site (aparece no t\xEDtulo do browser e SEO)",
21
- initialValue: defaults?.siteName ?? ""
22
- });
23
- assertNotCancelled(siteName);
24
- const siteUrl = await text({
25
- message: "URL do site (sem barra no final)",
26
- initialValue: defaults?.siteUrl ?? "",
27
- validate: (v) => {
28
- if (!v.startsWith("http://") && !v.startsWith("https://")) {
29
- return "A URL deve come\xE7ar com http:// ou https://";
30
- }
31
- }
57
+ async function ask(opts) {
58
+ const value = await text(opts);
59
+ assertNotCancelled(value);
60
+ return value.trim();
61
+ }
62
+ async function identityPrompt(defaults, options = {}) {
63
+ const skip = options.onlyMissing === true;
64
+ const given = (v) => (v ?? "").trim();
65
+ const authorName = skip && given(defaults?.authorName) ? given(defaults?.authorName) : await ask({
66
+ message: "Seu nome",
67
+ initialValue: defaults?.authorName ?? "",
68
+ validate: (v) => v.trim() ? void 0 : "Informe seu nome"
32
69
  });
33
- assertNotCancelled(siteUrl);
34
- const siteDescription = await text({
35
- message: "Descri\xE7\xE3o curta (SEO e Open Graph)",
70
+ const siteName = skip ? given(defaults?.siteName) || authorName : await ask({
71
+ message: "Nome do site (aparece na aba do navegador e no Google)",
72
+ initialValue: defaults?.siteName ?? authorName
73
+ }) || authorName;
74
+ const siteUrlGiven = skip && given(defaults?.siteUrl) && !validateUrl(given(defaults?.siteUrl));
75
+ const siteUrl = normalizeUrl(
76
+ siteUrlGiven ? given(defaults?.siteUrl) : await ask({
77
+ message: "Endere\xE7o do site (ex: meusite.com \u2014 n\xE3o precisa do https://)",
78
+ initialValue: defaults?.siteUrl ?? "",
79
+ validate: validateUrl
80
+ })
81
+ );
82
+ const siteDescription = skip ? given(defaults?.siteDescription) : await ask({
83
+ message: "Em uma frase, o que voc\xEA faz? (aparece no Google e quando algu\xE9m compartilha o link)",
36
84
  initialValue: defaults?.siteDescription ?? ""
37
85
  });
38
- assertNotCancelled(siteDescription);
39
- const authorName = await text({
40
- message: "Seu nome (para RSS e meta author)",
41
- initialValue: defaults?.authorName ?? ""
42
- });
43
- assertNotCancelled(authorName);
44
- const authorEmail = await text({
45
- message: "Seu email (para RSS \u2014 n\xE3o aparece publicamente)",
46
- initialValue: defaults?.authorEmail ?? "",
47
- validate: (v) => {
48
- if (!v.includes("@") || !v.includes(".")) {
49
- return "Informe um email v\xE1lido (ex: contato@meusite.com)";
50
- }
51
- }
52
- });
53
- assertNotCancelled(authorEmail);
54
- const twitterHandle = await text({
55
- message: "Twitter/X handle (sem @, Enter para pular)",
56
- initialValue: defaults?.twitterHandle ?? ""
57
- });
58
- assertNotCancelled(twitterHandle);
59
- const lang = await select({
60
- message: "Idioma padr\xE3o",
61
- initialValue: defaults?.lang ?? "pt-BR",
62
- options: [
63
- { value: "pt-BR", label: "Portugu\xEAs (pt-BR)" },
64
- { value: "en-US", label: "Ingl\xEAs (en-US)" }
65
- ]
66
- });
67
- assertNotCancelled(lang);
68
- return {
69
- siteName,
70
- siteUrl,
71
- siteDescription,
72
- authorName,
73
- authorEmail,
74
- twitterHandle: twitterHandle ?? "",
75
- lang
76
- };
86
+ const emailGiven = skip && given(defaults?.authorEmail) && !validateEmail(given(defaults?.authorEmail));
87
+ const authorEmail = normalizeEmail(
88
+ emailGiven ? given(defaults?.authorEmail) : await ask({
89
+ message: "Seu e-mail (n\xE3o aparece no site)",
90
+ initialValue: defaults?.authorEmail ?? "",
91
+ validate: validateEmail
92
+ })
93
+ );
94
+ const twitterHandle = normalizeHandle(
95
+ skip ? given(defaults?.twitterHandle) : await ask({
96
+ message: "Seu perfil no X/Twitter (opcional \u2014 Enter para pular)",
97
+ initialValue: defaults?.twitterHandle ?? ""
98
+ })
99
+ );
100
+ let lang = defaults?.lang ?? "pt-BR";
101
+ if (options.askLang !== false) {
102
+ const chosen = await select({
103
+ message: "Idioma do site",
104
+ initialValue: lang,
105
+ options: [
106
+ { value: "pt-BR", label: "Portugu\xEAs (pt-BR)" },
107
+ { value: "en-US", label: "Ingl\xEAs (en-US)" }
108
+ ]
109
+ });
110
+ assertNotCancelled(chosen);
111
+ lang = chosen;
112
+ }
113
+ return { siteName, siteUrl, siteDescription, authorName, authorEmail, twitterHandle, lang };
77
114
  }
78
115
 
79
116
  // src/utils/download.ts
@@ -298,6 +335,18 @@ var LAYOUTS = [
298
335
  function getLayout(id) {
299
336
  return LAYOUTS.find((l) => l.id === id);
300
337
  }
338
+ function recommendedAppearance(layoutId) {
339
+ const layout = getLayout(layoutId);
340
+ if (!layout) throw new Error(`Layout desconhecido: "${layoutId}".`);
341
+ return {
342
+ theme: layout.recommended.scheme,
343
+ colorMode: layout.recommended.mode,
344
+ colorModeToggle: true,
345
+ texture: layout.recommended.texture,
346
+ fontSans: layout.fonts.sans[0],
347
+ fontMono: layout.fonts.mono
348
+ };
349
+ }
301
350
  var COLOR_MODES = [
302
351
  { value: "light", label: "Claro", hint: "fundo claro" },
303
352
  { value: "dark", label: "Escuro", hint: "fundo escuro" },
@@ -632,9 +681,9 @@ async function applyFont(options, paths, fsModule = nodeFsPromises3) {
632
681
 
633
682
  // src/transforms/applyPlugins.ts
634
683
  import * as nodeFsPromises4 from "fs/promises";
635
- async function applyPlugins(plugins, registryPath, fsModule = nodeFsPromises4) {
684
+ async function applyPlugins(plugins2, registryPath, fsModule = nodeFsPromises4) {
636
685
  let content = await fsModule.readFile(registryPath, "utf-8");
637
- for (const [id, enabled] of Object.entries(plugins)) {
686
+ for (const [id, enabled] of Object.entries(plugins2)) {
638
687
  if (!content.includes(`id: '${id}'`)) {
639
688
  throw new Error(`applyPlugins: plugin id "${id}" n\xE3o encontrado em "${registryPath}".`);
640
689
  }
@@ -898,210 +947,239 @@ async function fontPrompts(layoutId, current) {
898
947
  return { fontSans, fontMono };
899
948
  }
900
949
 
901
- // src/commands/create.ts
902
- var ALL_PLUGINS = [
903
- "contact-wizard",
904
- "proposals",
905
- "payments",
906
- "blog",
907
- "portfolio",
908
- "resume",
909
- "about",
910
- "ai-resumes",
911
- "audit-log",
912
- "media-manager",
913
- "i18n",
914
- "playground",
915
- "testimonials",
916
- "testimonials-intake"
950
+ // src/prompts/pluginsPrompt.ts
951
+ import { select as select3, multiselect, isCancel as isCancel3, cancel as cancel2 } from "@clack/prompts";
952
+
953
+ // src/plugins.ts
954
+ var PLUGINS = [
955
+ { id: "contact-wizard", label: "Contato", description: "formul\xE1rio para pedirem or\xE7amento", recommended: true, needsKey: false },
956
+ { id: "proposals", label: "Propostas", description: "propostas comerciais com aceite online", recommended: true, needsKey: false },
957
+ { id: "payments", label: "Pagamentos", description: "cobran\xE7a por PIX, boleto e cart\xE3o (conta no Asaas)", recommended: false, needsKey: true },
958
+ { id: "blog", label: "Blog", description: "posts e artigos", recommended: true, needsKey: false },
959
+ { id: "portfolio", label: "Portf\xF3lio", description: "galeria de projetos e cases", recommended: true, needsKey: false },
960
+ { id: "resume", label: "Curr\xEDculo", description: "curr\xEDculo com download em PDF", recommended: true, needsKey: false },
961
+ { id: "about", label: "Sobre", description: "p\xE1gina sobre voc\xEA", recommended: true, needsKey: false },
962
+ { id: "ai-resumes", label: "Curr\xEDculo com IA", description: "gera vers\xF5es do curr\xEDculo por vaga (chave do OpenRouter)", recommended: false, needsKey: true },
963
+ { id: "audit-log", label: "Hist\xF3rico do painel", description: "registra quem mudou o qu\xEA no painel", recommended: true, needsKey: false },
964
+ { id: "media-manager", label: "Biblioteca de imagens", description: "gerenciador de arquivos e imagens", recommended: false, needsKey: false },
965
+ { id: "i18n", label: "Tradu\xE7\xE3o com IA", description: "traduz o conte\xFAdo do site (chave do OpenRouter)", recommended: false, needsKey: true },
966
+ { id: "playground", label: "Playground", description: "\xE1rea para testar prompts de IA (chave do OpenRouter)", recommended: false, needsKey: true },
967
+ { id: "testimonials", label: "Depoimentos", description: "depoimentos de clientes no site", recommended: true, needsKey: false },
968
+ { id: "testimonials-intake", label: "Coleta de depoimentos", description: "link para clientes enviarem depoimentos", recommended: true, needsKey: false }
917
969
  ];
918
- function validateProjectName(name) {
919
- if (/\s/.test(name)) {
920
- throw new Error(
921
- `Nome inv\xE1lido: "${name}" cont\xE9m espa\xE7os. Use h\xEDfens ou underscores (ex: meu-portfolio).`
922
- );
923
- }
924
- if (/[^a-zA-Z0-9\-_]/.test(name)) {
925
- throw new Error(
926
- `Nome inv\xE1lido: "${name}" cont\xE9m caracteres especiais. Use apenas letras, n\xFAmeros, h\xEDfens e underscores.`
927
- );
970
+ var ALL_PLUGINS = PLUGINS.map((p) => p.id);
971
+ var PLUGIN_PRESETS = [
972
+ {
973
+ id: "recommended",
974
+ label: "Completo",
975
+ hint: "portf\xF3lio, curr\xEDculo, blog, contato, propostas e depoimentos",
976
+ plugins: PLUGINS.filter((p) => p.recommended).map((p) => p.id)
977
+ },
978
+ {
979
+ id: "freelancer",
980
+ label: "Para vender servi\xE7os",
981
+ hint: "portf\xF3lio, contato, propostas e depoimentos",
982
+ plugins: ["contact-wizard", "proposals", "portfolio", "about", "testimonials", "testimonials-intake"]
983
+ },
984
+ {
985
+ id: "simple",
986
+ label: "S\xF3 o portf\xF3lio",
987
+ hint: "portf\xF3lio, curr\xEDculo, sobre e contato",
988
+ plugins: ["contact-wizard", "portfolio", "resume", "about"]
928
989
  }
990
+ ];
991
+ function pluginsRecord(selected) {
992
+ return Object.fromEntries(ALL_PLUGINS.map((id) => [id, selected.includes(id)]));
929
993
  }
930
- async function removeDir(dirPath, fs3) {
931
- if (await fs3.exists(dirPath)) {
932
- await fs3.rm(dirPath, { recursive: true, force: true });
994
+
995
+ // src/prompts/pluginsPrompt.ts
996
+ function assertNotCancelled2(value) {
997
+ if (isCancel3(value)) {
998
+ cancel2("Opera\xE7\xE3o cancelada.");
999
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
933
1000
  }
934
1001
  }
935
- async function runCreate(projectName, deps) {
936
- validateProjectName(projectName);
937
- const fs3 = deps.fs ?? {
938
- ...nodeFsPromises10,
939
- exists: async (p) => {
940
- try {
941
- await nodeFsPromises10.access(p);
942
- return true;
943
- } catch {
944
- return false;
945
- }
946
- }
947
- };
948
- const download = deps.download ?? downloadRelease;
949
- const getVersion = deps.getLatestVersion ?? getLatestVersion;
950
- const applyLayoutFn = deps.applyLayout ?? applyLayout;
951
- const applyThemeFn = deps.applyTheme ?? applyTheme;
952
- const applyFontFn = deps.applyFont ?? applyFont;
953
- const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
954
- const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
955
- const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
956
- const writeStateFn = deps.writeState ?? writeState;
957
- const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
958
- const execFn = deps.exec ?? (async (cmd, cwd) => {
959
- const { execSync } = await import("child_process");
960
- execSync(cmd, { cwd, stdio: "inherit" });
961
- });
962
- const doIdentityPrompt = deps.identityPrompt ?? identityPrompt;
963
- const projectDir = `${deps.projectsDir}/${projectName}`;
964
- const version = await getVersion();
965
- await download(projectDir, version);
966
- const layout = await layoutPrompt();
967
- await applyLayoutFn(
968
- layout,
969
- { projectDir, templatesDir: `${projectDir}/templates` },
970
- fs3
971
- );
972
- const themeChoice = await schemePrompt(layout);
973
- await applyThemeFn(
974
- { preset: themeChoice },
975
- `${projectDir}/src/index.css`,
976
- fs3
977
- );
978
- const appearance = await appearancePrompt(layout);
979
- await applyAppearanceFn(
980
- appearance,
981
- `${projectDir}/index.html`,
982
- fs3
983
- );
984
- const { fontSans, fontMono } = await fontPrompts(layout);
985
- await applyFontFn(
986
- { fontSans, fontMono },
987
- { css: `${projectDir}/src/index.css`, html: `${projectDir}/index.html` },
988
- fs3
989
- );
990
- const selectedPlugins = await multiselect({
991
- message: "Plugins ativos",
992
- options: [
993
- { value: "contact-wizard", label: "Contact Wizard \u2014 formul\xE1rio de contato multi-etapas", hint: "recomendado" },
994
- { value: "proposals", label: "Propostas \u2014 propostas comerciais com assinatura eletr\xF4nica", hint: "recomendado" },
995
- { value: "payments", label: "Pagamentos \u2014 checkout com PIX, boleto e cart\xE3o via Asaas" },
996
- { value: "blog", label: "Blog \u2014 listagem e leitura de posts", hint: "recomendado" },
997
- { value: "portfolio", label: "Portfolio \u2014 galeria de projetos", hint: "recomendado" },
998
- { value: "resume", label: "Curr\xEDculo \u2014 curr\xEDculo interativo com download de PDF", hint: "recomendado" },
999
- { value: "about", label: "Sobre \u2014 p\xE1gina sobre mim", hint: "recomendado" },
1000
- { value: "ai-resumes", label: "CV com IA \u2014 gera\xE7\xE3o de curr\xEDculo customizado por IA" },
1001
- { value: "audit-log", label: "Audit Log \u2014 log de auditoria do painel admin", hint: "recomendado" },
1002
- { value: "media-manager", label: "Media Manager \u2014 gerenciador de arquivos e imagens" },
1003
- { value: "i18n", label: "Tradu\xE7\xE3o IA \u2014 internacionaliza\xE7\xE3o autom\xE1tica de conte\xFAdo" },
1004
- { value: "playground", label: "Playground \u2014 ambiente de testes interativo" },
1005
- { value: "testimonials", label: "Depoimentos \u2014 se\xE7\xE3o de testimoniais de clientes", hint: "recomendado" },
1006
- { value: "testimonials-intake", label: "Coleta de Depoimentos \u2014 formul\xE1rio p\xFAblico para coleta", hint: "recomendado" }
1007
- ],
1008
- required: false
1002
+ function pluginOptions() {
1003
+ return PLUGINS.map((p) => ({ value: p.id, label: `${p.label} \u2014 ${p.description}` }));
1004
+ }
1005
+ async function pluginMultiselect(initialValues) {
1006
+ const chosen = await multiselect({
1007
+ message: "O que o site vai ter? (espa\xE7o marca/desmarca, Enter confirma)",
1008
+ initialValues,
1009
+ required: false,
1010
+ options: pluginOptions()
1009
1011
  });
1010
- const pluginsRecord = Object.fromEntries(
1011
- ALL_PLUGINS.map((id) => [id, selectedPlugins.includes(id)])
1012
- );
1013
- await applyPluginsFn(
1014
- pluginsRecord,
1015
- `${projectDir}/convex/pluginRegistry.ts`,
1016
- fs3
1017
- );
1018
- const identity = await doIdentityPrompt();
1019
- await applyIndexHtmlFn(
1020
- indexHtmlInput(identity, fontSans, fontMono),
1021
- `${projectDir}/index.html`,
1022
- fs3
1023
- );
1024
- await applyRubricalConfigFn(
1025
- rubricaConfigInput(identity, fontSans, fontMono),
1026
- projectDir,
1027
- fs3
1028
- );
1029
- const pkgPath = `${projectDir}/package.json`;
1030
- const pkgRaw = await fs3.readFile(pkgPath, "utf-8");
1031
- const pkg = JSON.parse(pkgRaw);
1032
- pkg.name = projectName;
1033
- await fs3.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
1034
- await writeStateFn(
1035
- projectDir,
1036
- {
1037
- // Versão realmente baixada: o update usa como base para preservar as personalizações.
1038
- version: version.replace(/^v/, ""),
1039
- layout,
1040
- theme: themeChoice,
1041
- ...appearance,
1042
- fontSans,
1043
- fontMono,
1044
- plugins: pluginsRecord,
1045
- identity: {
1046
- siteName: identity.siteName,
1047
- siteUrl: identity.siteUrl,
1048
- siteDescription: identity.siteDescription,
1049
- authorName: identity.authorName,
1050
- authorEmail: identity.authorEmail,
1051
- twitterHandle: identity.twitterHandle,
1052
- lang: identity.lang
1053
- }
1054
- },
1055
- fs3
1056
- );
1057
- const doGitInit = await confirm2({ message: "Inicializar reposit\xF3rio git?" });
1058
- const packageManager = await select3({
1059
- message: "Gerenciador de pacotes",
1012
+ assertNotCancelled2(chosen);
1013
+ return chosen;
1014
+ }
1015
+ async function pluginsPrompt() {
1016
+ const choice = await select3({
1017
+ message: "O que o site vai ter?",
1018
+ initialValue: PLUGIN_PRESETS[0].id,
1060
1019
  options: [
1061
- { value: "pnpm", label: "pnpm (recomendado)" },
1062
- { value: "npm", label: "npm" },
1063
- { value: "none", label: "N\xE3o agora" }
1020
+ ...PLUGIN_PRESETS.map((p) => ({ value: p.id, label: p.label, hint: p.hint })),
1021
+ { value: "custom", label: "Escolher um por um" }
1064
1022
  ]
1065
1023
  });
1066
- if (doGitInit) {
1067
- await execFn("git init", projectDir);
1068
- }
1069
- if (packageManager !== "none") {
1070
- await execFn(`${packageManager} install`, projectDir);
1071
- }
1072
- await removeDir(`${projectDir}/templates`, fs3);
1073
- await removeDir(`${projectDir}/cli`, fs3);
1074
- const installStep = packageManager === "none" ? "pnpm install\n " : "";
1075
- outro(
1076
- `Projeto criado com sucesso!
1077
-
1078
- cd ${projectName}
1079
-
1080
- Pr\xF3ximos passos:
1081
-
1082
- 1. Suba o backend:
1083
- npx convex dev
1084
- (deixe rodando em um terminal)
1085
-
1086
- 2. Configure o ambiente (em outro terminal, com Convex ativo):
1087
- rubrica setup
1024
+ assertNotCancelled2(choice);
1025
+ const preset = PLUGIN_PRESETS.find((p) => p.id === choice);
1026
+ if (preset) return preset.plugins;
1027
+ return pluginMultiselect(PLUGINS.filter((p) => p.recommended).map((p) => p.id));
1028
+ }
1088
1029
 
1089
- 3. Inicie o frontend:
1090
- ${installStep}pnpm dev
1030
+ // src/utils/packageManager.ts
1031
+ function packageManagerFromUserAgent(userAgent) {
1032
+ return userAgent?.startsWith("pnpm/") ? "pnpm" : "npm";
1033
+ }
1091
1034
 
1092
- Boa sorte! \u{1F680}`
1093
- );
1035
+ // src/recipe.ts
1036
+ var RECIPE_VERSION = 1;
1037
+ var KEYS = {
1038
+ layout: "l",
1039
+ scheme: "s",
1040
+ colorMode: "m",
1041
+ colorModeToggle: "a",
1042
+ texture: "t",
1043
+ fontSans: "f",
1044
+ fontMono: "fm",
1045
+ plugins: "p",
1046
+ identity: "i"
1047
+ };
1048
+ var IDENTITY_KEYS = {
1049
+ authorName: "n",
1050
+ siteName: "sn",
1051
+ siteUrl: "u",
1052
+ siteDescription: "d",
1053
+ authorEmail: "e",
1054
+ twitterHandle: "x",
1055
+ lang: "lg",
1056
+ profession: "pf",
1057
+ specialties: "es"
1058
+ };
1059
+ var LANGS = ["pt-BR", "en-US"];
1060
+ function fromBase64Url(code) {
1061
+ const b64 = code.replace(/-/g, "+").replace(/_/g, "/");
1062
+ const binary = atob(b64 + "=".repeat((4 - b64.length % 4) % 4));
1063
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
1064
+ }
1065
+ var INVALID = "Essa receita n\xE3o \xE9 v\xE1lida. Copie o comando de novo no site do Rubrica.";
1066
+ function decodeRecipe(code) {
1067
+ let data;
1068
+ try {
1069
+ const trimmed = code.trim();
1070
+ if (!trimmed) throw new Error("vazio");
1071
+ data = JSON.parse(fromBase64Url(trimmed));
1072
+ } catch {
1073
+ throw new Error(INVALID);
1074
+ }
1075
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(INVALID);
1076
+ const raw = data;
1077
+ const expanded = {};
1078
+ for (const [long, short] of Object.entries(KEYS)) {
1079
+ if (raw[short] !== void 0) expanded[long] = raw[short];
1080
+ }
1081
+ const rawId = raw[KEYS.identity];
1082
+ if (rawId && typeof rawId === "object" && !Array.isArray(rawId)) {
1083
+ const id = {};
1084
+ for (const [long, short] of Object.entries(IDENTITY_KEYS)) {
1085
+ const value = rawId[short];
1086
+ if (value !== void 0) id[long] = value;
1087
+ }
1088
+ expanded.identity = id;
1089
+ }
1090
+ const result = sanitizeRecipe(expanded);
1091
+ if (typeof raw.v === "number" && raw.v > RECIPE_VERSION) {
1092
+ result.warnings.unshift(
1093
+ "Essa receita \xE9 de uma vers\xE3o mais nova do Rubrica. Rode com `npx create-rubrica@latest` para aproveitar tudo."
1094
+ );
1095
+ }
1096
+ return result;
1097
+ }
1098
+ function sanitizeRecipe(input) {
1099
+ const recipe = {};
1100
+ const warnings = [];
1101
+ const str = (v) => typeof v === "string";
1102
+ const pick = (key2, valid, what) => {
1103
+ const value = input[key2];
1104
+ if (!str(value)) return;
1105
+ if (valid(value)) recipe[key2] = value;
1106
+ else warnings.push(`${what} "${value}" n\xE3o existe nesta vers\xE3o; vou perguntar.`);
1107
+ };
1108
+ pick("layout", (v) => LAYOUTS.some((l) => l.id === v), "Layout");
1109
+ pick("scheme", (v) => SCHEMES.some((s) => s.id === v), "Esquema de cores");
1110
+ pick("colorMode", (v) => COLOR_MODES.some((m) => m.value === v), "Modo de cor");
1111
+ pick("texture", (v) => TEXTURES.some((t) => t.value === v), "Textura");
1112
+ pick("fontSans", (v) => SANS_FONTS.some((f) => f.family === v), "Fonte");
1113
+ pick("fontMono", (v) => v === "" || MONO_FONTS.some((f) => f.family === v), "Fonte mono");
1114
+ if (typeof input.colorModeToggle === "boolean") recipe.colorModeToggle = input.colorModeToggle;
1115
+ if (Array.isArray(input.plugins)) {
1116
+ recipe.plugins = [];
1117
+ for (const id of input.plugins) {
1118
+ if (str(id) && PLUGINS.some((p) => p.id === id)) recipe.plugins.push(id);
1119
+ else warnings.push(`Plugin "${String(id)}" n\xE3o existe nesta vers\xE3o; ficou de fora.`);
1120
+ }
1121
+ }
1122
+ const rawId = input.identity;
1123
+ if (rawId && typeof rawId === "object" && !Array.isArray(rawId)) {
1124
+ const id = rawId;
1125
+ const identity = {};
1126
+ for (const key2 of ["authorName", "siteName", "siteDescription", "profession", "specialties"]) {
1127
+ if (str(id[key2]) && id[key2].trim()) identity[key2] = id[key2].trim();
1128
+ }
1129
+ if (str(id.siteUrl) && id.siteUrl.trim()) {
1130
+ if (validateUrl(id.siteUrl)) warnings.push(`Endere\xE7o "${id.siteUrl}" n\xE3o parece v\xE1lido; vou perguntar.`);
1131
+ else identity.siteUrl = normalizeUrl(id.siteUrl);
1132
+ }
1133
+ if (str(id.authorEmail) && id.authorEmail.trim()) {
1134
+ if (validateEmail(id.authorEmail)) warnings.push(`E-mail "${id.authorEmail}" n\xE3o parece v\xE1lido; vou perguntar.`);
1135
+ else identity.authorEmail = normalizeEmail(id.authorEmail);
1136
+ }
1137
+ if (str(id.twitterHandle) && normalizeHandle(id.twitterHandle)) identity.twitterHandle = normalizeHandle(id.twitterHandle);
1138
+ if (str(id.lang)) {
1139
+ if (LANGS.includes(id.lang)) identity.lang = id.lang;
1140
+ else warnings.push(`Idioma "${id.lang}" n\xE3o \xE9 suportado; vou usar pt-BR.`);
1141
+ }
1142
+ if (Object.keys(identity).length) recipe.identity = identity;
1143
+ }
1144
+ return { recipe, warnings };
1145
+ }
1146
+ function recipeSummary(recipe) {
1147
+ const lines = [];
1148
+ if (recipe.layout) lines.push(`Layout: ${getLayout(recipe.layout)?.label ?? recipe.layout}`);
1149
+ const colors = [];
1150
+ if (recipe.scheme) colors.push(SCHEMES.find((s) => s.id === recipe.scheme)?.label ?? recipe.scheme);
1151
+ if (recipe.colorMode) {
1152
+ const mode2 = COLOR_MODES.find((m) => m.value === recipe.colorMode)?.label ?? recipe.colorMode;
1153
+ colors.push(`modo ${mode2.toLowerCase()}`);
1154
+ }
1155
+ if (recipe.colorModeToggle !== void 0) colors.push(recipe.colorModeToggle ? "com bot\xE3o para alternar" : "sem bot\xE3o para alternar");
1156
+ if (colors.length) lines.push(`Cores: ${colors.join(", ")}`);
1157
+ if (recipe.texture) lines.push(`Textura: ${TEXTURES.find((t) => t.value === recipe.texture)?.label ?? recipe.texture}`);
1158
+ if (recipe.fontSans) lines.push(`Fontes: ${[recipe.fontSans, recipe.fontMono].filter(Boolean).join(" e ")}`);
1159
+ if (recipe.plugins) {
1160
+ const names = recipe.plugins.map((id2) => PLUGINS.find((p) => p.id === id2)?.label ?? id2);
1161
+ lines.push(`Plugins: ${names.length ? names.join(", ") : "nenhum"}`);
1162
+ }
1163
+ const id = recipe.identity ?? {};
1164
+ if (id.authorName) lines.push(`Nome: ${id.authorName}`);
1165
+ const site = [id.siteName, id.siteUrl].filter(Boolean).join(" \u2014 ");
1166
+ if (site) lines.push(`Site: ${site}`);
1167
+ if (id.authorEmail) lines.push(`E-mail: ${id.authorEmail}`);
1168
+ if (id.profession) lines.push(`Profiss\xE3o: ${id.profession}${id.specialties ? ` (${id.specialties})` : ""}`);
1169
+ return lines;
1094
1170
  }
1095
1171
 
1096
- // src/commands/config.ts
1097
- import { outro as outro2, multiselect as multiselect2, confirm as confirm3, isCancel as isCancel4, cancel as cancel3, log } from "@clack/prompts";
1098
- import * as nodeFsPromises12 from "fs/promises";
1172
+ // src/commands/setup.ts
1173
+ import { outro, text as text2, password, confirm as confirm2, spinner, isCancel as isCancel4, cancel as cancel3, log } from "@clack/prompts";
1174
+ import * as nodeFsPromises11 from "fs/promises";
1099
1175
  import * as path6 from "path";
1176
+ import * as nodeCrypto from "crypto";
1177
+ import { execFileSync as defaultExecFileSync } from "child_process";
1100
1178
 
1101
1179
  // src/utils/detectProject.ts
1102
- import * as nodeFsPromises11 from "fs/promises";
1180
+ import * as nodeFsPromises10 from "fs/promises";
1103
1181
  import * as path5 from "path";
1104
- async function detectProject(startDir, fsModule = nodeFsPromises11) {
1182
+ async function detectProject(startDir, fsModule = nodeFsPromises10) {
1105
1183
  let current = startDir;
1106
1184
  while (true) {
1107
1185
  const candidate = path5.join(current, "rubrica.json");
@@ -1120,53 +1198,579 @@ async function detectProject(startDir, fsModule = nodeFsPromises11) {
1120
1198
  }
1121
1199
  }
1122
1200
 
1123
- // src/commands/config.ts
1124
- import { tmpdir as tmpdir2 } from "os";
1125
- async function existsIn(fs3, p) {
1126
- try {
1127
- await fs3.access(p);
1128
- return true;
1129
- } catch {
1130
- return false;
1201
+ // src/utils/generateJwtKeys.ts
1202
+ import { generateKeyPair, exportPKCS8, exportJWK } from "jose";
1203
+ async function generateJwtKeys() {
1204
+ const { privateKey, publicKey } = await generateKeyPair("RS256", { extractable: true });
1205
+ const JWT_PRIVATE_KEY = await exportPKCS8(privateKey);
1206
+ const jwk = await exportJWK(publicKey);
1207
+ const JWKS = JSON.stringify({ keys: [{ use: "sig", ...jwk }] });
1208
+ return { JWT_PRIVATE_KEY, JWKS };
1209
+ }
1210
+
1211
+ // src/utils/password.ts
1212
+ function validatePassword(password3) {
1213
+ if (password3.length < 12) return "A senha precisa ter pelo menos 12 caracteres";
1214
+ if (!/[A-Z]/.test(password3)) return "Inclua ao menos uma letra mai\xFAscula";
1215
+ if (!/[a-z]/.test(password3)) return "Inclua ao menos uma letra min\xFAscula";
1216
+ if (!/[0-9]/.test(password3)) return "Inclua ao menos um n\xFAmero";
1217
+ return void 0;
1218
+ }
1219
+
1220
+ // src/commands/setup.ts
1221
+ function parseEnvFile(content) {
1222
+ const result = {};
1223
+ for (const line of content.split("\n")) {
1224
+ const trimmed = line.trim();
1225
+ if (!trimmed || trimmed.startsWith("#")) continue;
1226
+ const eqIdx = trimmed.indexOf("=");
1227
+ if (eqIdx === -1) continue;
1228
+ const key2 = trimmed.slice(0, eqIdx).trim();
1229
+ const value = trimmed.slice(eqIdx + 1).trim();
1230
+ result[key2] = value;
1131
1231
  }
1232
+ return result;
1132
1233
  }
1133
- async function runConfig(deps = {}) {
1234
+ async function runSetup(deps = {}) {
1134
1235
  const cwd = deps.cwd ?? process.cwd();
1135
- const fs3 = deps.fs ?? nodeFsPromises12;
1136
- const detectProjectFn = deps.detectProject ?? detectProject;
1137
- const readStateFn = deps.readState ?? readState;
1138
- const writeStateFn = deps.writeState ?? writeState;
1139
- const doIdentityPrompt = deps.identityPrompt ?? identityPrompt;
1140
- const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
1141
- const applyThemeFn = deps.applyTheme ?? applyTheme;
1142
- const applyFontFn = deps.applyFont ?? applyFont;
1143
- const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
1144
- const applyLayoutFn = deps.applyLayout ?? applyLayout;
1145
- const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
1146
- const downloadReleaseFn = deps.downloadRelease ?? downloadRelease;
1147
- const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
1148
- const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
1149
- const rubricaJsonPath = await detectProjectFn(cwd, fs3);
1150
- const projectDir = path6.dirname(rubricaJsonPath);
1151
- const currentState = await readStateFn(projectDir, fs3);
1152
- const stateUpdate = {};
1153
- const sections = await multiselect2({
1154
- message: "O que deseja reconfigurar?",
1155
- options: [
1156
- { value: "identity", label: "Identidade (nome, URL, SEO, RSS)" },
1157
- { value: "appearance", label: "Apar\xEAncia (esquema de cores, modo claro/escuro, textura, fontes)" },
1158
- { value: "layout", label: "Layout" },
1159
- { value: "plugins", label: "Plugins" }
1160
- ],
1236
+ const fs3 = deps.fs ?? {
1237
+ access: (p) => nodeFsPromises11.access(p).then(() => void 0),
1238
+ readFile: (p, enc) => nodeFsPromises11.readFile(p, enc),
1239
+ writeFile: (p, data) => nodeFsPromises11.writeFile(p, data).then(() => void 0),
1240
+ mkdir: (p, opts) => nodeFsPromises11.mkdir(p, opts).then(() => void 0)
1241
+ };
1242
+ const detectProject2 = deps.detectProject ?? detectProject;
1243
+ const generateJwtKeys2 = deps.generateJwtKeys ?? generateJwtKeys;
1244
+ const readState2 = deps.readState ?? readState;
1245
+ const randomBytes2 = deps.randomBytes ?? ((size) => nodeCrypto.randomBytes(size));
1246
+ const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync(file, args, opts));
1247
+ try {
1248
+ await detectProject2(cwd);
1249
+ } catch (err) {
1250
+ cancel3(err.message);
1251
+ return;
1252
+ }
1253
+ const convex = (...args) => execFileSync("npx", ["convex", ...args], { stdio: "pipe", cwd });
1254
+ const setEnv = (key2, value) => convex("env", "set", "--", key2, value);
1255
+ const envPath = path6.join(cwd, ".env.local");
1256
+ const readEnv = async () => parseEnvFile(await fs3.readFile(envPath, "utf-8"));
1257
+ let envVars = {};
1258
+ try {
1259
+ envVars = await readEnv();
1260
+ } catch {
1261
+ log.info("Conectando o projeto ao Convex (o backend do site). Se pedir, fa\xE7a login no navegador.");
1262
+ try {
1263
+ const args = ["convex", "dev", "--once"];
1264
+ if (deps.newProject) {
1265
+ args.push("--configure", "new", "--project", deps.newProject, "--dev-deployment", "cloud");
1266
+ const convexJson = path6.join(cwd, "convex.json");
1267
+ const exists = await fs3.access(convexJson).then(() => true, () => false);
1268
+ if (!exists) await fs3.writeFile(convexJson, JSON.stringify({ aiFiles: { enabled: false } }, null, 2) + "\n");
1269
+ }
1270
+ execFileSync("npx", args, { stdio: "inherit", cwd });
1271
+ envVars = await readEnv();
1272
+ } catch {
1273
+ cancel3(
1274
+ "N\xE3o deu para conectar ao Convex. Quando quiser tentar de novo, rode: " + (deps.newProject ? `cd ${deps.newProject} && npx create-rubrica setup` : "npx create-rubrica setup (nesta pasta)")
1275
+ );
1276
+ return;
1277
+ }
1278
+ }
1279
+ if (!envVars["VITE_CONVEX_URL"]) {
1280
+ cancel3(
1281
+ "VITE_CONVEX_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1282
+ );
1283
+ return;
1284
+ }
1285
+ if (!envVars["VITE_CONVEX_SITE_URL"]) {
1286
+ cancel3(
1287
+ "VITE_CONVEX_SITE_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1288
+ );
1289
+ return;
1290
+ }
1291
+ const convexSiteUrl = envVars["VITE_CONVEX_SITE_URL"];
1292
+ const state = await readState2(cwd, fs3);
1293
+ const plugins2 = state.plugins;
1294
+ const identity = state.identity ?? {};
1295
+ const s = spinner();
1296
+ s.start("Gerando chaves JWT (RS256)...");
1297
+ const { JWT_PRIVATE_KEY, JWKS } = await generateJwtKeys2();
1298
+ s.stop("Chaves JWT geradas.");
1299
+ setEnv("JWT_PRIVATE_KEY", JWT_PRIVATE_KEY);
1300
+ setEnv("JWKS", JWKS);
1301
+ let siteUrl = normalizeUrl(identity.siteUrl ?? "");
1302
+ if (siteUrl) {
1303
+ log.info(`Endere\xE7o do site: ${siteUrl} (para mudar: npx create-rubrica config)`);
1304
+ } else {
1305
+ const answer = await text2({
1306
+ message: "Endere\xE7o do site (ex: meusite.com \u2014 n\xE3o precisa do https://)",
1307
+ initialValue: "",
1308
+ validate: validateUrl
1309
+ });
1310
+ if (isCancel4(answer)) {
1311
+ cancel3("Setup cancelado.");
1312
+ return;
1313
+ }
1314
+ siteUrl = normalizeUrl(answer);
1315
+ }
1316
+ setEnv("SITE_URL", siteUrl);
1317
+ const optional = async (message, key2) => {
1318
+ const value = await text2({ message, initialValue: "" });
1319
+ if (!isCancel4(value) && value && value.trim()) setEnv(key2, value.trim());
1320
+ };
1321
+ const wants = async (message) => await confirm2({ message, initialValue: false }) === true;
1322
+ const fromSite = deps.site !== void 0;
1323
+ if (!fromSite && (plugins2["contact-wizard"] || plugins2["testimonials-intake"])) {
1324
+ if (await wants("Quer receber um aviso no Telegram a cada novo contato ou depoimento? (d\xE1 para configurar depois)")) {
1325
+ await optional("Token do bot do Telegram (quem cria \xE9 o @BotFather; Enter para pular):", "TELEGRAM_BOT_TOKEN");
1326
+ await optional("Id da conversa que recebe os avisos (Enter para pular):", "TELEGRAM_ADMIN_CHAT_ID");
1327
+ }
1328
+ }
1329
+ if (plugins2["playground"]) {
1330
+ const pepper = randomBytes2(32).toString("hex");
1331
+ setEnv("PLAYGROUND_KEY_PEPPER", pepper);
1332
+ }
1333
+ if (plugins2["ai-resumes"] || plugins2["i18n"] || plugins2["playground"]) {
1334
+ await optional("Chave do OpenRouter, usada nos recursos de IA (openrouter.ai/keys; Enter para pular):", "OPENROUTER_API_KEY");
1335
+ }
1336
+ if (plugins2["payments"]) {
1337
+ const asaasKey = await text2({
1338
+ message: "Chave da API do Asaas, de testes ou de produ\xE7\xE3o (Enter para pular):",
1339
+ initialValue: ""
1340
+ });
1341
+ if (!isCancel4(asaasKey) && asaasKey && asaasKey.trim()) {
1342
+ const key2 = asaasKey.trim();
1343
+ setEnv("ASAAS_API_KEY", key2);
1344
+ const webhookToken = randomBytes2(32).toString("hex");
1345
+ setEnv("ASAAS_WEBHOOK_TOKEN", webhookToken);
1346
+ const env = key2.startsWith("$aact_prod_") ? "produ\xE7\xE3o" : "sandbox (testes)";
1347
+ log.info(
1348
+ `Asaas configurado em ${env}. Falta cadastrar o webhook no painel do Asaas
1349
+ (Integra\xE7\xF5es \u2192 Webhooks \u2192 Adicionar), com os eventos de cobran\xE7a ligados:
1350
+
1351
+ URL: ${convexSiteUrl.replace(/\/+$/, "")}/webhooks/asaas
1352
+ Token: ${webhookToken}
1353
+
1354
+ Sem o webhook, os pagamentos nunca aparecem como pagos.`
1355
+ );
1356
+ }
1357
+ }
1358
+ const savedEmail = normalizeEmail(identity.authorEmail ?? "");
1359
+ let adminExists = false;
1360
+ try {
1361
+ adminExists = execFileSync("npx", ["convex", "run", "users:isSetupRequired"], { stdio: "pipe", cwd }).toString().trim() === "false";
1362
+ } catch {
1363
+ }
1364
+ let adminEmail = savedEmail;
1365
+ if (adminExists) {
1366
+ log.info("O painel j\xE1 tem um admin; o login continua o mesmo. Para trocar a senha: npx create-rubrica senha");
1367
+ } else {
1368
+ if (fromSite && savedEmail && !validateEmail(savedEmail)) {
1369
+ log.info(`Login do painel: ${adminEmail}. Agora escolha a senha.`);
1370
+ } else {
1371
+ const adminEmailAnswer = await text2({
1372
+ message: "E-mail para entrar no painel admin:",
1373
+ initialValue: savedEmail,
1374
+ validate: validateEmail
1375
+ });
1376
+ if (isCancel4(adminEmailAnswer)) {
1377
+ cancel3("Setup cancelado.");
1378
+ return;
1379
+ }
1380
+ adminEmail = normalizeEmail(adminEmailAnswer);
1381
+ }
1382
+ const adminPassword = await password({
1383
+ message: "Senha do painel admin (12 ou mais caracteres, com mai\xFAscula, min\xFAscula e n\xFAmero):",
1384
+ validate: validatePassword
1385
+ });
1386
+ if (isCancel4(adminPassword)) {
1387
+ cancel3("Setup cancelado.");
1388
+ return;
1389
+ }
1390
+ const adminPasswordConfirm = await password({
1391
+ message: "Confirme a senha:",
1392
+ validate: (v) => {
1393
+ if (v !== adminPassword) return "As senhas n\xE3o coincidem";
1394
+ }
1395
+ });
1396
+ if (isCancel4(adminPasswordConfirm)) {
1397
+ cancel3("Setup cancelado.");
1398
+ return;
1399
+ }
1400
+ try {
1401
+ execFileSync(
1402
+ "npx",
1403
+ ["convex", "run", "seed:setupAdmin", JSON.stringify({ email: adminEmail, password: adminPassword })],
1404
+ { stdio: "pipe", cwd }
1405
+ );
1406
+ } catch (err) {
1407
+ const e = err;
1408
+ const output = e.stdout?.toString() || e.stderr?.toString() || e.message || "";
1409
+ if (output.includes("Root user already exists")) {
1410
+ log.warn("O painel j\xE1 tinha um admin; o login continua o mesmo. Para trocar a senha: npx create-rubrica senha");
1411
+ } else {
1412
+ cancel3(`Erro ao criar usu\xE1rio root: ${output || String(err)}`);
1413
+ return;
1414
+ }
1415
+ }
1416
+ }
1417
+ const enabledPlugins = Object.entries(plugins2).filter(([, on]) => on).map(([id]) => id);
1418
+ try {
1419
+ execFileSync(
1420
+ "npx",
1421
+ ["convex", "run", "seed:seedAll", JSON.stringify({ enabledPlugins })],
1422
+ { stdio: "pipe", cwd }
1423
+ );
1424
+ } catch (err) {
1425
+ const output = err.stdout?.toString() || err.stderr?.toString() || err.message;
1426
+ log.warn(`seedAll falhou: ${output.trim() || "erro desconhecido"} \u2014 rode 'npx convex run seed:seedAll "{...}"' manualmente depois.`);
1427
+ }
1428
+ if (identity.siteName) {
1429
+ try {
1430
+ execFileSync(
1431
+ "npx",
1432
+ ["convex", "run", "siteConfig:setBatchInternal", JSON.stringify({
1433
+ items: [
1434
+ { key: "site_title", value: identity.siteName },
1435
+ { key: "site_name", value: identity.siteName },
1436
+ { key: "site_url", value: siteUrl },
1437
+ { key: "site_description", value: identity.siteDescription || "" },
1438
+ { key: "author_name", value: identity.authorName || "" },
1439
+ { key: "author_email", value: identity.authorEmail || "" },
1440
+ { key: "twitter_handle", value: identity.twitterHandle || "" },
1441
+ { key: "lang", value: identity.lang || "pt-BR" }
1442
+ ]
1443
+ })],
1444
+ { stdio: "pipe", cwd }
1445
+ );
1446
+ } catch {
1447
+ }
1448
+ if (identity.authorName) {
1449
+ try {
1450
+ execFileSync(
1451
+ "npx",
1452
+ ["convex", "run", "contactInfo:updateInternal", JSON.stringify({
1453
+ name: identity.authorName,
1454
+ email: identity.authorEmail || "",
1455
+ showEmail: false
1456
+ })],
1457
+ { stdio: "pipe", cwd }
1458
+ );
1459
+ } catch {
1460
+ }
1461
+ }
1462
+ }
1463
+ if (!fromSite && await wants("O site vai ficar na Vercel e voc\xEA quer o bot\xE3o de publicar no painel? (d\xE1 para configurar depois)")) {
1464
+ await optional("Link do Deploy Hook da Vercel (Settings \u2192 Git \u2192 Deploy Hooks; Enter para pular):", "VERCEL_DEPLOY_HOOK_URL");
1465
+ await optional("Segredo do webhook da Vercel (Enter para pular):", "VERCEL_WEBHOOK_SECRET");
1466
+ }
1467
+ const askText = async (message, placeholder) => {
1468
+ const value = await text2({ message, placeholder, initialValue: "" });
1469
+ return isCancel4(value) ? "" : (value || "").trim();
1470
+ };
1471
+ const professionStr = fromSite ? (deps.site?.profession ?? "").trim() : await askText(
1472
+ "Qual \xE9 a sua profiss\xE3o ou \xE1rea de atua\xE7\xE3o? (aparece abaixo do seu nome no site; Enter para pular)",
1473
+ "Ex: Designer UX, Fot\xF3grafa, Advogada, Engenheira Civil..."
1474
+ );
1475
+ const specialtiesStr = fromSite ? (deps.site?.specialties ?? "").trim() : await askText(
1476
+ "Quais s\xE3o suas principais especialidades? (separadas por v\xEDrgula; a IA usa nas propostas; Enter para pular)",
1477
+ "Ex: Branding, Motion Design, Fotografia de Produto"
1478
+ );
1479
+ if (professionStr) {
1480
+ const name = identity.authorName || adminEmail.split("@")[0];
1481
+ const aiContext = specialtiesStr ? `${name} \xE9 ${professionStr} com especialidade em ${specialtiesStr}. Entrega projetos com qualidade e comprometimento.` : `${name} \xE9 ${professionStr}. Entrega projetos com qualidade e comprometimento.`;
1482
+ try {
1483
+ execFileSync(
1484
+ "npx",
1485
+ [
1486
+ "convex",
1487
+ "run",
1488
+ "contactInfo:updateInternal",
1489
+ JSON.stringify({ role: professionStr, roleTranslations: { ptBR: professionStr }, proposalAiContext: aiContext })
1490
+ ],
1491
+ { stdio: "pipe", cwd }
1492
+ );
1493
+ } catch {
1494
+ }
1495
+ }
1496
+ if (fromSite) {
1497
+ log.info(
1498
+ "Avisos no Telegram e o bot\xE3o de publicar da Vercel ficam para depois: quando quiser, rode npx create-rubrica setup nesta pasta."
1499
+ );
1500
+ }
1501
+ outro(
1502
+ `Pronto!
1503
+
1504
+ Admin: ${adminEmail || "o mesmo de antes"}
1505
+ O painel fica em /login
1506
+
1507
+ Para abrir o site:
1508
+ ${deps.nextStep ?? "pnpm dev"}`
1509
+ );
1510
+ }
1511
+
1512
+ // src/commands/create.ts
1513
+ function suggestedSiteUrl(projectName) {
1514
+ return `https://${projectName.toLowerCase().replace(/_/g, "-")}.vercel.app`;
1515
+ }
1516
+ function assertNotCancelled3(value) {
1517
+ if (isCancel5(value)) {
1518
+ cancel4("Opera\xE7\xE3o cancelada.");
1519
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
1520
+ }
1521
+ }
1522
+ function validateProjectName(name) {
1523
+ if (/\s/.test(name)) {
1524
+ throw new Error(
1525
+ `Nome inv\xE1lido: "${name}" cont\xE9m espa\xE7os. Use h\xEDfens ou underscores (ex: meu-portfolio).`
1526
+ );
1527
+ }
1528
+ if (/[^a-zA-Z0-9\-_]/.test(name)) {
1529
+ throw new Error(
1530
+ `Nome inv\xE1lido: "${name}" cont\xE9m caracteres especiais. Use apenas letras, n\xFAmeros, h\xEDfens e underscores.`
1531
+ );
1532
+ }
1533
+ }
1534
+ async function removeDir(dirPath, fs3) {
1535
+ if (await fs3.exists(dirPath)) {
1536
+ await fs3.rm(dirPath, { recursive: true, force: true });
1537
+ }
1538
+ }
1539
+ async function runCreate(projectName, deps) {
1540
+ validateProjectName(projectName);
1541
+ const fs3 = deps.fs ?? {
1542
+ ...nodeFsPromises12,
1543
+ exists: async (p) => {
1544
+ try {
1545
+ await nodeFsPromises12.access(p);
1546
+ return true;
1547
+ } catch {
1548
+ return false;
1549
+ }
1550
+ }
1551
+ };
1552
+ const download = deps.download ?? downloadRelease;
1553
+ const getVersion = deps.getLatestVersion ?? getLatestVersion;
1554
+ const applyLayoutFn = deps.applyLayout ?? applyLayout;
1555
+ const applyThemeFn = deps.applyTheme ?? applyTheme;
1556
+ const applyFontFn = deps.applyFont ?? applyFont;
1557
+ const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
1558
+ const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
1559
+ const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
1560
+ const writeStateFn = deps.writeState ?? writeState;
1561
+ const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
1562
+ const execFn = deps.exec ?? (async (cmd, cwd) => {
1563
+ const { execSync } = await import("child_process");
1564
+ execSync(cmd, { cwd, stdio: "inherit" });
1565
+ });
1566
+ const doIdentityPrompt = deps.identityPrompt ?? identityPrompt;
1567
+ const setupFn = deps.setup ?? runSetup;
1568
+ const packageManager = packageManagerFromUserAgent(deps.userAgent ?? process.env.npm_config_user_agent);
1569
+ const projectDir = `${deps.projectsDir}/${projectName}`;
1570
+ const recipe = deps.recipe ?? {};
1571
+ const fromRecipe = Object.keys(recipe).length > 0;
1572
+ if (fromRecipe) {
1573
+ note(recipeSummary(recipe).join("\n"), "Escolhas que vieram do site");
1574
+ const ok = await confirm3({ message: "Criar com essas escolhas? (o que faltar eu pergunto)", initialValue: true });
1575
+ if (ok !== true) {
1576
+ cancel4("Opera\xE7\xE3o cancelada.");
1577
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
1578
+ }
1579
+ }
1580
+ const mode2 = fromRecipe ? "quick" : await select4({
1581
+ message: "Como voc\xEA quer montar o site?",
1582
+ initialValue: "quick",
1583
+ options: [
1584
+ { value: "quick", label: "R\xE1pido", hint: "escolho o visual, cores e fontes v\xEAm combinadas" },
1585
+ { value: "custom", label: "Personalizado", hint: "escolho cores, modo claro/escuro, textura e fontes" }
1586
+ ]
1587
+ });
1588
+ assertNotCancelled3(mode2);
1589
+ const custom = mode2 === "custom";
1590
+ const version = await getVersion();
1591
+ await download(projectDir, version);
1592
+ const layout = recipe.layout ?? await layoutPrompt();
1593
+ assertNotCancelled3(layout);
1594
+ await applyLayoutFn(
1595
+ layout,
1596
+ { projectDir, templatesDir: `${projectDir}/templates` },
1597
+ fs3
1598
+ );
1599
+ let themeChoice;
1600
+ let appearance;
1601
+ let fontSans;
1602
+ let fontMono;
1603
+ if (custom) {
1604
+ themeChoice = await schemePrompt(layout);
1605
+ appearance = await appearancePrompt(layout);
1606
+ ({ fontSans, fontMono } = await fontPrompts(layout));
1607
+ } else {
1608
+ const rec = recommendedAppearance(layout);
1609
+ themeChoice = recipe.scheme ?? rec.theme;
1610
+ appearance = {
1611
+ colorMode: recipe.colorMode ?? rec.colorMode,
1612
+ colorModeToggle: recipe.colorModeToggle ?? rec.colorModeToggle,
1613
+ texture: recipe.texture ?? rec.texture
1614
+ };
1615
+ fontSans = recipe.fontSans ?? rec.fontSans;
1616
+ fontMono = rec.fontMono === "" ? "" : recipe.fontMono ?? rec.fontMono;
1617
+ }
1618
+ await applyThemeFn(
1619
+ { preset: themeChoice },
1620
+ `${projectDir}/src/index.css`,
1621
+ fs3
1622
+ );
1623
+ await applyAppearanceFn(
1624
+ appearance,
1625
+ `${projectDir}/index.html`,
1626
+ fs3
1627
+ );
1628
+ await applyFontFn(
1629
+ { fontSans, fontMono },
1630
+ { css: `${projectDir}/src/index.css`, html: `${projectDir}/index.html` },
1631
+ fs3
1632
+ );
1633
+ const plugins2 = pluginsRecord(recipe.plugins ?? await pluginsPrompt());
1634
+ await applyPluginsFn(
1635
+ plugins2,
1636
+ `${projectDir}/convex/pluginRegistry.ts`,
1637
+ fs3
1638
+ );
1639
+ const identity = await doIdentityPrompt(
1640
+ { siteUrl: suggestedSiteUrl(projectName), ...recipe.identity },
1641
+ fromRecipe ? { askLang: false, onlyMissing: true } : { askLang: custom }
1642
+ );
1643
+ await applyIndexHtmlFn(
1644
+ indexHtmlInput(identity, fontSans, fontMono),
1645
+ `${projectDir}/index.html`,
1646
+ fs3
1647
+ );
1648
+ await applyRubricalConfigFn(
1649
+ rubricaConfigInput(identity, fontSans, fontMono),
1650
+ projectDir,
1651
+ fs3
1652
+ );
1653
+ const pkgPath = `${projectDir}/package.json`;
1654
+ const pkgRaw = await fs3.readFile(pkgPath, "utf-8");
1655
+ const pkg = JSON.parse(pkgRaw);
1656
+ pkg.name = projectName;
1657
+ await fs3.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
1658
+ await writeStateFn(
1659
+ projectDir,
1660
+ {
1661
+ // Versão realmente baixada: o update usa como base para preservar as personalizações.
1662
+ version: version.replace(/^v/, ""),
1663
+ layout,
1664
+ theme: themeChoice,
1665
+ ...appearance,
1666
+ fontSans,
1667
+ fontMono,
1668
+ plugins: plugins2,
1669
+ identity: {
1670
+ siteName: identity.siteName,
1671
+ siteUrl: identity.siteUrl,
1672
+ siteDescription: identity.siteDescription,
1673
+ authorName: identity.authorName,
1674
+ authorEmail: identity.authorEmail,
1675
+ twitterHandle: identity.twitterHandle,
1676
+ lang: identity.lang
1677
+ }
1678
+ },
1679
+ fs3
1680
+ );
1681
+ try {
1682
+ await execFn("git init", projectDir);
1683
+ } catch {
1684
+ log2.warn("N\xE3o deu para iniciar o git (ele est\xE1 instalado?). O projeto funciona sem; d\xE1 para rodar `git init` depois.");
1685
+ }
1686
+ await execFn(`${packageManager} install`, projectDir);
1687
+ await removeDir(`${projectDir}/templates`, fs3);
1688
+ await removeDir(`${projectDir}/cli`, fs3);
1689
+ await removeDir(`${projectDir}/site`, fs3);
1690
+ const devCommand = `${packageManager} run dev`;
1691
+ const nextStep = `cd ${projectName} && ${devCommand}`;
1692
+ const setupNow = fromRecipe ? true : await confirm3({
1693
+ message: "Configurar o painel admin agora? Abre o login do Convex no navegador (conta gratuita).",
1694
+ initialValue: true
1695
+ });
1696
+ if (setupNow === true) {
1697
+ await setupFn({
1698
+ cwd: projectDir,
1699
+ nextStep,
1700
+ newProject: projectName,
1701
+ ...fromRecipe && {
1702
+ site: { profession: recipe.identity?.profession, specialties: recipe.identity?.specialties }
1703
+ }
1704
+ });
1705
+ return;
1706
+ }
1707
+ outro2(
1708
+ `Projeto criado!
1709
+
1710
+ cd ${projectName}
1711
+
1712
+ Pr\xF3ximos passos:
1713
+
1714
+ 1. Conecte o backend e crie o admin:
1715
+ npx create-rubrica setup
1716
+
1717
+ 2. Abra o site no navegador:
1718
+ ${devCommand}
1719
+
1720
+ Boa sorte! \u{1F680}`
1721
+ );
1722
+ }
1723
+
1724
+ // src/commands/config.ts
1725
+ import { outro as outro3, multiselect as multiselect2, confirm as confirm4, isCancel as isCancel6, cancel as cancel5, log as log3 } from "@clack/prompts";
1726
+ import * as nodeFsPromises13 from "fs/promises";
1727
+ import * as path7 from "path";
1728
+ import { tmpdir as tmpdir2 } from "os";
1729
+ async function existsIn(fs3, p) {
1730
+ try {
1731
+ await fs3.access(p);
1732
+ return true;
1733
+ } catch {
1734
+ return false;
1735
+ }
1736
+ }
1737
+ async function runConfig(deps = {}) {
1738
+ const cwd = deps.cwd ?? process.cwd();
1739
+ const fs3 = deps.fs ?? nodeFsPromises13;
1740
+ const detectProjectFn = deps.detectProject ?? detectProject;
1741
+ const readStateFn = deps.readState ?? readState;
1742
+ const writeStateFn = deps.writeState ?? writeState;
1743
+ const doIdentityPrompt = deps.identityPrompt ?? identityPrompt;
1744
+ const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
1745
+ const applyThemeFn = deps.applyTheme ?? applyTheme;
1746
+ const applyFontFn = deps.applyFont ?? applyFont;
1747
+ const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
1748
+ const applyLayoutFn = deps.applyLayout ?? applyLayout;
1749
+ const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
1750
+ const downloadReleaseFn = deps.downloadRelease ?? downloadRelease;
1751
+ const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
1752
+ const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
1753
+ const rubricaJsonPath = await detectProjectFn(cwd, fs3);
1754
+ const projectDir = path7.dirname(rubricaJsonPath);
1755
+ const currentState = await readStateFn(projectDir, fs3);
1756
+ const stateUpdate = {};
1757
+ const sections = await multiselect2({
1758
+ message: "O que deseja reconfigurar?",
1759
+ options: [
1760
+ { value: "identity", label: "Identidade (nome, URL, SEO, RSS)" },
1761
+ { value: "appearance", label: "Apar\xEAncia (esquema de cores, modo claro/escuro, textura, fontes)" },
1762
+ { value: "layout", label: "Layout" },
1763
+ { value: "plugins", label: "Plugins" }
1764
+ ],
1161
1765
  required: false
1162
1766
  });
1163
- if (isCancel4(sections)) {
1164
- cancel3("Opera\xE7\xE3o cancelada.");
1767
+ if (isCancel6(sections)) {
1768
+ cancel5("Opera\xE7\xE3o cancelada.");
1165
1769
  return;
1166
1770
  }
1167
1771
  const selected = sections;
1168
1772
  if (selected.includes("identity")) {
1169
- const identityData = await doIdentityPrompt();
1773
+ const identityData = await doIdentityPrompt(currentState.identity);
1170
1774
  await applyRubricalConfigFn(
1171
1775
  rubricaConfigInput(identityData, currentState.fontSans, currentState.fontMono),
1172
1776
  projectDir,
@@ -1174,7 +1778,7 @@ async function runConfig(deps = {}) {
1174
1778
  );
1175
1779
  await applyIndexHtmlFn(
1176
1780
  indexHtmlInput(identityData, currentState.fontSans, currentState.fontMono),
1177
- path6.join(projectDir, "index.html"),
1781
+ path7.join(projectDir, "index.html"),
1178
1782
  fs3
1179
1783
  );
1180
1784
  stateUpdate.identity = identityData;
@@ -1187,8 +1791,8 @@ async function runConfig(deps = {}) {
1187
1791
  texture: currentState.texture
1188
1792
  });
1189
1793
  const { fontSans, fontMono } = await fontPrompts(currentState.layout, currentState);
1190
- const cssPath = path6.join(projectDir, "src", "index.css");
1191
- const htmlPath = path6.join(projectDir, "index.html");
1794
+ const cssPath = path7.join(projectDir, "src", "index.css");
1795
+ const htmlPath = path7.join(projectDir, "index.html");
1192
1796
  await applyThemeFn(
1193
1797
  { preset: theme },
1194
1798
  cssPath,
@@ -1197,7 +1801,7 @@ async function runConfig(deps = {}) {
1197
1801
  await applyAppearanceFn(appearance, htmlPath, fs3);
1198
1802
  const css = await fs3.readFile(cssPath, "utf-8").catch(() => "");
1199
1803
  if (css && !css.includes(SCHEME_START)) {
1200
- log.warn(
1804
+ log3.warn(
1201
1805
  "Este projeto \xE9 de uma vers\xE3o sem modo claro/escuro: s\xF3 as 4 cores principais do esquema foram aplicadas. Para ter os dois modos, a altern\xE2ncia e as texturas, atualize com `npx create-rubrica@latest update` e rode o config de novo."
1202
1806
  );
1203
1807
  }
@@ -1221,22 +1825,22 @@ async function runConfig(deps = {}) {
1221
1825
  }
1222
1826
  if (selected.includes("layout")) {
1223
1827
  const newLayout = await layoutPrompt(currentState.layout);
1224
- const confirmed = await confirm3({
1828
+ const confirmed = await confirm4({
1225
1829
  message: "\u26A0 Isso sobrescreve Layout.tsx e arquivos de navega\xE7\xE3o. Customiza\xE7\xF5es manuais ser\xE3o perdidas. Continuar?"
1226
1830
  });
1227
- if (!isCancel4(confirmed) && confirmed === true) {
1228
- let templatesDir = path6.join(projectDir, "templates");
1831
+ if (!isCancel6(confirmed) && confirmed === true) {
1832
+ let templatesDir = path7.join(projectDir, "templates");
1229
1833
  let tmpDir;
1230
1834
  if (!await existsIn(fs3, templatesDir)) {
1231
- tmpDir = await nodeFsPromises12.mkdtemp(path6.join(tmpdir2(), "rubrica-config-"));
1835
+ tmpDir = await nodeFsPromises13.mkdtemp(path7.join(tmpdir2(), "rubrica-config-"));
1232
1836
  const version = currentState.version === "0.1.0" ? await getLatestVersionFn() : currentState.version;
1233
1837
  await downloadReleaseFn(tmpDir, version.startsWith("v") ? version : `v${version}`);
1234
- templatesDir = path6.join(tmpDir, "templates");
1838
+ templatesDir = path7.join(tmpDir, "templates");
1235
1839
  }
1236
1840
  try {
1237
- const layoutsDir = path6.join(templatesDir, "layouts");
1238
- if (await existsIn(fs3, layoutsDir) && !await existsIn(fs3, path6.join(layoutsDir, newLayout))) {
1239
- log.warn(
1841
+ const layoutsDir = path7.join(templatesDir, "layouts");
1842
+ if (await existsIn(fs3, layoutsDir) && !await existsIn(fs3, path7.join(layoutsDir, newLayout))) {
1843
+ log3.warn(
1240
1844
  `O layout "${newLayout}" n\xE3o existe na vers\xE3o ${currentState.version} deste projeto. Atualize o projeto com \`npx create-rubrica@latest update\` e rode o config de novo.`
1241
1845
  );
1242
1846
  return;
@@ -1244,10 +1848,10 @@ async function runConfig(deps = {}) {
1244
1848
  await applyLayoutFn(
1245
1849
  newLayout,
1246
1850
  { projectDir, templatesDir },
1247
- { ...fs3, copyFile: nodeFsPromises12.copyFile, unlink: nodeFsPromises12.unlink, exists: (p) => existsIn(fs3, p) }
1851
+ { ...fs3, copyFile: nodeFsPromises13.copyFile, unlink: nodeFsPromises13.unlink, exists: (p) => existsIn(fs3, p) }
1248
1852
  );
1249
1853
  } finally {
1250
- if (tmpDir) await nodeFsPromises12.rm(tmpDir, { recursive: true, force: true });
1854
+ if (tmpDir) await nodeFsPromises13.rm(tmpDir, { recursive: true, force: true });
1251
1855
  }
1252
1856
  stateUpdate.layout = newLayout;
1253
1857
  }
@@ -1257,17 +1861,17 @@ async function runConfig(deps = {}) {
1257
1861
  const selectedPlugins = await multiselect2({
1258
1862
  message: "Plugins ativos",
1259
1863
  initialValues: activePlugins,
1260
- options: ALL_PLUGINS.map((p) => ({ value: p, label: p })),
1864
+ options: pluginOptions(),
1261
1865
  required: false
1262
1866
  });
1263
- if (!isCancel4(selectedPlugins)) {
1867
+ if (!isCancel6(selectedPlugins)) {
1264
1868
  const pluginsMap = {};
1265
1869
  for (const p of ALL_PLUGINS) {
1266
1870
  pluginsMap[p] = selectedPlugins.includes(p);
1267
1871
  }
1268
1872
  await applyPluginsFn(
1269
1873
  pluginsMap,
1270
- path6.join(projectDir, "convex", "pluginRegistry.ts"),
1874
+ path7.join(projectDir, "convex", "pluginRegistry.ts"),
1271
1875
  fs3
1272
1876
  );
1273
1877
  stateUpdate.plugins = pluginsMap;
@@ -1276,25 +1880,25 @@ async function runConfig(deps = {}) {
1276
1880
  if (Object.keys(stateUpdate).length > 0) {
1277
1881
  await writeStateFn(projectDir, stateUpdate, fs3);
1278
1882
  }
1279
- outro2("Configura\xE7\xE3o atualizada com sucesso!");
1883
+ outro3("Configura\xE7\xE3o atualizada com sucesso!");
1280
1884
  }
1281
1885
 
1282
1886
  // src/commands/update.ts
1283
- import { intro as intro2, outro as outro3, confirm as confirm4, text as text2, isCancel as isCancel5, cancel as cancel4, log as log2, spinner } from "@clack/prompts";
1887
+ import { intro, outro as outro4, confirm as confirm5, text as text3, isCancel as isCancel7, cancel as cancel6, log as log4, spinner as spinner2 } from "@clack/prompts";
1284
1888
  import * as fs2 from "fs/promises";
1285
- import * as path9 from "path";
1889
+ import * as path10 from "path";
1286
1890
  import { tmpdir as tmpdir3 } from "os";
1287
1891
  import { execFile as execFile3 } from "child_process";
1288
1892
  import { promisify as promisify3 } from "util";
1289
1893
 
1290
1894
  // src/utils/pristine.ts
1291
- import * as nodeFsPromises13 from "fs/promises";
1292
- import * as path7 from "path";
1895
+ import * as nodeFsPromises14 from "fs/promises";
1896
+ import * as path8 from "path";
1293
1897
  var fsForTransforms = {
1294
- ...nodeFsPromises13,
1898
+ ...nodeFsPromises14,
1295
1899
  exists: async (p) => {
1296
1900
  try {
1297
- await nodeFsPromises13.access(p);
1901
+ await nodeFsPromises14.access(p);
1298
1902
  return true;
1299
1903
  } catch {
1300
1904
  return false;
@@ -1307,9 +1911,9 @@ async function buildPristine(options) {
1307
1911
  const tag = options.version.startsWith("v") ? options.version : `v${options.version}`;
1308
1912
  const fs3 = fsForTransforms;
1309
1913
  await download(dir, tag);
1310
- await applyLayout(state.layout, { projectDir: dir, templatesDir: path7.join(dir, "templates") }, fs3);
1311
- const cssPath = path7.join(dir, "src", "index.css");
1312
- const htmlPath = path7.join(dir, "index.html");
1914
+ await applyLayout(state.layout, { projectDir: dir, templatesDir: path8.join(dir, "templates") }, fs3);
1915
+ const cssPath = path8.join(dir, "src", "index.css");
1916
+ const htmlPath = path8.join(dir, "index.html");
1313
1917
  await applyTheme({ preset: state.theme }, cssPath, fs3);
1314
1918
  if (state.colorMode) {
1315
1919
  await applyAppearance(
@@ -1319,29 +1923,30 @@ async function buildPristine(options) {
1319
1923
  );
1320
1924
  }
1321
1925
  await applyFont({ fontSans: state.fontSans, fontMono: state.fontMono }, { css: cssPath, html: htmlPath }, fs3);
1322
- const registryPath = path7.join(dir, "convex", "pluginRegistry.ts");
1926
+ const registryPath = path8.join(dir, "convex", "pluginRegistry.ts");
1323
1927
  const knownPlugins = await knownPluginIds(registryPath);
1324
- const plugins = Object.fromEntries(
1928
+ const plugins2 = Object.fromEntries(
1325
1929
  Object.entries(state.plugins ?? {}).filter(([id]) => knownPlugins.has(id))
1326
1930
  );
1327
- await applyPlugins(plugins, registryPath, fs3);
1931
+ await applyPlugins(plugins2, registryPath, fs3);
1328
1932
  const identity = state.identity;
1329
1933
  if (identity) {
1330
1934
  await applyIndexHtml(indexHtmlInput(identity, state.fontSans, state.fontMono), htmlPath, fs3);
1331
1935
  await applyRubricalConfig(rubricaConfigInput(identity, state.fontSans, state.fontMono), dir, fs3);
1332
1936
  }
1333
1937
  if (options.packageName) {
1334
- const pkgPath = path7.join(dir, "package.json");
1335
- const pkg = JSON.parse(await nodeFsPromises13.readFile(pkgPath, "utf-8"));
1938
+ const pkgPath = path8.join(dir, "package.json");
1939
+ const pkg = JSON.parse(await nodeFsPromises14.readFile(pkgPath, "utf-8"));
1336
1940
  pkg.name = options.packageName;
1337
- await nodeFsPromises13.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
1941
+ await nodeFsPromises14.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
1338
1942
  }
1339
- await nodeFsPromises13.rm(path7.join(dir, "templates"), { recursive: true, force: true });
1340
- await nodeFsPromises13.rm(path7.join(dir, "cli"), { recursive: true, force: true });
1943
+ await nodeFsPromises14.rm(path8.join(dir, "templates"), { recursive: true, force: true });
1944
+ await nodeFsPromises14.rm(path8.join(dir, "cli"), { recursive: true, force: true });
1945
+ await nodeFsPromises14.rm(path8.join(dir, "site"), { recursive: true, force: true });
1341
1946
  }
1342
1947
  async function knownPluginIds(registryPath) {
1343
1948
  try {
1344
- const content = await nodeFsPromises13.readFile(registryPath, "utf-8");
1949
+ const content = await nodeFsPromises14.readFile(registryPath, "utf-8");
1345
1950
  return new Set([...content.matchAll(/id: '([^']+)'/g)].map((m) => m[1]));
1346
1951
  } catch {
1347
1952
  return /* @__PURE__ */ new Set();
@@ -1350,7 +1955,7 @@ async function knownPluginIds(registryPath) {
1350
1955
 
1351
1956
  // src/utils/threeWayUpdate.ts
1352
1957
  import * as fs from "fs/promises";
1353
- import * as path8 from "path";
1958
+ import * as path9 from "path";
1354
1959
  import { execFile as execFile2 } from "child_process";
1355
1960
  import { promisify as promisify2 } from "util";
1356
1961
  var execFileAsync2 = promisify2(execFile2);
@@ -1380,8 +1985,8 @@ async function listFiles(root) {
1380
1985
  return;
1381
1986
  }
1382
1987
  for (const entry of entries) {
1383
- const abs = path8.join(dir, entry.name);
1384
- const rel = path8.relative(root, abs).split(path8.sep).join("/");
1988
+ const abs = path9.join(dir, entry.name);
1989
+ const rel = path9.relative(root, abs).split(path9.sep).join("/");
1385
1990
  if (entry.isDirectory()) {
1386
1991
  if (!isProtected(`${rel}/`)) await walk(abs);
1387
1992
  } else if (entry.isFile() && !isProtected(rel)) {
@@ -1407,9 +2012,9 @@ function isBinary(buf) {
1407
2012
  return buf.subarray(0, 8e3).includes(0);
1408
2013
  }
1409
2014
  async function mergeText(ours, base, theirs, tmpDir) {
1410
- const o = path8.join(tmpDir, "ours");
1411
- const b = path8.join(tmpDir, "base");
1412
- const t = path8.join(tmpDir, "theirs");
2015
+ const o = path9.join(tmpDir, "ours");
2016
+ const b = path9.join(tmpDir, "base");
2017
+ const t = path9.join(tmpDir, "theirs");
1413
2018
  await fs.writeFile(o, ours);
1414
2019
  await fs.writeFile(b, base);
1415
2020
  await fs.writeFile(t, theirs);
@@ -1427,13 +2032,13 @@ async function mergeText(ours, base, theirs, tmpDir) {
1427
2032
  }
1428
2033
  async function planUpdate(dirs) {
1429
2034
  const files = /* @__PURE__ */ new Set([...await listFiles(dirs.base), ...await listFiles(dirs.next)]);
1430
- const tmpDir = await fs.mkdtemp(path8.join(path8.dirname(dirs.base), "merge-"));
2035
+ const tmpDir = await fs.mkdtemp(path9.join(path9.dirname(dirs.base), "merge-"));
1431
2036
  const actions = [];
1432
2037
  try {
1433
2038
  for (const file of [...files].sort()) {
1434
- const base = await readOrNull(path8.join(dirs.base, file));
1435
- const next = await readOrNull(path8.join(dirs.next, file));
1436
- const ours = await readOrNull(path8.join(dirs.project, file));
2039
+ const base = await readOrNull(path9.join(dirs.base, file));
2040
+ const next = await readOrNull(path9.join(dirs.next, file));
2041
+ const ours = await readOrNull(path9.join(dirs.project, file));
1437
2042
  if (same(base, next) || same(ours, next)) continue;
1438
2043
  if (same(ours, base)) {
1439
2044
  if (next === null) actions.push({ file, kind: "remove" });
@@ -1453,7 +2058,7 @@ async function planUpdate(dirs) {
1453
2058
  actions.push({ file, kind: "keep", reason: "removido no Rubrica, mas voc\xEA o personalizou" });
1454
2059
  continue;
1455
2060
  }
1456
- if (LOCKFILES.has(path8.basename(file))) {
2061
+ if (LOCKFILES.has(path9.basename(file))) {
1457
2062
  actions.push({ file, kind: "lockfile", reason: "rode o install para atualizar as depend\xEAncias" });
1458
2063
  continue;
1459
2064
  }
@@ -1476,12 +2081,12 @@ async function planUpdate(dirs) {
1476
2081
  }
1477
2082
  async function applyPlan(projectDir, actions) {
1478
2083
  for (const action of actions) {
1479
- const target = path8.join(projectDir, action.file);
2084
+ const target = path9.join(projectDir, action.file);
1480
2085
  switch (action.kind) {
1481
2086
  case "update":
1482
2087
  case "add":
1483
2088
  case "merge":
1484
- await fs.mkdir(path8.dirname(target), { recursive: true });
2089
+ await fs.mkdir(path9.dirname(target), { recursive: true });
1485
2090
  await fs.writeFile(target, action.content);
1486
2091
  break;
1487
2092
  case "remove":
@@ -1489,7 +2094,7 @@ async function applyPlan(projectDir, actions) {
1489
2094
  break;
1490
2095
  case "conflict":
1491
2096
  if (action.incoming) {
1492
- await fs.mkdir(path8.dirname(target), { recursive: true });
2097
+ await fs.mkdir(path9.dirname(target), { recursive: true });
1493
2098
  await fs.writeFile(`${target}${NEW_SUFFIX}`, action.incoming);
1494
2099
  }
1495
2100
  break;
@@ -1579,66 +2184,66 @@ async function runUpdate(deps = {}) {
1579
2184
  const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
1580
2185
  const download = deps.downloadRelease ?? downloadRelease;
1581
2186
  const checkRequiredEnvFn = deps.checkRequiredEnv ?? checkRequiredEnv;
1582
- const ask = !opts.yes;
1583
- intro2("Rubrica Update");
2187
+ const ask2 = !opts.yes;
2188
+ intro("Rubrica Update");
1584
2189
  try {
1585
2190
  await execFileAsync3("git", ["--version"]);
1586
2191
  } catch {
1587
- cancel4("O update precisa do git instalado (ele \xE9 usado para mesclar suas mudan\xE7as com a vers\xE3o nova).");
2192
+ cancel6("O update precisa do git instalado (ele \xE9 usado para mesclar suas mudan\xE7as com a vers\xE3o nova).");
1588
2193
  return;
1589
2194
  }
1590
- const projectDir = path9.dirname(await detectProject(cwd));
2195
+ const projectDir = path10.dirname(await detectProject(cwd));
1591
2196
  const state = await readState(projectDir);
1592
2197
  let fromVersion = normalizeVersion(opts.from ?? state.version);
1593
2198
  if (!opts.from && fromVersion === LEGACY_PLACEHOLDER_VERSION) {
1594
- log2.warn(
2199
+ log4.warn(
1595
2200
  `O rubrica.json diz ${LEGACY_PLACEHOLDER_VERSION}, mas vers\xF5es antigas do CLI sempre gravavam esse n\xFAmero.
1596
2201
  Para preservar suas personaliza\xE7\xF5es, o update precisa saber com qual vers\xE3o o projeto foi criado (veja a data de cria\xE7\xE3o e compare com https://github.com/MierzwaMatheus/rubrica/releases).`
1597
2202
  );
1598
- if (!ask) {
1599
- cancel4("Informe a vers\xE3o de origem com --from <vers\xE3o>.");
2203
+ if (!ask2) {
2204
+ cancel6("Informe a vers\xE3o de origem com --from <vers\xE3o>.");
1600
2205
  return;
1601
2206
  }
1602
- const answer = await text2({
2207
+ const answer = await text3({
1603
2208
  message: "Com qual vers\xE3o o projeto foi criado?",
1604
2209
  placeholder: "ex.: 0.3.12",
1605
2210
  validate: (v) => /^v?\d+\.\d+\.\d+$/.test(v.trim()) ? void 0 : "Use o formato 0.3.12"
1606
2211
  });
1607
- if (isCancel5(answer)) {
1608
- cancel4("Atualiza\xE7\xE3o cancelada.");
2212
+ if (isCancel7(answer)) {
2213
+ cancel6("Atualiza\xE7\xE3o cancelada.");
1609
2214
  return;
1610
2215
  }
1611
2216
  fromVersion = normalizeVersion(answer);
1612
2217
  }
1613
2218
  const toVersion = normalizeVersion(opts.to ?? await getLatestVersionFn());
1614
2219
  if (fromVersion === toVersion) {
1615
- outro3(`J\xE1 est\xE1 na vers\xE3o mais recente (${toVersion}).`);
2220
+ outro4(`J\xE1 est\xE1 na vers\xE3o mais recente (${toVersion}).`);
1616
2221
  return;
1617
2222
  }
1618
2223
  const status = await gitStatus(projectDir);
1619
2224
  if (!opts.dryRun) {
1620
2225
  if (status === null) {
1621
- log2.warn("Este projeto n\xE3o est\xE1 num reposit\xF3rio git. Recomendado: fa\xE7a um backup antes, para poder desfazer.");
2226
+ log4.warn("Este projeto n\xE3o est\xE1 num reposit\xF3rio git. Recomendado: fa\xE7a um backup antes, para poder desfazer.");
1622
2227
  } else if (status !== "") {
1623
- log2.warn("H\xE1 mudan\xE7as n\xE3o commitadas. Recomendado: fa\xE7a commit antes, para poder desfazer o update com o git.");
2228
+ log4.warn("H\xE1 mudan\xE7as n\xE3o commitadas. Recomendado: fa\xE7a commit antes, para poder desfazer o update com o git.");
1624
2229
  }
1625
2230
  }
1626
2231
  if (parseMajor(toVersion) > parseMajor(fromVersion)) {
1627
- log2.warn(
2232
+ log4.warn(
1628
2233
  `Atualiza\xE7\xE3o de vers\xE3o major: ${fromVersion} \u2192 ${toVersion}.
1629
2234
  Leia o guia de atualiza\xE7\xE3o nas notas da release antes de publicar.`
1630
2235
  );
1631
2236
  }
1632
- const workDir = await fs2.mkdtemp(path9.join(tmpdir3(), "rubrica-update-"));
1633
- const baseDir = path9.join(workDir, "base");
1634
- const nextDir = path9.join(workDir, "next");
2237
+ const workDir = await fs2.mkdtemp(path10.join(tmpdir3(), "rubrica-update-"));
2238
+ const baseDir = path10.join(workDir, "base");
2239
+ const nextDir = path10.join(workDir, "next");
1635
2240
  let packageName;
1636
2241
  try {
1637
- packageName = JSON.parse(await fs2.readFile(path9.join(projectDir, "package.json"), "utf-8")).name;
2242
+ packageName = JSON.parse(await fs2.readFile(path10.join(projectDir, "package.json"), "utf-8")).name;
1638
2243
  } catch {
1639
2244
  packageName = void 0;
1640
2245
  }
1641
- const s = spinner();
2246
+ const s = spinner2();
1642
2247
  try {
1643
2248
  s.start(`Baixando ${fromVersion} e ${toVersion}`);
1644
2249
  await buildPristine({ dir: baseDir, version: fromVersion, state, packageName, download });
@@ -1647,17 +2252,17 @@ Leia o guia de atualiza\xE7\xE3o nas notas da release antes de publicar.`
1647
2252
  s.start("Comparando com o seu projeto");
1648
2253
  const actions = await planUpdate({ base: baseDir, next: nextDir, project: projectDir });
1649
2254
  s.stop("Compara\xE7\xE3o conclu\xEDda");
1650
- log2.info(`${fromVersion} \u2192 ${toVersion}
2255
+ log4.info(`${fromVersion} \u2192 ${toVersion}
1651
2256
 
1652
2257
  ${formatPlan(actions)}`);
1653
2258
  if (opts.dryRun) {
1654
- outro3("Simula\xE7\xE3o: nada foi gravado.");
2259
+ outro4("Simula\xE7\xE3o: nada foi gravado.");
1655
2260
  return;
1656
2261
  }
1657
- if (ask) {
1658
- const proceed = await confirm4({ message: `Aplicar a atualiza\xE7\xE3o para ${toVersion}?` });
1659
- if (isCancel5(proceed) || !proceed) {
1660
- cancel4("Atualiza\xE7\xE3o cancelada.");
2262
+ if (ask2) {
2263
+ const proceed = await confirm5({ message: `Aplicar a atualiza\xE7\xE3o para ${toVersion}?` });
2264
+ if (isCancel7(proceed) || !proceed) {
2265
+ cancel6("Atualiza\xE7\xE3o cancelada.");
1661
2266
  return;
1662
2267
  }
1663
2268
  }
@@ -1680,12 +2285,12 @@ ${formatPlan(actions)}`);
1680
2285
  steps.push("Rode o site (pnpm dev) e confira antes de publicar");
1681
2286
  const missingVars = await checkRequiredEnvFn(projectDir, fs2);
1682
2287
  if (missingVars.length > 0) {
1683
- log2.warn(
2288
+ log4.warn(
1684
2289
  `Vari\xE1veis de ambiente faltando no Convex:
1685
2290
  ` + missingVars.map((v) => ` \u2022 ${v.name} \u2014 ${v.description}`).join("\n")
1686
2291
  );
1687
2292
  }
1688
- outro3(`Atualizado para ${toVersion}.
2293
+ outro4(`Atualizado para ${toVersion}.
1689
2294
 
1690
2295
  Pr\xF3ximos passos:
1691
2296
  ${steps.map((st, i) => ` ${i + 1}. ${st}`).join("\n")}`);
@@ -1694,340 +2299,222 @@ ${steps.map((st, i) => ` ${i + 1}. ${st}`).join("\n")}`);
1694
2299
  }
1695
2300
  }
1696
2301
 
1697
- // src/commands/setup.ts
1698
- import { outro as outro4, text as text3, password, spinner as spinner2, isCancel as isCancel6, cancel as cancel5, log as log3 } from "@clack/prompts";
1699
- import * as nodeFsPromises14 from "fs/promises";
1700
- import * as path10 from "path";
1701
- import * as nodeCrypto from "crypto";
1702
- import { execFileSync as defaultExecFileSync } from "child_process";
1703
-
1704
- // src/utils/generateJwtKeys.ts
1705
- import { generateKeyPair, exportPKCS8, exportJWK } from "jose";
1706
- async function generateJwtKeys() {
1707
- const { privateKey, publicKey } = await generateKeyPair("RS256", { extractable: true });
1708
- const JWT_PRIVATE_KEY = await exportPKCS8(privateKey);
1709
- const jwk = await exportJWK(publicKey);
1710
- const JWKS = JSON.stringify({ keys: [{ use: "sig", ...jwk }] });
1711
- return { JWT_PRIVATE_KEY, JWKS };
2302
+ // src/args.ts
2303
+ var VALUE_FLAGS = ["--receita", "--layout", "--esquema", "--modo", "--textura", "--fonte", "--mono", "--plugins"];
2304
+ var key = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]/g, "");
2305
+ var MODES = { claro: "light", escuro: "dark", automatico: "system" };
2306
+ var TEXTURES2 = { nenhuma: "none", grao: "grain", papel: "paper" };
2307
+ function font(value, list) {
2308
+ return list.find((f) => key(f.family) === key(value))?.family ?? value;
1712
2309
  }
1713
-
1714
- // src/commands/setup.ts
1715
- function parseEnvFile(content) {
1716
- const result = {};
1717
- for (const line of content.split("\n")) {
1718
- const trimmed = line.trim();
1719
- if (!trimmed || trimmed.startsWith("#")) continue;
1720
- const eqIdx = trimmed.indexOf("=");
1721
- if (eqIdx === -1) continue;
1722
- const key = trimmed.slice(0, eqIdx).trim();
1723
- const value = trimmed.slice(eqIdx + 1).trim();
1724
- result[key] = value;
2310
+ function plugins(value) {
2311
+ if (key(value) === "nenhum") return [];
2312
+ const preset = PLUGIN_PRESETS.find((p) => p.id === value);
2313
+ if (preset) return [...preset.plugins];
2314
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
2315
+ }
2316
+ function parseCreateArgs(args) {
2317
+ let projectName;
2318
+ let recipeCode;
2319
+ const flags = {};
2320
+ const parseWarnings = [];
2321
+ for (let i = 0; i < args.length; i++) {
2322
+ const arg = args[i];
2323
+ if (!arg.startsWith("--")) {
2324
+ projectName ??= arg;
2325
+ continue;
2326
+ }
2327
+ const eq = arg.indexOf("=");
2328
+ const name = eq === -1 ? arg : arg.slice(0, eq);
2329
+ if (name === "--alternancia") {
2330
+ flags.colorModeToggle = true;
2331
+ continue;
2332
+ }
2333
+ if (name === "--sem-alternancia") {
2334
+ flags.colorModeToggle = false;
2335
+ continue;
2336
+ }
2337
+ if (!VALUE_FLAGS.includes(name)) {
2338
+ parseWarnings.push(`Op\xE7\xE3o desconhecida: ${name} (ignorada).`);
2339
+ continue;
2340
+ }
2341
+ let value;
2342
+ if (eq !== -1) value = arg.slice(eq + 1);
2343
+ else if (args[i + 1] !== void 0 && !args[i + 1].startsWith("--")) value = args[++i];
2344
+ if (!value) {
2345
+ parseWarnings.push(`A op\xE7\xE3o ${name} precisa de um valor (ignorada).`);
2346
+ continue;
2347
+ }
2348
+ switch (name) {
2349
+ case "--receita":
2350
+ recipeCode = value;
2351
+ break;
2352
+ case "--layout":
2353
+ flags.layout = value;
2354
+ break;
2355
+ case "--esquema":
2356
+ flags.scheme = value;
2357
+ break;
2358
+ case "--modo":
2359
+ flags.colorMode = MODES[key(value)] ?? value;
2360
+ break;
2361
+ case "--textura":
2362
+ flags.texture = TEXTURES2[key(value)] ?? value;
2363
+ break;
2364
+ case "--fonte":
2365
+ flags.fontSans = font(value, SANS_FONTS);
2366
+ break;
2367
+ case "--mono":
2368
+ flags.fontMono = font(value, MONO_FONTS);
2369
+ break;
2370
+ case "--plugins":
2371
+ flags.plugins = plugins(value);
2372
+ break;
2373
+ }
1725
2374
  }
1726
- return result;
2375
+ const fromCode = recipeCode ? decodeRecipe(recipeCode) : { recipe: {}, warnings: [] };
2376
+ const fromFlags = sanitizeRecipe(flags);
2377
+ return {
2378
+ projectName,
2379
+ recipe: { ...fromCode.recipe, ...fromFlags.recipe },
2380
+ warnings: [...fromCode.warnings, ...fromFlags.warnings, ...parseWarnings]
2381
+ };
1727
2382
  }
1728
- async function runSetup(deps = {}) {
2383
+
2384
+ // src/commands/password.ts
2385
+ import { outro as outro5, text as text4, password as password2, select as select6, isCancel as isCancel8, cancel as cancel7, log as log5 } from "@clack/prompts";
2386
+ import * as nodeFsPromises15 from "fs/promises";
2387
+ import * as path11 from "path";
2388
+ import { execFileSync as defaultExecFileSync2 } from "child_process";
2389
+ var NOTHING_CHANGED = "Nada foi alterado.";
2390
+ async function runPassword(deps = {}) {
1729
2391
  const cwd = deps.cwd ?? process.cwd();
1730
- const fs3 = deps.fs ?? {
1731
- access: (p) => nodeFsPromises14.access(p).then(() => void 0),
1732
- readFile: (p, enc) => nodeFsPromises14.readFile(p, enc),
1733
- writeFile: (p, data) => nodeFsPromises14.writeFile(p, data).then(() => void 0),
1734
- mkdir: (p, opts) => nodeFsPromises14.mkdir(p, opts).then(() => void 0)
1735
- };
2392
+ const fs3 = deps.fs ?? { readFile: (p, e) => nodeFsPromises15.readFile(p, e) };
1736
2393
  const detectProject2 = deps.detectProject ?? detectProject;
1737
- const generateJwtKeys2 = deps.generateJwtKeys ?? generateJwtKeys;
1738
2394
  const readState2 = deps.readState ?? readState;
1739
- const randomBytes2 = deps.randomBytes ?? ((size) => nodeCrypto.randomBytes(size));
1740
- const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync(file, args, opts));
2395
+ const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync2(file, args, opts));
1741
2396
  try {
1742
2397
  await detectProject2(cwd);
1743
2398
  } catch (err) {
1744
- cancel5(err.message);
1745
- return;
1746
- }
1747
- const envPath = path10.join(cwd, ".env.local");
1748
- let envVars = {};
1749
- try {
1750
- const envContent = await fs3.readFile(envPath, "utf-8");
1751
- envVars = parseEnvFile(envContent);
1752
- } catch {
1753
- cancel5(
1754
- "Arquivo .env.local n\xE3o encontrado. Rode npx convex dev primeiro para cri\xE1-lo."
1755
- );
1756
- return;
1757
- }
1758
- if (!envVars["VITE_CONVEX_URL"]) {
1759
- cancel5(
1760
- "VITE_CONVEX_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1761
- );
1762
- return;
1763
- }
1764
- if (!envVars["VITE_CONVEX_SITE_URL"]) {
1765
- cancel5(
1766
- "VITE_CONVEX_SITE_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1767
- );
2399
+ cancel7(err.message);
1768
2400
  return;
1769
2401
  }
1770
- const siteUrlDefault = envVars["VITE_CONVEX_SITE_URL"];
1771
- const s = spinner2();
1772
- s.start("Gerando chaves JWT (RS256)...");
1773
- const { JWT_PRIVATE_KEY, JWKS } = await generateJwtKeys2();
1774
- s.stop("Chaves JWT geradas.");
1775
- execFileSync("npx", ["convex", "env", "set", "--", "JWT_PRIVATE_KEY", JWT_PRIVATE_KEY], {
1776
- stdio: "pipe"
1777
- });
1778
- execFileSync("npx", ["convex", "env", "set", "--", "JWKS", JWKS], {
1779
- stdio: "pipe"
1780
- });
1781
- const siteUrl = await text3({
1782
- message: "URL p\xFAblica do site (SITE_URL no Convex):",
1783
- initialValue: siteUrlDefault,
1784
- validate: (v) => {
1785
- if (!v || !v.startsWith("http://") && !v.startsWith("https://"))
1786
- return "URL deve come\xE7ar com http:// ou https://";
1787
- }
1788
- });
1789
- if (isCancel6(siteUrl)) {
1790
- cancel5("Setup cancelado.");
2402
+ const connected = await fs3.readFile(path11.join(cwd, ".env.local"), "utf-8").then(
2403
+ (env) => /^CONVEX_DEPLOYMENT=/m.test(env) || /^VITE_CONVEX_URL=/m.test(env),
2404
+ () => false
2405
+ );
2406
+ if (!connected) {
2407
+ cancel7("Este projeto ainda n\xE3o est\xE1 ligado ao Convex, ent\xE3o ainda n\xE3o tem painel. Rode npx create-rubrica setup primeiro.");
1791
2408
  return;
1792
2409
  }
1793
- execFileSync("npx", ["convex", "env", "set", "--", "SITE_URL", siteUrl], {
1794
- stdio: "pipe"
1795
- });
1796
2410
  const state = await readState2(cwd, fs3);
1797
- const plugins = state.plugins;
1798
- if (plugins["contact-wizard"] || plugins["testimonials-intake"]) {
1799
- const telegramToken = await text3({
1800
- message: "TELEGRAM_BOT_TOKEN (Enter para pular):",
1801
- initialValue: ""
1802
- });
1803
- if (!isCancel6(telegramToken) && telegramToken && telegramToken.trim()) {
1804
- execFileSync("npx", ["convex", "env", "set", "--", "TELEGRAM_BOT_TOKEN", telegramToken], { stdio: "pipe" });
1805
- }
1806
- const telegramChatId = await text3({
1807
- message: "TELEGRAM_ADMIN_CHAT_ID (Enter para pular):",
1808
- initialValue: ""
1809
- });
1810
- if (!isCancel6(telegramChatId) && telegramChatId && telegramChatId.trim()) {
1811
- execFileSync("npx", ["convex", "env", "set", "--", "TELEGRAM_ADMIN_CHAT_ID", telegramChatId], { stdio: "pipe" });
1812
- }
1813
- }
1814
- if (plugins["playground"]) {
1815
- const pepper = randomBytes2(32).toString("hex");
1816
- execFileSync("npx", ["convex", "env", "set", "--", "PLAYGROUND_KEY_PEPPER", pepper], { stdio: "pipe" });
1817
- }
1818
- if (plugins["ai-resumes"] || plugins["i18n"] || plugins["playground"]) {
1819
- const openrouterKey = await text3({
1820
- message: "OPENROUTER_API_KEY (Enter para pular):",
1821
- initialValue: ""
1822
- });
1823
- if (!isCancel6(openrouterKey) && openrouterKey && openrouterKey.trim()) {
1824
- execFileSync("npx", ["convex", "env", "set", "--", "OPENROUTER_API_KEY", openrouterKey], { stdio: "pipe" });
1825
- }
1826
- }
1827
- if (plugins["payments"]) {
1828
- const asaasKey = await text3({
1829
- message: "ASAAS_API_KEY \u2014 chave da API do Asaas, sandbox ou produ\xE7\xE3o (Enter para pular):",
1830
- initialValue: ""
1831
- });
1832
- if (!isCancel6(asaasKey) && asaasKey && asaasKey.trim()) {
1833
- const key = asaasKey.trim();
1834
- execFileSync("npx", ["convex", "env", "set", "--", "ASAAS_API_KEY", key], { stdio: "pipe" });
1835
- const webhookToken = randomBytes2(32).toString("hex");
1836
- execFileSync("npx", ["convex", "env", "set", "--", "ASAAS_WEBHOOK_TOKEN", webhookToken], { stdio: "pipe" });
1837
- const env = key.startsWith("$aact_prod_") ? "produ\xE7\xE3o" : "sandbox (testes)";
1838
- log3.info(
1839
- `Asaas configurado em ${env}. Falta cadastrar o webhook no painel do Asaas
1840
- (Integra\xE7\xF5es \u2192 Webhooks \u2192 Adicionar), com os eventos de cobran\xE7a ligados:
1841
-
1842
- URL: ${siteUrlDefault.replace(/\/+$/, "")}/webhooks/asaas
1843
- Token: ${webhookToken}
1844
-
1845
- Sem o webhook, os pagamentos nunca aparecem como pagos.`
1846
- );
1847
- }
1848
- }
1849
- const adminEmail = await text3({
1850
- message: "Email do usu\xE1rio root:",
1851
- validate: (v) => {
1852
- if (!v.includes("@") || !v.includes("."))
1853
- return "Email inv\xE1lido \u2014 deve conter @ e pelo menos um ponto";
1854
- }
2411
+ const identity = state.identity ?? {};
2412
+ const where = await select6({
2413
+ message: "Onde voc\xEA quer trocar a senha?",
2414
+ initialValue: "prod",
2415
+ options: [
2416
+ { value: "prod", label: "No site publicado", hint: "o que est\xE1 no ar" },
2417
+ { value: "dev", label: "No site do seu computador", hint: "o que abre com npm run dev" }
2418
+ ]
1855
2419
  });
1856
- if (isCancel6(adminEmail)) {
1857
- cancel5("Setup cancelado.");
1858
- return;
1859
- }
1860
- const adminPassword = await password({
1861
- message: "Senha do usu\xE1rio root (m\xEDnimo 12 caracteres):",
1862
- validate: (v) => {
1863
- if (v.length < 12) return "Senha deve ter pelo menos 12 caracteres";
1864
- }
2420
+ if (isCancel8(where)) return void cancel7(NOTHING_CHANGED);
2421
+ const emailAnswer = await text4({
2422
+ message: "E-mail de quem entra no painel:",
2423
+ initialValue: normalizeEmail(identity.authorEmail ?? ""),
2424
+ validate: validateEmail
1865
2425
  });
1866
- if (isCancel6(adminPassword)) {
1867
- cancel5("Setup cancelado.");
1868
- return;
1869
- }
1870
- const adminPasswordConfirm = await password({
1871
- message: "Confirme a senha:",
1872
- validate: (v) => {
1873
- if (v !== adminPassword) return "As senhas n\xE3o coincidem";
1874
- }
2426
+ if (isCancel8(emailAnswer)) return void cancel7(NOTHING_CHANGED);
2427
+ const email = normalizeEmail(emailAnswer);
2428
+ const newPassword = await password2({
2429
+ message: "Senha nova (12 ou mais caracteres, com mai\xFAscula, min\xFAscula e n\xFAmero):",
2430
+ validate: validatePassword
1875
2431
  });
1876
- if (isCancel6(adminPasswordConfirm)) {
1877
- cancel5("Setup cancelado.");
1878
- return;
1879
- }
2432
+ if (isCancel8(newPassword)) return void cancel7(NOTHING_CHANGED);
2433
+ const confirmPassword = await password2({
2434
+ message: "Repita a senha nova:",
2435
+ validate: (v) => v !== newPassword ? "As senhas n\xE3o coincidem" : void 0
2436
+ });
2437
+ if (isCancel8(confirmPassword)) return void cancel7(NOTHING_CHANGED);
2438
+ const prod = where === "prod";
1880
2439
  try {
1881
2440
  execFileSync(
1882
2441
  "npx",
1883
- ["convex", "run", "seed:setupAdmin", JSON.stringify({ email: adminEmail, password: adminPassword })],
1884
- { stdio: "pipe" }
2442
+ ["convex", "run", ...prod ? ["--prod"] : [], "users:resetPasswordInternal", JSON.stringify({ email, password: newPassword })],
2443
+ { stdio: "pipe", cwd }
1885
2444
  );
1886
2445
  } catch (err) {
1887
2446
  const e = err;
1888
- const output = e.stdout?.toString() || e.stderr?.toString() || e.message || "";
1889
- if (output.includes("Root user already exists")) {
1890
- log3.warn("Admin j\xE1 configurado \u2014 credenciais mantidas. Para redefinir, acesse o Convex Dashboard.");
1891
- } else {
1892
- cancel5(`Erro ao criar usu\xE1rio root: ${output || String(err)}`);
1893
- return;
1894
- }
1895
- }
1896
- const enabledPlugins = Object.entries(plugins).filter(([, on]) => on).map(([id]) => id);
1897
- try {
1898
- execFileSync(
1899
- "npx",
1900
- ["convex", "run", "seed:seedAll", JSON.stringify({ enabledPlugins })],
1901
- { stdio: "pipe" }
1902
- );
1903
- } catch (err) {
1904
- const output = err.stdout?.toString() || err.stderr?.toString() || err.message;
1905
- log3.warn(`seedAll falhou: ${output.trim() || "erro desconhecido"} \u2014 rode 'npx convex run seed:seedAll "{...}"' manualmente depois.`);
1906
- }
1907
- const identity = state.identity;
1908
- if (identity?.siteName) {
1909
- try {
1910
- execFileSync(
1911
- "npx",
1912
- ["convex", "run", "siteConfig:setBatchInternal", JSON.stringify({
1913
- items: [
1914
- { key: "site_title", value: identity.siteName },
1915
- { key: "site_name", value: identity.siteName },
1916
- { key: "site_url", value: identity.siteUrl || "" },
1917
- { key: "site_description", value: identity.siteDescription || "" },
1918
- { key: "author_name", value: identity.authorName || "" },
1919
- { key: "author_email", value: identity.authorEmail || "" },
1920
- { key: "twitter_handle", value: identity.twitterHandle || "" },
1921
- { key: "lang", value: identity.lang || "pt-BR" }
1922
- ]
1923
- })],
1924
- { stdio: "pipe" }
2447
+ const output = `${e.stderr?.toString() ?? ""}${e.stdout?.toString() ?? ""}` || e.message || "";
2448
+ if (output.includes("Nenhum usu\xE1rio")) {
2449
+ cancel7(`Nenhum usu\xE1rio com o e-mail ${email} neste site. Confira o e-mail e rode de novo.`);
2450
+ } else if (output.includes("No functions found")) {
2451
+ cancel7(
2452
+ prod ? 'O site ainda n\xE3o foi publicado, ent\xE3o n\xE3o h\xE1 senha para trocar l\xE1. Para o site do seu computador, rode de novo e escolha "No site do seu computador".' : "O backend deste projeto est\xE1 vazio. Rode npx create-rubrica setup para configur\xE1-lo."
1925
2453
  );
1926
- } catch {
1927
- }
1928
- if (identity.authorName) {
1929
- try {
1930
- execFileSync(
1931
- "npx",
1932
- ["convex", "run", "contactInfo:updateInternal", JSON.stringify({
1933
- name: identity.authorName,
1934
- email: identity.authorEmail || "",
1935
- showEmail: false
1936
- })],
1937
- { stdio: "pipe" }
1938
- );
1939
- } catch {
1940
- }
1941
- }
1942
- }
1943
- const vercelHookUrl = await text3({
1944
- message: "VERCEL_DEPLOY_HOOK_URL (Enter para pular):",
1945
- initialValue: ""
1946
- });
1947
- if (!isCancel6(vercelHookUrl) && vercelHookUrl && vercelHookUrl.trim()) {
1948
- execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_DEPLOY_HOOK_URL", vercelHookUrl], { stdio: "pipe" });
1949
- }
1950
- const vercelWebhookSecret = await text3({
1951
- message: "VERCEL_WEBHOOK_SECRET (Enter para pular):",
1952
- initialValue: ""
1953
- });
1954
- if (!isCancel6(vercelWebhookSecret) && vercelWebhookSecret && vercelWebhookSecret.trim()) {
1955
- execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_WEBHOOK_SECRET", vercelWebhookSecret], { stdio: "pipe" });
1956
- }
1957
- const profession = await text3({
1958
- message: "Qual \xE9 a sua profiss\xE3o ou \xE1rea de atua\xE7\xE3o? (Enter para usar padr\xE3o tech)",
1959
- placeholder: "Ex: Designer UX, Fot\xF3grafa, Advogada, Engenheira Civil...",
1960
- initialValue: ""
1961
- });
1962
- const specialties = await text3({
1963
- message: "Quais s\xE3o suas principais especialidades? (separadas por v\xEDrgula, Enter para pular)",
1964
- placeholder: "Ex: Branding, Motion Design, Fotografia de Produto",
1965
- initialValue: ""
1966
- });
1967
- const professionStr = isCancel6(profession) ? "" : (profession || "").trim();
1968
- const specialtiesStr = isCancel6(specialties) ? "" : (specialties || "").trim();
1969
- if (professionStr || specialtiesStr) {
1970
- const tags = specialtiesStr ? specialtiesStr.split(",").map((s2) => s2.trim()).filter(Boolean).slice(0, 4).map((label, i) => ({ label, color: i % 2 === 0 ? "primary" : "secondary" })) : [
1971
- { label: "React", color: "primary" },
1972
- { label: "TypeScript", color: "primary" },
1973
- { label: "Arquitetura de Sistemas", color: "secondary" },
1974
- { label: "DevOps & Infraestrutura", color: "secondary" }
1975
- ];
1976
- try {
1977
- execFileSync(
1978
- "npx",
1979
- ["convex", "run", "homeContent:set", JSON.stringify({ key: "hero_tags", value: tags })],
1980
- { stdio: "pipe" }
2454
+ } else if (/Could not find|not found/i.test(output) && output.includes("resetPasswordInternal")) {
2455
+ cancel7(
2456
+ "Este projeto \xE9 de uma vers\xE3o sem a troca de senha pelo terminal. Atualize com npx create-rubrica@latest update" + (prod ? ", publique de novo e rode este comando outra vez." : " e rode de novo.")
2457
+ );
2458
+ } else {
2459
+ cancel7(
2460
+ `N\xE3o deu para trocar a senha:
2461
+ ${output.trim()}` + (prod ? '\n\nSe voc\xEA ainda n\xE3o publicou o site, rode de novo e escolha "No site do seu computador".' : "")
1981
2462
  );
1982
- } catch {
1983
- }
1984
- if (professionStr) {
1985
- const name = adminEmail.split("@")[0];
1986
- const aiContext = specialtiesStr ? `${name} \xE9 ${professionStr} com especialidade em ${specialtiesStr}. Entrega projetos com qualidade e comprometimento.` : `${name} \xE9 ${professionStr}. Entrega projetos com qualidade e comprometimento.`;
1987
- try {
1988
- execFileSync(
1989
- "npx",
1990
- ["convex", "run", "contactInfo:updateInternal", JSON.stringify({ proposalAiContext: aiContext })],
1991
- { stdio: "pipe" }
1992
- );
1993
- } catch {
1994
- }
1995
2463
  }
2464
+ return;
1996
2465
  }
1997
- outro4(
1998
- `Setup conclu\xEDdo!
1999
-
2000
- Admin criado: ${adminEmail}
2001
- Acesse: /login
2466
+ const loginUrl = !prod ? "http://localhost:3000/login" : identity.siteUrl ? `${identity.siteUrl.replace(/\/+$/, "")}/login` : "o /login do seu site";
2467
+ log5.info("Se o login estava bloqueado por tentativas erradas, ele tamb\xE9m foi liberado.");
2468
+ outro5(`Senha trocada!
2002
2469
 
2003
- Pr\xF3ximo passo: pnpm dev`
2004
- );
2470
+ Entre em ${loginUrl}
2471
+ com ${email}`);
2005
2472
  }
2006
2473
 
2007
2474
  // src/index.ts
2008
2475
  async function runCli(argv, cwd) {
2009
2476
  const [, , command, projectName] = argv;
2010
- intro3("Rubrica CLI");
2477
+ intro2("Rubrica CLI");
2011
2478
  if (command === "create") {
2012
2479
  if (!projectName) {
2013
2480
  console.error("Uso: rubrica create <nome-do-projeto>");
2014
2481
  process.exit(1);
2015
2482
  }
2016
- await runCreate(projectName, { projectsDir: cwd });
2483
+ await create(argv.slice(3), cwd);
2017
2484
  } else if (command === "config") {
2018
2485
  await runConfig({ cwd });
2019
2486
  } else if (command === "update") {
2020
2487
  await runUpdate({ cwd, options: parseUpdateOptions(argv.slice(3)) });
2021
2488
  } else if (command === "setup") {
2022
2489
  await runSetup({ cwd });
2490
+ } else if (command === "senha") {
2491
+ await runPassword({ cwd });
2023
2492
  } else if (command && !command.startsWith("-")) {
2024
- await runCreate(command, { projectsDir: cwd });
2493
+ await create(argv.slice(2), cwd);
2025
2494
  } else {
2026
2495
  console.log(
2027
- "Comandos dispon\xEDveis: create <nome-do-projeto> | config | setup\n update [--dry-run] [--from <vers\xE3o>] [--to <vers\xE3o>] [--yes]"
2496
+ "Comandos dispon\xEDveis: create <nome-do-projeto> [--receita <c\xF3digo>] | config | setup | senha\n update [--dry-run] [--from <vers\xE3o>] [--to <vers\xE3o>] [--yes]"
2028
2497
  );
2029
2498
  }
2030
2499
  }
2500
+ async function create(args, cwd) {
2501
+ let parsed;
2502
+ try {
2503
+ parsed = parseCreateArgs(args);
2504
+ } catch (err) {
2505
+ console.error(err.message);
2506
+ process.exitCode = 1;
2507
+ return;
2508
+ }
2509
+ if (!parsed.projectName) {
2510
+ console.error("Uso: npx create-rubrica <nome-da-pasta> [--receita <c\xF3digo>]");
2511
+ process.exitCode = 1;
2512
+ return;
2513
+ }
2514
+ for (const warning of parsed.warnings) log6.warn(warning);
2515
+ const hasRecipe = Object.keys(parsed.recipe).length > 0;
2516
+ await runCreate(parsed.projectName, hasRecipe ? { projectsDir: cwd, recipe: parsed.recipe } : { projectsDir: cwd });
2517
+ }
2031
2518
  function parseUpdateOptions(args) {
2032
2519
  const options = {};
2033
2520
  for (let i = 0; i < args.length; i++) {