create-codeverse 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReadMe.MD +457 -0
- package/bin/cli.js +280 -0
- package/lib/apply/front.js +122 -0
- package/lib/apply/test.js +67 -0
- package/lib/copyTemplate.js +73 -0
- package/lib/desktop.js +13 -0
- package/lib/installDependencies.js +37 -0
- package/lib/openInEditor.js +14 -0
- package/lib/packageJson.js +19 -0
- package/lib/paths.js +4 -0
- package/lib/prompts.js +68 -0
- package/lib/runCommand.js +40 -0
- package/lib/secret.js +80 -0
- package/lib/templates.js +79 -0
- package/lib/validateProjectName.js +24 -0
- package/lib/versions.js +50 -0
- package/package.json +46 -6
- package/templates/codeskills.enc +0 -0
- package/templates/extras/test-componentes/cypress/component/Login.cy.jsx +120 -0
- package/templates/extras/test-componentes/cypress/fixtures/example.json +5 -0
- package/templates/extras/test-componentes/cypress/support/commands.js +25 -0
- package/templates/extras/test-componentes/cypress/support/component-index.html +14 -0
- package/templates/extras/test-componentes/cypress/support/component.js +24 -0
- package/templates/extras/test-componentes/cypress.config.js +10 -0
- package/templates/extras/test-componentes/src/app/page.jsx +5 -0
- package/templates/extras/test-componentes/src/components/Login.jsx +47 -0
- package/templates/extras/test-dependencias/tests/nome-do-script.test.js +79 -0
- package/templates/front/.env.example +0 -0
- package/templates/front/ReadMe.MD +36 -0
- package/templates/front/_gitignore +42 -0
- package/templates/front/biome.json +42 -0
- package/templates/front/jsconfig.json +8 -0
- package/templates/front/next.config.mjs +11 -0
- package/templates/front/package.template.json +41 -0
- package/templates/front/public/fonts/gitkeep +0 -0
- package/templates/front/public/icons/gitkeep +0 -0
- package/templates/front/public/images/gitkeep +0 -0
- package/templates/front/public/media/gitkeep +0 -0
- package/templates/front/public/sounds/gitkeep +0 -0
- package/templates/front/src/app/favicon.ico +0 -0
- package/templates/front/src/app/globals.css +9 -0
- package/templates/front/src/app/layout.js +14 -0
- package/templates/front/src/app/nome-da-rota/nome-da-rota.module.css +0 -0
- package/templates/front/src/app/nome-da-rota/page.jsx +5 -0
- package/templates/front/src/app/page.jsx +39 -0
- package/templates/front/src/app/page.module.css +98 -0
- package/templates/front/src/components/Nome-do-componente.jsx +5 -0
- package/templates/front/src/components/Nome-do-componente.module.css +0 -0
- package/templates/integracao/cypress/e2e/meu-teste.cy.js +75 -0
- package/templates/integracao/cypress/fixtures/example.json +5 -0
- package/templates/integracao/cypress/support/commands.js +25 -0
- package/templates/integracao/cypress/support/e2e.js +17 -0
- package/templates/integracao/cypress.config.js +7 -0
- package/templates/integracao/package.template.json +37 -0
- package/templates/test/.env.example +0 -0
- package/templates/test/_gitignore +25 -0
- package/templates/test/jest.reporters.config.mjs +14 -0
- package/templates/test/package.template.json +42 -0
- package/templates/test/src/nome-do-seu-script.js +4 -0
- package/templates/test/tests/nome-do-script.test.js +40 -0
- package/templates/versions.json +81 -0
- package/README.md +0 -3
package/bin/cli.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
cancel,
|
|
8
|
+
confirm,
|
|
9
|
+
intro,
|
|
10
|
+
log,
|
|
11
|
+
multiselect,
|
|
12
|
+
note,
|
|
13
|
+
outro,
|
|
14
|
+
password,
|
|
15
|
+
select,
|
|
16
|
+
spinner,
|
|
17
|
+
text,
|
|
18
|
+
} from '@clack/prompts';
|
|
19
|
+
|
|
20
|
+
import { copyTemplate, writeSecretTemplate } from '../lib/copyTemplate.js';
|
|
21
|
+
import { getDesktopDir } from '../lib/desktop.js';
|
|
22
|
+
import {
|
|
23
|
+
buildInstallCommands,
|
|
24
|
+
formatCommand,
|
|
25
|
+
installDependencies,
|
|
26
|
+
} from '../lib/installDependencies.js';
|
|
27
|
+
import { isInsideVsCode, openInEditor } from '../lib/openInEditor.js';
|
|
28
|
+
import { writePackageJson } from '../lib/packageJson.js';
|
|
29
|
+
import {
|
|
30
|
+
alignedOptions,
|
|
31
|
+
configurePrompts,
|
|
32
|
+
countdown,
|
|
33
|
+
exitIfCancel,
|
|
34
|
+
replaceAnswerLine,
|
|
35
|
+
} from '../lib/prompts.js';
|
|
36
|
+
import { openSecretTemplate } from '../lib/secret.js';
|
|
37
|
+
import { templates } from '../lib/templates.js';
|
|
38
|
+
import { validateProjectName } from '../lib/validateProjectName.js';
|
|
39
|
+
import { resolvePackages } from '../lib/versions.js';
|
|
40
|
+
|
|
41
|
+
const OPEN_DELAY_SECONDS = 5;
|
|
42
|
+
|
|
43
|
+
async function main() {
|
|
44
|
+
console.clear();
|
|
45
|
+
configurePrompts();
|
|
46
|
+
intro('Bem-vindo(a) ao CodeVerse ⚡');
|
|
47
|
+
note(
|
|
48
|
+
'Seu ambiente de desenvolvimento começa aqui ... 💫',
|
|
49
|
+
'O que vamos construir hoje? 🙌',
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
const devName = exitIfCancel(
|
|
53
|
+
await text({
|
|
54
|
+
message: 'Qual é o seu nome, DEV? 👧',
|
|
55
|
+
placeholder: 'Buguilino Undefined NotNull',
|
|
56
|
+
validate: (raw) => {
|
|
57
|
+
if (!String(raw ?? '').trim()) return 'Digite o seu nome, fera ...';
|
|
58
|
+
},
|
|
59
|
+
}),
|
|
60
|
+
).trim();
|
|
61
|
+
|
|
62
|
+
const { dir: baseDir, isDesktop } = getDesktopDir();
|
|
63
|
+
const placeLabel = isDesktop ? 'na Área de Trabalho' : 'nesta pasta';
|
|
64
|
+
|
|
65
|
+
const projectName = exitIfCancel(
|
|
66
|
+
await text({
|
|
67
|
+
message: 'Qual é o nome do seu projeto/app? 💻',
|
|
68
|
+
placeholder: 'num-crasha-por-favor',
|
|
69
|
+
validate: (raw) => {
|
|
70
|
+
const result = validateProjectName(raw);
|
|
71
|
+
if (!result.valid) return result.message;
|
|
72
|
+
if (existsSync(join(baseDir, result.value))) {
|
|
73
|
+
return `Já existe uma pasta com esse nome ${placeLabel}. Escolha outro nome.`;
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
}),
|
|
77
|
+
).trim();
|
|
78
|
+
|
|
79
|
+
const targetDir = join(baseDir, projectName);
|
|
80
|
+
|
|
81
|
+
// Sem Área de Trabalho, o projeto vai para a pasta onde o comando rodou, mas
|
|
82
|
+
// só depois de o aluno confirmar (Enter = S). Com "n", nada é criado.
|
|
83
|
+
if (!isDesktop) {
|
|
84
|
+
note(
|
|
85
|
+
`O projeto será salvo na pasta atual do terminal:\n \u001b[32m${targetDir}\u001b[0m`,
|
|
86
|
+
'Não encontrei a Área de Trabalho 😢',
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const keepGoing = exitIfCancel(
|
|
90
|
+
await confirm({
|
|
91
|
+
message: 'Continuar e salvar aqui?',
|
|
92
|
+
initialValue: true,
|
|
93
|
+
}),
|
|
94
|
+
);
|
|
95
|
+
if (!keepGoing) {
|
|
96
|
+
cancel('Operação cancelada. Nada foi criado. 😢');
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Ordem alfabética, exceto os templates com `last: true`, que ficam sempre no fim.
|
|
102
|
+
const sortedTemplates = [...templates].sort(
|
|
103
|
+
(a, b) => Boolean(a.last) - Boolean(b.last) || a.label.localeCompare(b.label, 'pt-BR'),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
// Templates com `secret: true` pedem o código secreto. Código errado volta
|
|
107
|
+
// para este menu; código certo deixa em `secretFiles` os arquivos já abertos.
|
|
108
|
+
let template;
|
|
109
|
+
let secretFiles = null;
|
|
110
|
+
while (true) {
|
|
111
|
+
const templateId = exitIfCancel(
|
|
112
|
+
await select({
|
|
113
|
+
showInstructions: false,
|
|
114
|
+
message: 'O que vamos construir hoje? Sua próxima grande ideia começa aqui! ✨',
|
|
115
|
+
options: alignedOptions(sortedTemplates),
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
template = templates.find((item) => item.id === templateId);
|
|
120
|
+
|
|
121
|
+
if (!template.ready) {
|
|
122
|
+
note('Em breve teremos muito mais novidades para vocês!!!', 'Estamos trabalhando nisso 🚧');
|
|
123
|
+
outro('Até a próxima, DEV! 🚀');
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!template.secret) break;
|
|
128
|
+
|
|
129
|
+
const code = exitIfCancel(
|
|
130
|
+
await password({
|
|
131
|
+
message: 'Digite o código super secreto 🔒',
|
|
132
|
+
validate: (raw) => {
|
|
133
|
+
if (!String(raw ?? '')) return 'Digite o código, fera ...';
|
|
134
|
+
},
|
|
135
|
+
}),
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
const checking = spinner();
|
|
139
|
+
checking.start('Verificando o código...');
|
|
140
|
+
try {
|
|
141
|
+
secretFiles = await openSecretTemplate(template.id, code);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
checking.error(err.message);
|
|
144
|
+
process.exitCode = 1;
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (secretFiles) {
|
|
148
|
+
checking.stop('Código aceito! 🔓');
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
checking.error('Código inválido. Escolha o template de novo. 😢');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Templates com `choice` (ex.: Test) escolhem um sub-template de seleção única,
|
|
155
|
+
// com pasta (`dir`), extras e `apply` próprios. Os demais usam multiselect de extras.
|
|
156
|
+
let dir = template.id;
|
|
157
|
+
let versionPaths = null;
|
|
158
|
+
let chosenOptions = [];
|
|
159
|
+
let apply = template.apply;
|
|
160
|
+
if (template.choice) {
|
|
161
|
+
// Ordem fixa definida em lib/templates.js (não alfabética).
|
|
162
|
+
const choiceId = exitIfCancel(
|
|
163
|
+
await select({
|
|
164
|
+
showInstructions: false,
|
|
165
|
+
message: 'Que tipo de teste você vai fazer? 🧪',
|
|
166
|
+
options: alignedOptions(template.options),
|
|
167
|
+
}),
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
const choice = template.options.find((item) => item.id === choiceId);
|
|
171
|
+
if (!choice.ready) {
|
|
172
|
+
note(
|
|
173
|
+
'Em breve teremos muito mais novidades para vocês!!!',
|
|
174
|
+
'Estamos trabalhando nisso 🚧',
|
|
175
|
+
);
|
|
176
|
+
outro('Até a próxima, DEV! 🚀');
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
dir = choice.dir;
|
|
181
|
+
versionPaths = choice.versions;
|
|
182
|
+
apply = choice.apply;
|
|
183
|
+
} else if (template.options?.length) {
|
|
184
|
+
const sortedOptions = [...template.options].sort((a, b) =>
|
|
185
|
+
a.label.localeCompare(b.label, 'pt-BR'),
|
|
186
|
+
);
|
|
187
|
+
const extraOptions = alignedOptions(sortedOptions);
|
|
188
|
+
chosenOptions = exitIfCancel(
|
|
189
|
+
await multiselect({
|
|
190
|
+
showInstructions: false,
|
|
191
|
+
message: 'Quais extras vão turbinar seu projeto? (opcional) ⚡',
|
|
192
|
+
options: extraOptions,
|
|
193
|
+
required: false,
|
|
194
|
+
}),
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
// O resumo do clack usa os labels alinhados ("Axios , Toast-Hot");
|
|
198
|
+
// reescreve a linha com os labels sem os espaços, na mesma ordem.
|
|
199
|
+
if (chosenOptions.length === 0) {
|
|
200
|
+
replaceAnswerLine('Nenhum extra selecionado', 'none');
|
|
201
|
+
} else {
|
|
202
|
+
const chosenLabels = extraOptions
|
|
203
|
+
.filter(({ value }) => chosenOptions.includes(value))
|
|
204
|
+
.map(({ label }) => label);
|
|
205
|
+
replaceAnswerLine(
|
|
206
|
+
chosenLabels.map((label) => label.trimEnd()).join(', '),
|
|
207
|
+
chosenLabels.join(', '),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const progress = spinner();
|
|
213
|
+
progress.start('Criando o seu projeto...');
|
|
214
|
+
|
|
215
|
+
let commands;
|
|
216
|
+
try {
|
|
217
|
+
// Template secreto: os arquivos vêm do .enc já aberto; as versões, como nos
|
|
218
|
+
// demais, vêm do versions.json (bloco "<id>.base").
|
|
219
|
+
if (secretFiles) await writeSecretTemplate(secretFiles, targetDir);
|
|
220
|
+
else await copyTemplate(dir, targetDir);
|
|
221
|
+
|
|
222
|
+
// Templates com `choice` já trazem a lista de blocos; os demais somam o base
|
|
223
|
+
// do template com os extras marcados (ex.: "front.base", "front.antd").
|
|
224
|
+
const blockPaths = versionPaths ?? [
|
|
225
|
+
`${template.id}.base`,
|
|
226
|
+
...chosenOptions.map((id) => `${template.id}.${id}`),
|
|
227
|
+
];
|
|
228
|
+
const packages = await resolvePackages(blockPaths);
|
|
229
|
+
commands = buildInstallCommands(packages);
|
|
230
|
+
await writePackageJson(targetDir, { projectName, devName }, packages.pinned);
|
|
231
|
+
await apply?.(targetDir, chosenOptions);
|
|
232
|
+
progress.stop('Projeto criado! 👍');
|
|
233
|
+
} catch (err) {
|
|
234
|
+
progress.error(err.message);
|
|
235
|
+
process.exitCode = 1;
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Se a instalação falhar, a pasta é mantida e `pending` guarda o que faltou.
|
|
240
|
+
// O cypress baixa o próprio programa (~200 MB) ao ser instalado, então avisa o aluno.
|
|
241
|
+
let pending = [];
|
|
242
|
+
const hasCypress = commands.some((args) => args.some((arg) => arg.startsWith('cypress@')));
|
|
243
|
+
progress.start(
|
|
244
|
+
hasCypress
|
|
245
|
+
? 'Baixando o Cypress, pode demorar alguns minutos ⏳ '
|
|
246
|
+
: 'Instalando dependências ⏳ ',
|
|
247
|
+
);
|
|
248
|
+
try {
|
|
249
|
+
await installDependencies(targetDir, commands);
|
|
250
|
+
progress.stop('Dependências instaladas!');
|
|
251
|
+
} catch (err) {
|
|
252
|
+
pending = err.pending ?? commands;
|
|
253
|
+
progress.error('Falha ao instalar as dependências.');
|
|
254
|
+
log.error(err.message);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (pending.length > 0) {
|
|
258
|
+
const manualSteps = [`cd "${targetDir}"`, ...pending.map(formatCommand)].join('\n');
|
|
259
|
+
note(manualSteps, 'Falta instalar as dependências. Rode no terminal:');
|
|
260
|
+
process.exitCode = 1;
|
|
261
|
+
} else {
|
|
262
|
+
note('npm run dev', 'Para rodar, abra o terminal do VS Code (Ctrl + `) e execute:');
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// A abertura do VS Code é o último passo, depois de uma contagem que dá tempo
|
|
266
|
+
// de ler as mensagens acima. Dentro do terminal do VS Code, o projeto novo troca
|
|
267
|
+
// a janela atual (`code -r`), o que encerra este terminal.
|
|
268
|
+
await countdown('Abrindo o VS Code', OPEN_DELAY_SECONDS);
|
|
269
|
+
outro(
|
|
270
|
+
pending.length > 0
|
|
271
|
+
? 'Projeto criado com pendências.'
|
|
272
|
+
: 'Parabéns e bom desenvolvimento! 🚀',
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
const opened = await openInEditor(targetDir, { reuseWindow: isInsideVsCode() });
|
|
276
|
+
if (!opened)
|
|
277
|
+
log.warn(`VS Code não encontrado. Abra manualmente a pasta do projeto: ${targetDir}`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
main();
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const POSTCSS_CONFIG = `const config = {
|
|
5
|
+
plugins: {
|
|
6
|
+
'@tailwindcss/postcss': {},
|
|
7
|
+
},
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export default config;
|
|
11
|
+
`;
|
|
12
|
+
|
|
13
|
+
// Com Tailwind, o globals.css fica só com o import (o preflight do Tailwind
|
|
14
|
+
// substitui o reset que existia antes).
|
|
15
|
+
const TAILWIND_GLOBALS = '@import "tailwindcss";\n';
|
|
16
|
+
|
|
17
|
+
// Mesma tela do page.jsx original, com classes do Tailwind no lugar do
|
|
18
|
+
// page.module.css (que é removido nesse caso).
|
|
19
|
+
const TAILWIND_PAGE = `export default function Home() {
|
|
20
|
+
return (
|
|
21
|
+
<main className="flex min-h-screen w-full flex-col items-center justify-start bg-[image:linear-gradient(to_bottom,rgba(10,15,30,0.35),rgba(10,15,30,0.5)),url('https://minio.codeverse.dev.br/mural/1785759396834-148tgv.jpeg')] bg-cover bg-center bg-no-repeat px-6 py-8 text-center font-sans">
|
|
22
|
+
<div className="mt-60 flex flex-col items-center">
|
|
23
|
+
<h1 className="m-0 bg-[linear-gradient(135deg,#a5b4fc_0%,#38bdf8_100%)] bg-clip-text text-[clamp(2.5rem,6vw,4.5rem)] font-extrabold tracking-[-0.02em] text-transparent">
|
|
24
|
+
Codeverse
|
|
25
|
+
</h1>
|
|
26
|
+
<p className="mt-1 text-[clamp(1rem,2.5vw,1.4rem)] font-normal tracking-[0.15em] text-slate-300 uppercase">
|
|
27
|
+
Explore. Aprenda. Colabore.
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
<a
|
|
31
|
+
href="https://codeverse.dev.br"
|
|
32
|
+
target="_blank"
|
|
33
|
+
rel="noopener noreferrer"
|
|
34
|
+
className="mt-4 inline-flex items-center gap-[0.6rem] rounded-full bg-[linear-gradient(135deg,#a5b4fc_0%,#38bdf8_100%)] px-9 py-[0.85rem] font-bold text-[#0a0f1e] no-underline transition-[transform,box-shadow] duration-200 ease-in-out hover:-translate-y-0.5 hover:shadow-[0_10px_30px_rgba(56,189,248,0.35)]">
|
|
35
|
+
<svg
|
|
36
|
+
className="h-[25px] w-[25px] animate-[spin_6s_linear_infinite]"
|
|
37
|
+
viewBox="-11.5 -10.23174 23 20.46348"
|
|
38
|
+
width="25"
|
|
39
|
+
height="25"
|
|
40
|
+
aria-hidden="true">
|
|
41
|
+
<circle r="2.05" fill="currentColor" />
|
|
42
|
+
<g stroke="currentColor" strokeWidth="1" fill="none">
|
|
43
|
+
<ellipse rx="11" ry="4.2" />
|
|
44
|
+
<ellipse rx="11" ry="4.2" transform="rotate(60)" />
|
|
45
|
+
<ellipse rx="11" ry="4.2" transform="rotate(120)" />
|
|
46
|
+
</g>
|
|
47
|
+
</svg>
|
|
48
|
+
Ver material tutorial
|
|
49
|
+
</a>
|
|
50
|
+
|
|
51
|
+
<p className="mt-4 text-[0.85rem] tracking-[0.1em] text-slate-400 uppercase">
|
|
52
|
+
Scaffolding oficial - Codeverse
|
|
53
|
+
</p>
|
|
54
|
+
</div>
|
|
55
|
+
|
|
56
|
+
<footer className="text-[0.85rem] text-slate-400/60">
|
|
57
|
+
<p>Pouco pra quem vê..., muito pra quem aprende.</p>
|
|
58
|
+
</footer>
|
|
59
|
+
</main>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
`;
|
|
63
|
+
|
|
64
|
+
const GLOBALS_IMPORT_RE = /import '\.\/globals\.css';\r?\n/;
|
|
65
|
+
const BODY_MARKER = '<body>{children}</body>';
|
|
66
|
+
|
|
67
|
+
// CSS modules que o Tailwind substitui. Só são removidos com Tailwind; sem ele,
|
|
68
|
+
// ficam todos no projeto.
|
|
69
|
+
const MODULE_CSS_TO_REMOVE = [
|
|
70
|
+
['src', 'app', 'page.module.css'],
|
|
71
|
+
['src', 'app', 'nome-da-rota', 'nome-da-rota.module.css'],
|
|
72
|
+
['src', 'components', 'Nome-do-componente.module.css'],
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
async function applyTailwind(projectDir) {
|
|
76
|
+
await writeFile(join(projectDir, 'postcss.config.mjs'), POSTCSS_CONFIG, 'utf8');
|
|
77
|
+
|
|
78
|
+
await writeFile(join(projectDir, 'src', 'app', 'globals.css'), TAILWIND_GLOBALS, 'utf8');
|
|
79
|
+
await writeFile(join(projectDir, 'src', 'app', 'page.jsx'), TAILWIND_PAGE, 'utf8');
|
|
80
|
+
|
|
81
|
+
for (const parts of MODULE_CSS_TO_REMOVE) {
|
|
82
|
+
await rm(join(projectDir, ...parts), { force: true });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function applyLayoutIntegrations(projectDir, { antd, toast, tailwind }) {
|
|
87
|
+
if (!antd && !toast && !tailwind) return;
|
|
88
|
+
|
|
89
|
+
const layoutPath = join(projectDir, 'src', 'app', 'layout.js');
|
|
90
|
+
let content = await readFile(layoutPath, 'utf8');
|
|
91
|
+
|
|
92
|
+
const imports = [];
|
|
93
|
+
if (antd) imports.push("import { AntdRegistry } from '@ant-design/nextjs-registry';");
|
|
94
|
+
if (toast) imports.push("import { Toaster } from 'react-hot-toast';");
|
|
95
|
+
if (imports.length > 0) {
|
|
96
|
+
content = content.replace(GLOBALS_IMPORT_RE, (match) => {
|
|
97
|
+
const eol = match.endsWith('\r\n') ? '\r\n' : '\n';
|
|
98
|
+
return `${match}${imports.join(eol)}${eol}`;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const children = antd ? '<AntdRegistry>{children}</AntdRegistry>' : '{children}';
|
|
103
|
+
const toaster = toast ? '\n <Toaster />' : '';
|
|
104
|
+
const body = `\n ${children}${toaster}\n `;
|
|
105
|
+
|
|
106
|
+
const bodyOpenTag = tailwind ? '<body className="min-h-screen antialiased">' : '<body>';
|
|
107
|
+
content = content.replace(BODY_MARKER, `${bodyOpenTag}${body}</body>`);
|
|
108
|
+
|
|
109
|
+
await writeFile(layoutPath, content, 'utf8');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Alterações no código do template FrontEnd conforme os extras marcados.
|
|
113
|
+
export async function applyFront(projectDir, optionIds) {
|
|
114
|
+
const selected = {
|
|
115
|
+
antd: optionIds.includes('antd'),
|
|
116
|
+
toast: optionIds.includes('toast'),
|
|
117
|
+
tailwind: optionIds.includes('tailwind'),
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
if (selected.tailwind) await applyTailwind(projectDir);
|
|
121
|
+
await applyLayoutIntegrations(projectDir, selected);
|
|
122
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { appendFile, cp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { TEMPLATES_DIR } from '../paths.js';
|
|
5
|
+
|
|
6
|
+
const EXTRA_DIR = join(TEMPLATES_DIR, 'extras', 'test-dependencias');
|
|
7
|
+
const COMPONENTES_DIR = join(TEMPLATES_DIR, 'extras', 'test-componentes');
|
|
8
|
+
|
|
9
|
+
const COMPONENTES_DESCRIPTION =
|
|
10
|
+
'Projeto template didático de testes de componentes com Next.js (App Router) e Cypress.';
|
|
11
|
+
|
|
12
|
+
const COMPONENTES_KEYWORDS = [
|
|
13
|
+
'javascript',
|
|
14
|
+
'nextjs',
|
|
15
|
+
'app-router',
|
|
16
|
+
'cypress',
|
|
17
|
+
'testes',
|
|
18
|
+
'testes-de-componentes',
|
|
19
|
+
'component-testing',
|
|
20
|
+
'biome',
|
|
21
|
+
'codeverse',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const CYPRESS_GITIGNORE = `
|
|
25
|
+
# Gerados pelo Cypress ao rodar os testes
|
|
26
|
+
cypress/screenshots/
|
|
27
|
+
cypress/videos/
|
|
28
|
+
cypress/downloads/
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
// Opção "Dependências": troca o arquivo de testes do projeto por exemplos de
|
|
32
|
+
// mock (jest.fn). Os arquivos com o mesmo nome são sobrescritos.
|
|
33
|
+
export async function applyTestDependencias(projectDir) {
|
|
34
|
+
await cp(EXTRA_DIR, projectDir, { recursive: true });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Arquivos e pastas do template FrontEnd que não fazem parte do Component Testing.
|
|
38
|
+
const COMPONENTES_TO_REMOVE = [
|
|
39
|
+
['.env.example'],
|
|
40
|
+
['src', 'app', 'page.module.css'],
|
|
41
|
+
['src', 'app', 'nome-da-rota'],
|
|
42
|
+
['src', 'components', 'Nome-do-componente.jsx'],
|
|
43
|
+
['src', 'components', 'Nome-do-componente.module.css'],
|
|
44
|
+
['public', 'fonts'],
|
|
45
|
+
['public', 'icons'],
|
|
46
|
+
['public', 'images'],
|
|
47
|
+
['public', 'media'],
|
|
48
|
+
['public', 'sounds'],
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
// Opção "Component Testing": parte do template FrontEnd e acrescenta o Cypress.
|
|
52
|
+
// O page.jsx passa a mostrar só o componente Login (teste em cypress/component/Login.cy.jsx).
|
|
53
|
+
// O package.json já gerado ganha o script de teste.
|
|
54
|
+
export async function applyTestComponentes(projectDir) {
|
|
55
|
+
await cp(COMPONENTES_DIR, projectDir, { recursive: true });
|
|
56
|
+
for (const parts of COMPONENTES_TO_REMOVE) {
|
|
57
|
+
await rm(join(projectDir, ...parts), { recursive: true, force: true });
|
|
58
|
+
}
|
|
59
|
+
await appendFile(join(projectDir, '.gitignore'), CYPRESS_GITIGNORE, 'utf8');
|
|
60
|
+
|
|
61
|
+
const pkgPath = join(projectDir, 'package.json');
|
|
62
|
+
const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
|
|
63
|
+
pkg.description = COMPONENTES_DESCRIPTION;
|
|
64
|
+
pkg.keywords = COMPONENTES_KEYWORDS;
|
|
65
|
+
pkg.scripts = { ...pkg.scripts, test: 'cls && cypress open' };
|
|
66
|
+
await writeFile(pkgPath, `${JSON.stringify(pkg, null, 4)}\n`, 'utf8');
|
|
67
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { cp, mkdir, rename, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { TEMPLATES_DIR } from './paths.js';
|
|
5
|
+
|
|
6
|
+
// Nunca copiados para o projeto do aluno.
|
|
7
|
+
const SKIP = new Set(['node_modules', '.next', 'package-lock.json']);
|
|
8
|
+
|
|
9
|
+
async function pathExists(target) {
|
|
10
|
+
try {
|
|
11
|
+
await stat(target);
|
|
12
|
+
return true;
|
|
13
|
+
} catch (err) {
|
|
14
|
+
if (err.code === 'ENOENT') return false;
|
|
15
|
+
throw err;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function assertNotExists(destDir) {
|
|
20
|
+
if (await pathExists(destDir)) {
|
|
21
|
+
throw new Error(`A pasta "${destDir}" já existe. Escolha outro nome de projeto ou remova a pasta existente.`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// "gitkeep" só existe para as pastas vazias sobreviverem ao publish do npm;
|
|
26
|
+
// a pasta é criada, mas sem o arquivo marcador dentro.
|
|
27
|
+
const isGitkeep = (path) => basename(path) === 'gitkeep';
|
|
28
|
+
|
|
29
|
+
// O npm remove arquivos chamados ".gitignore" no publish, então o template
|
|
30
|
+
// guarda "_gitignore" e ele volta ao nome certo aqui.
|
|
31
|
+
async function restoreGitignore(destDir) {
|
|
32
|
+
try {
|
|
33
|
+
await rename(join(destDir, '_gitignore'), join(destDir, '.gitignore'));
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (err.code !== 'ENOENT') throw err;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function copyTemplate(templateId, destDir) {
|
|
40
|
+
await assertNotExists(destDir);
|
|
41
|
+
|
|
42
|
+
const sourceDir = join(TEMPLATES_DIR, templateId);
|
|
43
|
+
|
|
44
|
+
await cp(sourceDir, destDir, {
|
|
45
|
+
recursive: true,
|
|
46
|
+
filter(source) {
|
|
47
|
+
const rel = relative(sourceDir, source);
|
|
48
|
+
if (rel === '') return true;
|
|
49
|
+
if (isGitkeep(source)) return false;
|
|
50
|
+
return !SKIP.has(rel.split(sep)[0]);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await restoreGitignore(destDir);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Grava os arquivos do template secreto (já abertos com o código certo).
|
|
58
|
+
// files: [{ path: 'src/index.js', data: Buffer }]
|
|
59
|
+
export async function writeSecretTemplate(files, destDir) {
|
|
60
|
+
await assertNotExists(destDir);
|
|
61
|
+
const root = resolve(destDir);
|
|
62
|
+
|
|
63
|
+
for (const { path, data } of files) {
|
|
64
|
+
const target = resolve(root, path);
|
|
65
|
+
if (target !== root && !target.startsWith(root + sep)) {
|
|
66
|
+
throw new Error(`Caminho inválido no template secreto: ${path}`);
|
|
67
|
+
}
|
|
68
|
+
await mkdir(dirname(target), { recursive: true });
|
|
69
|
+
if (!isGitkeep(target)) await writeFile(target, data);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
await restoreGitignore(destDir);
|
|
73
|
+
}
|
package/lib/desktop.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Pasta onde os projetos são criados, independente de onde o comando rodou:
|
|
6
|
+
// %USERPROFILE%\Desktop (no Windows, homedir() é o %USERPROFILE%). Se essa pasta
|
|
7
|
+
// não existir (ex.: Desktop movido para o OneDrive), usa a pasta onde o comando
|
|
8
|
+
// foi rodado e devolve `isDesktop: false` para o CLI pedir confirmação.
|
|
9
|
+
export function getDesktopDir() {
|
|
10
|
+
const desktop = join(homedir(), 'Desktop');
|
|
11
|
+
if (existsSync(desktop)) return { dir: desktop, isDesktop: true };
|
|
12
|
+
return { dir: process.cwd(), isDesktop: false };
|
|
13
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { runCommand } from './runCommand.js';
|
|
2
|
+
|
|
3
|
+
// Comandos npm que deixam o projeto completo, na ordem em que rodam:
|
|
4
|
+
// 1. `npm install` se há pacotes com versão fixada no package.json
|
|
5
|
+
// 2. `npm install a@latest` pacotes com "latest" (o npm grava ^X.Y.Z sozinho)
|
|
6
|
+
// 3. `npm install -D b@latest` idem, para devDependencies
|
|
7
|
+
export function buildInstallCommands({ pinned, latest }) {
|
|
8
|
+
const commands = [];
|
|
9
|
+
|
|
10
|
+
const hasPinned = Object.keys(pinned.dependencies).length + Object.keys(pinned.devDependencies).length > 0;
|
|
11
|
+
if (hasPinned) commands.push(['install']);
|
|
12
|
+
|
|
13
|
+
if (latest.dependencies.length > 0) {
|
|
14
|
+
commands.push(['install', ...latest.dependencies.map((name) => `${name}@latest`)]);
|
|
15
|
+
}
|
|
16
|
+
if (latest.devDependencies.length > 0) {
|
|
17
|
+
commands.push(['install', '-D', ...latest.devDependencies.map((name) => `${name}@latest`)]);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return commands;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const formatCommand = (args) => `npm ${args.join(' ')}`;
|
|
24
|
+
|
|
25
|
+
// Roda os comandos em sequência. Se um falhar, o erro carrega em `pending` os
|
|
26
|
+
// comandos que ainda faltavam (o que falhou e os seguintes), para o aluno
|
|
27
|
+
// poder terminar a instalação manualmente.
|
|
28
|
+
export async function installDependencies(projectDir, commands) {
|
|
29
|
+
for (const [index, args] of commands.entries()) {
|
|
30
|
+
try {
|
|
31
|
+
await runCommand('npm', args, { cwd: projectDir });
|
|
32
|
+
} catch (err) {
|
|
33
|
+
err.pending = commands.slice(index);
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { runCommand } from './runCommand.js';
|
|
2
|
+
|
|
3
|
+
// O VS Code define TERM_PROGRAM=vscode nos seus terminais integrados.
|
|
4
|
+
export const isInsideVsCode = () => process.env.TERM_PROGRAM === 'vscode';
|
|
5
|
+
|
|
6
|
+
// Abre a pasta no VS Code. Devolve false se o comando `code` não existir.
|
|
7
|
+
// `reuseWindow` (`code -r`) troca a pasta da janela atual em vez de abrir outra;
|
|
8
|
+
// o terminal integrado dessa janela é encerrado na troca.
|
|
9
|
+
export function openInEditor(projectDir, { reuseWindow = false } = {}) {
|
|
10
|
+
const args = reuseWindow ? ['-r', '.'] : ['.'];
|
|
11
|
+
return runCommand('code', args, { cwd: projectDir, capture: false })
|
|
12
|
+
.then(() => true)
|
|
13
|
+
.catch(() => false);
|
|
14
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
// Transforma o package.template.json do projeto copiado em package.json:
|
|
5
|
+
// aplica o nome do projeto, o autor (nome do DEV) e as dependências com versão
|
|
6
|
+
// fixada. Só mexe no package.json do projeto do aluno, nunca no do CLI.
|
|
7
|
+
export async function writePackageJson(projectDir, { projectName, devName }, pinned) {
|
|
8
|
+
const templateFile = join(projectDir, 'package.template.json');
|
|
9
|
+
const pkg = JSON.parse(await readFile(templateFile, 'utf8'));
|
|
10
|
+
|
|
11
|
+
pkg.name = projectName;
|
|
12
|
+
pkg.author = { name: devName };
|
|
13
|
+
for (const group of ['dependencies', 'devDependencies']) {
|
|
14
|
+
if (Object.keys(pinned[group]).length > 0) pkg[group] = pinned[group];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
await writeFile(join(projectDir, 'package.json'), `${JSON.stringify(pkg, null, 4)}\n`, 'utf8');
|
|
18
|
+
await rm(templateFile);
|
|
19
|
+
}
|
package/lib/paths.js
ADDED