@aliens-syndicate/cli 0.1.3 → 0.1.5

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/tools/create.mjs CHANGED
@@ -1,64 +1,78 @@
1
+ // aliens new (n) <name>: asks which extensions to use, creates the project and installs its packages.
1
2
  import { copyFile, cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
2
- import { basename, join, resolve } from 'node:path';
3
+ import { basename, join, relative, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
3
5
  import { createProjectDirectories, styleLayers } from './project-layout.mjs';
4
-
5
- // Messages follow the system language (ALIENS_LANG overrides it): English, Portuguese, Spanish or Chinese.
6
- const language = (() => {
7
- const tag = (process.env.ALIENS_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG ||
8
- Intl.DateTimeFormat().resolvedOptions().locale || 'en').toLowerCase();
9
- return ['pt', 'es', 'zh'].find(code => tag.startsWith(code)) ?? 'en';
10
- })();
11
- const messages = {
12
- en: { usage: 'Usage: node tools/create.mjs <new-project-folder>', name: 'Use a single-line folder name without leading or trailing spaces.',
13
- created: 'Aliens project created in', exists: 'The destination folder already exists.' },
14
- pt: { usage: 'Uso: node tools/create.mjs <pasta-do-novo-projeto>', name: 'Use um nome de pasta em uma única linha, sem espaços nas pontas.',
15
- created: 'Projeto Aliens criado em', exists: 'A pasta de destino já existe.' },
16
- es: { usage: 'Uso: node tools/create.mjs <carpeta-del-nuevo-proyecto>', name: 'Usa un nombre de carpeta en una sola línea, sin espacios en los extremos.',
17
- created: 'Proyecto Aliens creado en', exists: 'La carpeta de destino ya existe.' },
18
- zh: { usage: '用法:node tools/create.mjs <新项目文件夹>', name: '请使用单行文件夹名称,首尾不要有空格。',
19
- created: 'Aliens 项目已创建于', exists: '目标文件夹已存在。' }
20
- }[language];
6
+ import {
7
+ CliError, ask, bold, cliPackage, cliVersion, confirm, cyan, defaultPort, dim, extensions, green, interactive, kebab,
8
+ latestVersion, ok, parseFlags, pick, projectToolFiles, runCommand, validName, warn
9
+ } from './cli-shared.mjs';
10
+
11
+ const text = {
12
+ en: { usage: 'Usage: aliens new <project-name>', name: 'What is your project named?', fallbackName: 'my-aliens-app',
13
+ badName: 'Use lowercase words separated by hyphens for the project name, like my-app.', exists: 'The folder {path} already exists.',
14
+ style: 'Use utility classes in .style ({package})?', icons: 'Use the icon library ({package})?', elements: 'Use ready-made Elements ({package})?',
15
+ creating: 'Creating the Aliens project in {path}', created: 'Aliens project created in {path}', installing: 'Installing the packages with npm…',
16
+ unpublished: '{package} is not on npm yet, so the project starts without it.', installFailed: 'npm install failed. Enter the folder and run npm install.',
17
+ skipped: 'Packages not installed (--skip-install). Enter the folder and run npm install.', next: 'Next steps:' },
18
+ pt: { usage: 'Uso: aliens new <nome-do-projeto>', name: 'Qual é o nome do projeto?', fallbackName: 'meu-app-aliens',
19
+ badName: 'Use palavras minúsculas separadas por hífen no nome do projeto, como meu-app.', exists: 'A pasta {path} já existe.',
20
+ style: 'Usar classes utilitárias no .style ({package})?', icons: 'Usar a biblioteca de ícones ({package})?', elements: 'Usar Elements prontos ({package})?',
21
+ creating: 'Criando o projeto Aliens em {path}', created: 'Projeto Aliens criado em {path}', installing: 'Instalando os pacotes com o npm…',
22
+ unpublished: '{package} ainda não está no npm, então o projeto começa sem ele.', installFailed: 'O npm install falhou. Entre na pasta e rode npm install.',
23
+ skipped: 'Pacotes não instalados (--skip-install). Entre na pasta e rode npm install.', next: 'Próximos passos:' },
24
+ es: { usage: 'Uso: aliens new <nombre-del-proyecto>', name: '¿Cómo se llama tu proyecto?', fallbackName: 'mi-app-aliens',
25
+ badName: 'Usa palabras en minúsculas separadas por guiones en el nombre del proyecto, como mi-app.', exists: 'La carpeta {path} ya existe.',
26
+ style: '¿Usar clases utilitarias en .style ({package})?', icons: '¿Usar la biblioteca de íconos ({package})?', elements: '¿Usar Elements listos ({package})?',
27
+ creating: 'Creando el proyecto Aliens en {path}', created: 'Proyecto Aliens creado en {path}', installing: 'Instalando los paquetes con npm…',
28
+ unpublished: '{package} todavía no está en npm, así que el proyecto empieza sin él.', installFailed: 'npm install falló. Entra en la carpeta y ejecuta npm install.',
29
+ skipped: 'Paquetes no instalados (--skip-install). Entra en la carpeta y ejecuta npm install.', next: 'Próximos pasos:' },
30
+ zh: { usage: '用法:aliens new <项目名称>', name: '项目叫什么名字?', fallbackName: 'my-aliens-app',
31
+ badName: '项目名称请使用以连字符分隔的小写单词,例如 my-app。', exists: '文件夹 {path} 已存在。',
32
+ style: '在 .style 中使用工具类({package})?', icons: '使用图标库({package})?', elements: '使用现成的 Elements({package})?',
33
+ creating: '正在 {path} 中创建 Aliens 项目', created: 'Aliens 项目已创建于 {path}', installing: '正在用 npm 安装依赖包…',
34
+ unpublished: '{package} 尚未发布到 npm,项目将先不包含它。', installFailed: 'npm install 失败。请进入文件夹运行 npm install。',
35
+ skipped: '未安装依赖包(--skip-install)。请进入文件夹运行 npm install。', next: '下一步:' }
36
+ };
37
+ const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
21
38
 
22
39
  const starter = join(import.meta.dirname, 'starter');
23
40
  const editorExtension = join(import.meta.dirname, 'vscode-space');
24
41
 
25
- async function create([path, ...extra]) {
26
- if (!path || extra.length) throw new Error(messages.usage);
27
- const destination = resolve(path);
28
- const name = basename(destination);
29
- if (!name || /[\r\n\u2028\u2029]/u.test(name) || name !== name.trim()) {
30
- throw new Error(messages.name);
31
- }
32
-
33
- await mkdir(destination);
34
- try {
35
- const project = join(destination, 'project');
36
- const tools = join(destination, 'tools');
37
- await mkdir(project);
38
- await cp(join(starter, 'app'), join(project, 'app'), { recursive: true });
39
- await cp(join(starter, 'styles'), join(project, 'styles'), { recursive: true });
40
- await createProjectDirectories(destination);
41
- // The agent, rule, and skill an AI needs to start working come ready in ai/.
42
- await cp(join(starter, 'ai'), join(destination, 'ai'), { recursive: true });
43
- await mkdir(join(project, 'app', 'pages', 'home'));
44
- await mkdir(tools);
45
- await mkdir(join(destination, '.vscode'));
46
- const manifest = JSON.parse(await readFile(join(editorExtension, 'package.json'), 'utf8'));
47
- const paletteSetting = 'editor.semanticTokenColorCustomizations';
48
- const editorDefaults = manifest.contributes.configurationDefaults;
49
- const editorSettings = { '[space]': editorDefaults['[space]'], [paletteSetting]: editorDefaults[paletteSetting] };
50
-
51
- const translations = Object.fromEntries(await Promise.all(
52
- (await readdir(join(starter, 'language'))).filter(file => /^\.[a-z]{2}-[A-Z]{2}$/.test(file)).map(async file => [
53
- 'project/language/' + file,
54
- `site:\n title: ${name}\n\nhome:\n description: ${name}\n\n` + await readFile(join(starter, 'language', file), 'utf8')
55
- ])
56
- ));
57
- const template = {
58
- ...translations,
59
- 'README.md': `# ${name}
60
-
61
- Run \`node tools/build.mjs\` to generate the preview in \`dist/\`.
42
+ // The comment block at the top of every .config: the commands of the CLI, so the project explains how to run itself.
43
+ export const configGuide = `# Aliens CLI · aliens help lists every command and option.
44
+ # aliens run Builds, serves on http://localhost:${defaultPort} and reloads on every save. --port <number> changes the port.
45
+ # aliens build Generates the preview in dist/ and the ai/.map index.
46
+ # aliens generate <kind> <name> Creates Space files (alias g): element (e), page (p), service (s), pipe, guard and the other kinds.
47
+ # aliens new <name> Creates a new Aliens project (alias n).
48
+ # aliens doctor Checks Node.js, the CLI, .config, the packages, the port and the build.
49
+ # aliens update Updates the @aliens-syndicate packages and tools/ to the installed CLI.
50
+ # aliens cache Deletes dist/ and the caches the tools keep.
51
+ # aliens version Shows the CLI, Node.js and package versions.
52
+ `;
53
+
54
+ function readme(name) {
55
+ return `# ${name}
56
+
57
+ An [Aliens](https://github.com/AliensSyndicate/aliens-syndicate-framework) project written in Space.
58
+
59
+ ## Commands
60
+
61
+ | Command | What it does |
62
+ | --- | --- |
63
+ | \`aliens run\` | Builds, serves on http://localhost:${defaultPort} and reloads on every save. \`--port <number>\` changes the port. |
64
+ | \`aliens build\` | Generates the preview in \`dist/\` and the \`ai/.map\` index. |
65
+ | \`aliens g element molecules/card\` | Creates \`card.markup\`, \`card.logic\`, \`card.style\` and \`card.test\`. |
66
+ | \`aliens g page about\` | Creates a page in \`project/app/pages/about/\`. |
67
+ | \`aliens g s cart\` | Creates \`project/app/services/cart.service\`. |
68
+ | \`aliens doctor\` | Checks Node.js, the CLI, \`.config\`, the packages, the port and the build. |
69
+ | \`aliens update\` | Updates the @aliens-syndicate packages and \`tools/\`. |
70
+ | \`aliens cache\` | Deletes \`dist/\` and the caches. |
71
+ | \`aliens version\` | Shows the versions in use. |
72
+
73
+ \`npm run dev\` and \`npm run build\` run the same commands.
74
+
75
+ ## Project
62
76
 
63
77
  The configuration lives in \`.config\` and the build generates the \`ai/.map\` index.
64
78
  The Home includes the style library, with tokens in \`project/styles/settings/\`, components in \`project/styles/components/\` and themes in \`project/styles/settings/theme.style\`.
@@ -71,9 +85,20 @@ style:
71
85
  from: @aliens-syndicate/style
72
86
  \`\`\`
73
87
 
88
+ To use buttons, badges, alerts, cards and fields written in Space, run \`npm install @aliens-syndicate/elements\` and add to \`.config\`:
89
+
90
+ \`\`\`
91
+ elements:
92
+ from: @aliens-syndicate/elements
93
+ \`\`\`
94
+
74
95
  Pages and Elements live in \`project/app/pages/\` and \`project/app/elements/\`.
75
- `,
76
- '.config': `project:
96
+ `;
97
+ }
98
+
99
+ function config(name, chosen) {
100
+ return `${configGuide}
101
+ project:
77
102
  name: ${name}
78
103
  version: 0.1.0
79
104
 
@@ -88,41 +113,136 @@ build:
88
113
  target: web
89
114
  environment: local
90
115
 
116
+ serve:
117
+ port: ${defaultPort}
118
+ ${chosen.map(extension => `\n${extension.section}:\n from: ${extension.name}\n${extension.extra ?? ''}`).join('')}
91
119
  language:
92
120
  directory: project/language
93
121
  default: en-US
94
122
  detection: browser
95
- `,
96
- 'project/.env': '# Configure project environment values here.\n',
97
- 'project/app/app.logic': 'Logic App\n',
98
- 'project/app/app.markup': 'Markup App\n home\n',
99
- 'project/app/app.route': 'Route App\n routes:\n home:\n path: /\n element: home\n',
100
- 'project/app/pages/home/home.markup': 'Markup Home\n style-guide\n',
101
- 'project/styles/main.style': 'Style Main\n default:\n' + styleLayers.map(layer => ' ' + layer + '\n').join('')
102
- };
123
+ `;
124
+ }
125
+
126
+ async function copyStarter(destination, name) {
127
+ const project = join(destination, 'project');
128
+ const tools = join(destination, 'tools');
129
+ await mkdir(project);
130
+ await cp(join(starter, 'app'), join(project, 'app'), { recursive: true });
131
+ await cp(join(starter, 'styles'), join(project, 'styles'), { recursive: true });
132
+ await createProjectDirectories(destination);
133
+ // The agent, rule, and skill an AI needs to start working come ready in ai/.
134
+ await cp(join(starter, 'ai'), join(destination, 'ai'), { recursive: true });
135
+ await mkdir(join(project, 'app', 'pages', 'home'));
136
+ await mkdir(tools);
137
+ await mkdir(join(destination, '.vscode'));
138
+ const manifest = JSON.parse(await readFile(join(editorExtension, 'package.json'), 'utf8'));
139
+ const paletteSetting = 'editor.semanticTokenColorCustomizations';
140
+ const editorDefaults = manifest.contributes.configurationDefaults;
141
+ const editorSettings = { '[space]': editorDefaults['[space]'], [paletteSetting]: editorDefaults[paletteSetting] };
142
+
143
+ const translations = Object.fromEntries(await Promise.all(
144
+ (await readdir(join(starter, 'language'))).filter(file => /^\.[a-z]{2}-[A-Z]{2}$/.test(file)).map(async file => [
145
+ 'project/language/' + file,
146
+ `site:\n title: ${name}\n\nhome:\n description: ${name}\n\n` + await readFile(join(starter, 'language', file), 'utf8')
147
+ ])
148
+ ));
149
+ const template = {
150
+ ...translations,
151
+ 'README.md': readme(name),
152
+ 'project/.env': '# Configure project environment values here.\n',
153
+ 'project/app/app.logic': 'Logic App\n',
154
+ 'project/app/app.markup': 'Markup App\n home\n',
155
+ 'project/app/app.route': 'Route App\n routes:\n home:\n path: /\n element: home\n',
156
+ 'project/app/pages/home/home.markup': 'Markup Home\n style-guide\n',
157
+ 'project/styles/main.style': 'Style Main\n default:\n' + styleLayers.map(layer => ' ' + layer + '\n').join('')
158
+ };
159
+ const results = await Promise.allSettled([
160
+ ...Object.entries(template).map(([file, content]) => writeFile(join(destination, file), content, { flag: 'wx' })),
161
+ ...projectToolFiles.map(file => copyFile(join(import.meta.dirname, file), join(tools, file))),
162
+ cp(editorExtension, join(tools, 'vscode-space'), { recursive: true }),
163
+ writeFile(join(destination, '.vscode', 'settings.json'), JSON.stringify(editorSettings, null, 3) + '\n'),
164
+ writeFile(join(destination, '.gitignore'), 'dist/\nnode_modules/\n.aliens/\n.DS_Store\nproject/.env\n')
165
+ ]);
166
+ const failure = results.find(result => result.status === 'rejected');
167
+ if (failure) throw failure.reason;
168
+ }
103
169
 
104
- const results = await Promise.allSettled([
105
- ...Object.entries(template).map(([file, content]) => writeFile(join(destination, file), content, { flag: 'wx' })),
106
- ...['build.mjs', 'watch.mjs', 'runtime.mjs', 'project-layout.mjs'].map(file =>
107
- copyFile(join(import.meta.dirname, file), join(tools, file))
108
- ),
109
- cp(editorExtension, join(tools, 'vscode-space'), { recursive: true }),
110
- writeFile(join(destination, '.vscode', 'settings.json'), JSON.stringify(editorSettings, null, 3) + '\n'),
111
- writeFile(join(destination, '.gitignore'), 'dist/\n.DS_Store\nproject/.env\n')
112
- ]);
113
- const failure = results.find(result => result.status === 'rejected');
114
- if (failure) throw failure.reason;
170
+ export async function create(args) {
171
+ const { flags, positionals } = parseFlags(args, {
172
+ booleans: ['yes', 'skip-install', ...extensions.map(extension => extension.section)], aliases: { y: 'yes' }
173
+ });
174
+ if (positionals.length > 1) throw new CliError(t('usage'));
175
+ const asking = interactive() && !flags.yes;
176
+ let path = positionals[0];
177
+ if (!path) {
178
+ if (!asking) throw new CliError(t('usage'));
179
+ path = await ask(t('name'), t('fallbackName'));
180
+ }
181
+ const destination = resolve(path);
182
+ const name = basename(destination);
183
+ if (!validName(name)) throw new CliError(`${t('badName')} (${kebab(name)}?)`);
184
+
185
+ // Each extension is on unless a flag turns it off; without flags, the prompt asks with "yes" as the default.
186
+ const chosen = [];
187
+ for (const extension of extensions) {
188
+ let use = flags[extension.section];
189
+ if (use === undefined) use = asking ? await confirm(t(extension.section, { package: extension.name })) : true;
190
+ if (use) chosen.push(extension);
191
+ }
192
+
193
+ console.log(`\n${t('creating', { path: bold(destination) })}\n`);
194
+ try {
195
+ await mkdir(destination);
196
+ } catch (error) {
197
+ throw error.code === 'EEXIST' ? new CliError(t('exists', { path: destination })) : error;
198
+ }
199
+
200
+ try {
201
+ await copyStarter(destination, name);
202
+ // Before installing, keep only the packages npm already publishes, so the build never asks for a missing one.
203
+ const packages = [{ name: cliPackage }, ...chosen];
204
+ const versions = new Map();
205
+ if (!flags['skip-install']) {
206
+ await Promise.all(packages.map(async entry => versions.set(entry.name, await latestVersion(entry.name))));
207
+ for (const extension of [...chosen]) {
208
+ if (versions.get(extension.name)) continue;
209
+ console.log(warn(t('unpublished', { package: extension.name })));
210
+ chosen.splice(chosen.indexOf(extension), 1);
211
+ }
212
+ }
213
+ const devDependencies = Object.fromEntries([{ name: cliPackage }, ...chosen]
214
+ .filter(entry => flags['skip-install'] || versions.get(entry.name))
215
+ .map(entry => [entry.name, entry.name === cliPackage && flags['skip-install'] ? `^${cliVersion}` : versions.get(entry.name) ? `^${versions.get(entry.name)}` : 'latest']));
216
+ const manifest = {
217
+ name, version: '0.1.0', private: true, type: 'module',
218
+ scripts: { dev: 'aliens run', build: 'aliens build', doctor: 'aliens doctor' }, devDependencies
219
+ };
220
+ await writeFile(join(destination, 'package.json'), JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx' });
221
+ await writeFile(join(destination, '.config'), config(name, chosen), { flag: 'wx' });
115
222
  } catch (error) {
116
223
  await rm(destination, { recursive: true, force: true });
117
224
  throw error;
118
225
  }
119
226
 
120
- console.log(`${messages.created} ${destination}`);
227
+ if (flags['skip-install']) console.log(warn(t('skipped')));
228
+ else {
229
+ console.log(dim(t('installing')));
230
+ const code = await runCommand('npm', ['install', '--no-fund', '--no-audit'], { cwd: destination });
231
+ if (code) console.log(warn(t('installFailed')));
232
+ }
233
+
234
+ const folder = relative(process.cwd(), destination) || '.';
235
+ console.log(`\n${ok(green(t('created', { path: destination })))}\n\n${t('next')}\n`);
236
+ if (folder !== '.') console.log(` ${cyan(`cd ${folder.includes(' ') ? JSON.stringify(folder) : folder}`)}`);
237
+ console.log(` ${cyan('aliens run')}\n`);
121
238
  }
122
239
 
123
- try {
124
- await create(process.argv.slice(2));
125
- } catch (error) {
126
- console.error(error.code === 'EEXIST' ? messages.exists : error.message);
127
- process.exitCode = 1;
240
+ // node tools/create.mjs <folder> keeps working for whoever runs the script without the CLI.
241
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
242
+ try {
243
+ await create(process.argv.slice(2));
244
+ } catch (error) {
245
+ console.error(error.message);
246
+ process.exitCode = 1;
247
+ }
128
248
  }
@@ -0,0 +1,139 @@
1
+ // aliens doctor: checks the machine and the project, like flutter doctor, and prints the fix for each problem.
2
+ import { existsSync } from 'node:fs';
3
+ import { createServer } from 'node:net';
4
+ import { join } from 'node:path';
5
+ import { toolsDifferences } from './update.mjs';
6
+ import {
7
+ bold, captureCommand, installedVersion, cliPackage, cliRoot, cliVersion, compareVersions, cyan, defaultPort, dim, findProject, green,
8
+ latestVersion, minimumNode, parseFlags, pick, readConfig, red, runBuild, yellow
9
+ } from './cli-shared.mjs';
10
+
11
+ const text = {
12
+ en: { title: 'Aliens doctor', checking: 'Checking the environment and the project…', node: 'Node.js {version}', nodeOld: 'Node.js {version} · Aliens needs {minimum} or newer',
13
+ nodeFix: 'Install the LTS version from https://nodejs.org', npm: 'npm {version}', npmMissing: 'npm was not found', npmFix: 'npm comes with Node.js: reinstall Node.js',
14
+ cli: 'Aliens CLI {version} (latest)', cliOld: 'Aliens CLI {version} · {latest} available', cliFix: 'npm install -g {package}@latest',
15
+ cliOffline: 'Aliens CLI {version} · could not reach npm to compare versions', noProject: 'No Aliens project in this folder',
16
+ noProjectFix: 'Create one with aliens new <name>, or open a project folder', project: 'Project {name} in {path}',
17
+ config: '.config is valid', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} does not exist', tools: 'tools/ matches the CLI {version}',
18
+ toolsOld: 'tools/ differs from the CLI {version} in {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ is the CLI itself (framework repository)',
19
+ extension: '{name} {version}', extensionMissing: '{name} is declared in .config ({section}:) but is not installed', extensionFix: 'npm install {name}',
20
+ port: 'Port {port} is free for aliens run', portUsed: 'Port {port} is in use', portDenied: 'Port {port} needs administrator rights on this system',
21
+ portFix: 'aliens run --port <number>, or set serve: port: in .config', build: 'aliens build passes', buildBad: 'aliens build fails: {error}',
22
+ buildFix: 'Fix the file and line in the message, then run aliens build', fine: 'No issues found.', issues: '{count} issue(s) found.', warnings: '{count} warning(s).' },
23
+ pt: { title: 'Aliens doctor', checking: 'Verificando o ambiente e o projeto…', node: 'Node.js {version}', nodeOld: 'Node.js {version} · o Aliens precisa da {minimum} ou mais nova',
24
+ nodeFix: 'Instale a versão LTS em https://nodejs.org', npm: 'npm {version}', npmMissing: 'npm não encontrado', npmFix: 'O npm vem com o Node.js: reinstale o Node.js',
25
+ cli: 'Aliens CLI {version} (mais recente)', cliOld: 'Aliens CLI {version} · {latest} disponível', cliFix: 'npm install -g {package}@latest',
26
+ cliOffline: 'Aliens CLI {version} · não foi possível consultar o npm para comparar versões', noProject: 'Nenhum projeto Aliens nesta pasta',
27
+ noProjectFix: 'Crie um com aliens new <nome> ou abra a pasta de um projeto', project: 'Projeto {name} em {path}',
28
+ config: '.config válido', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} não existe', tools: 'tools/ igual ao da CLI {version}',
29
+ toolsOld: 'tools/ diferente da CLI {version} em {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ é a própria CLI (repositório do framework)',
30
+ extension: '{name} {version}', extensionMissing: '{name} está declarado no .config ({section}:) mas não está instalado', extensionFix: 'npm install {name}',
31
+ port: 'Porta {port} livre para o aliens run', portUsed: 'A porta {port} está em uso', portDenied: 'A porta {port} exige permissão de administrador neste sistema',
32
+ portFix: 'aliens run --port <número> ou defina serve: port: no .config', build: 'aliens build passa', buildBad: 'aliens build falha: {error}',
33
+ buildFix: 'Corrija o arquivo e a linha da mensagem e rode aliens build', fine: 'Nenhum problema encontrado.', issues: '{count} problema(s) encontrado(s).', warnings: '{count} aviso(s).' },
34
+ es: { title: 'Aliens doctor', checking: 'Revisando el entorno y el proyecto…', node: 'Node.js {version}', nodeOld: 'Node.js {version} · Aliens necesita la {minimum} o más nueva',
35
+ nodeFix: 'Instala la versión LTS desde https://nodejs.org', npm: 'npm {version}', npmMissing: 'no se encontró npm', npmFix: 'npm viene con Node.js: reinstala Node.js',
36
+ cli: 'Aliens CLI {version} (la más reciente)', cliOld: 'Aliens CLI {version} · {latest} disponible', cliFix: 'npm install -g {package}@latest',
37
+ cliOffline: 'Aliens CLI {version} · no se pudo consultar npm para comparar versiones', noProject: 'No hay un proyecto Aliens en esta carpeta',
38
+ noProjectFix: 'Crea uno con aliens new <nombre> o abre la carpeta de un proyecto', project: 'Proyecto {name} en {path}',
39
+ config: '.config es válido', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} no existe', tools: 'tools/ coincide con la CLI {version}',
40
+ toolsOld: 'tools/ difiere de la CLI {version} en {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ es la propia CLI (repositorio del framework)',
41
+ extension: '{name} {version}', extensionMissing: '{name} está declarado en .config ({section}:) pero no está instalado', extensionFix: 'npm install {name}',
42
+ port: 'Puerto {port} libre para aliens run', portUsed: 'El puerto {port} está en uso', portDenied: 'El puerto {port} requiere permisos de administrador en este sistema',
43
+ portFix: 'aliens run --port <número> o define serve: port: en .config', build: 'aliens build pasa', buildBad: 'aliens build falla: {error}',
44
+ buildFix: 'Corrige el archivo y la línea del mensaje y ejecuta aliens build', fine: 'No se encontraron problemas.', issues: '{count} problema(s) encontrado(s).', warnings: '{count} aviso(s).' },
45
+ zh: { title: 'Aliens doctor', checking: '正在检查环境和项目…', node: 'Node.js {version}', nodeOld: 'Node.js {version} · Aliens 需要 {minimum} 或更高版本',
46
+ nodeFix: '从 https://nodejs.org 安装 LTS 版本', npm: 'npm {version}', npmMissing: '未找到 npm', npmFix: 'npm 随 Node.js 一起安装:请重新安装 Node.js',
47
+ cli: 'Aliens CLI {version}(最新)', cliOld: 'Aliens CLI {version} · 可升级到 {latest}', cliFix: 'npm install -g {package}@latest',
48
+ cliOffline: 'Aliens CLI {version} · 无法连接 npm 比较版本', noProject: '此文件夹中没有 Aliens 项目',
49
+ noProjectFix: '用 aliens new <名称> 创建一个,或打开项目文件夹', project: '项目 {name},位于 {path}',
50
+ config: '.config 有效', configBad: '.config:{problem}', entryMissing: 'files: entry: {file} 不存在', tools: 'tools/ 与 CLI {version} 一致',
51
+ toolsOld: 'tools/ 与 CLI {version} 不同:{files}', toolsFix: 'aliens update', toolsSelf: 'tools/ 就是 CLI 本身(框架仓库)',
52
+ extension: '{name} {version}', extensionMissing: '{name} 已在 .config({section}:)中声明,但尚未安装', extensionFix: 'npm install {name}',
53
+ port: '端口 {port} 可供 aliens run 使用', portUsed: '端口 {port} 已被占用', portDenied: '在此系统上,端口 {port} 需要管理员权限',
54
+ portFix: 'aliens run --port <端口>,或在 .config 中设置 serve: port:', build: 'aliens build 通过', buildBad: 'aliens build 失败:{error}',
55
+ buildFix: '按消息中的文件和行号修复后,运行 aliens build', fine: '未发现问题。', issues: '发现 {count} 个问题。', warnings: '{count} 个警告。' }
56
+ };
57
+ const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
58
+
59
+ const marks = { ok: green('[✓]'), warn: yellow('[!]'), fail: red('[✗]') };
60
+ const results = [];
61
+ function report(level, message, fix) {
62
+ results.push(level);
63
+ console.log(`${marks[level]} ${message}`);
64
+ if (fix) console.log(` ${dim('→')} ${cyan(fix)}`);
65
+ }
66
+
67
+ function portState(port) {
68
+ return new Promise(resolvePromise => {
69
+ const server = createServer();
70
+ server.once('error', error => resolvePromise(error.code));
71
+ server.listen(port, () => server.close(() => resolvePromise('free')));
72
+ });
73
+ }
74
+
75
+
76
+ export async function doctor(args) {
77
+ parseFlags(args);
78
+ console.log(`${bold(t('title'))}\n${dim(t('checking'))}\n`);
79
+ results.length = 0;
80
+
81
+ const node = process.versions.node;
82
+ if (compareVersions(node, minimumNode) >= 0) report('ok', t('node', { version: node }));
83
+ else report('fail', t('nodeOld', { version: node, minimum: minimumNode }), t('nodeFix'));
84
+
85
+ const npm = await captureCommand('npm', ['--version'], { stdio: ['ignore', 'pipe', 'ignore'] });
86
+ if (npm.code === 0) report('ok', t('npm', { version: npm.output }));
87
+ else report('fail', t('npmMissing'), t('npmFix'));
88
+
89
+ const latest = npm.code === 0 ? await latestVersion(cliPackage) : null;
90
+ if (!latest) report('warn', t('cliOffline', { version: cliVersion }));
91
+ else if (compareVersions(cliVersion, latest) >= 0) report('ok', t('cli', { version: cliVersion }));
92
+ else report('warn', t('cliOld', { version: cliVersion, latest }), t('cliFix', { package: cliPackage }));
93
+
94
+ const root = findProject();
95
+ if (!root) {
96
+ report('warn', t('noProject'), t('noProjectFix'));
97
+ } else {
98
+ let config;
99
+ try {
100
+ config = readConfig(root);
101
+ const entry = config.files?.entry;
102
+ if (!entry) throw new Error('files: entry: is missing');
103
+ if (!existsSync(join(root, entry))) throw new Error(t('entryMissing', { file: entry }));
104
+ report('ok', `${t('project', { name: bold(config.project?.name ?? '?'), path: dim(root) })}`);
105
+ report('ok', t('config'));
106
+ } catch (error) {
107
+ report('fail', t('configBad', { problem: error.message }));
108
+ }
109
+
110
+ if (root === cliRoot) report('ok', t('toolsSelf'));
111
+ else {
112
+ const changed = await toolsDifferences(root);
113
+ if (!changed.length) report('ok', t('tools', { version: cliVersion }));
114
+ else report('warn', t('toolsOld', { version: cliVersion, files: changed.slice(0, 3).join(', ') + (changed.length > 3 ? '…' : '') }), t('toolsFix'));
115
+ }
116
+
117
+ for (const [section, values] of Object.entries(config ?? {})) {
118
+ if (!values.from) continue;
119
+ const version = installedVersion(root, values.from);
120
+ if (version) report('ok', t('extension', { name: values.from, version }));
121
+ else report('fail', t('extensionMissing', { name: values.from, section }), t('extensionFix', { name: values.from }));
122
+ }
123
+
124
+ const port = Number(config?.serve?.port ?? defaultPort);
125
+ const state = await portState(port);
126
+ if (state === 'free') report('ok', t('port', { port }));
127
+ else report('warn', t(state === 'EACCES' ? 'portDenied' : 'portUsed', { port }), t('portFix'));
128
+
129
+ let buildError = '';
130
+ const code = await runBuild(root, { quiet: true, silentErrors: true, onError: message => { buildError = message; } });
131
+ if (!code) report('ok', t('build'));
132
+ else report('fail', t('buildBad', { error: buildError.split('\n').find(Boolean) ?? '?' }), t('buildFix'));
133
+ }
134
+
135
+ const failures = results.filter(level => level === 'fail').length;
136
+ const warnings = results.filter(level => level === 'warn').length;
137
+ console.log('\n' + (failures ? red(t('issues', { count: failures })) : green(t('fine'))) + (warnings ? ' ' + yellow(t('warnings', { count: warnings })) : ''));
138
+ if (failures) process.exitCode = 1;
139
+ }