@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.
@@ -0,0 +1,237 @@
1
+ // Helpers every CLI command shares: language, colors, prompts, flags, the project folder and its .config.
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { createInterface } from 'node:readline/promises';
6
+
7
+ // Messages follow the system language (ALIENS_LANG overrides it): English, Portuguese, Spanish or Chinese.
8
+ export const language = (() => {
9
+ const tag = (process.env.ALIENS_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG ||
10
+ Intl.DateTimeFormat().resolvedOptions().locale || 'en').toLowerCase();
11
+ return ['pt', 'es', 'zh'].find(code => tag.startsWith(code)) ?? 'en';
12
+ })();
13
+ export const pick = messages => messages[language] ?? messages.en;
14
+
15
+ export const cliRoot = resolve(import.meta.dirname, '..');
16
+ export const cliVersion = JSON.parse(readFileSync(join(cliRoot, 'package.json'), 'utf8')).version;
17
+ export const cliPackage = '@aliens-syndicate/cli';
18
+ export const minimumNode = '22.13.0';
19
+ export const defaultPort = 5151;
20
+
21
+ // Every project carries a copy of these tools, so it builds with the tools of the CLI version that created it.
22
+ export const projectToolFiles = ['build.mjs', 'watch.mjs', 'runtime.mjs', 'project-layout.mjs'];
23
+ export const projectToolDirectories = ['vscode-space'];
24
+
25
+ // The optional extensions a project can declare in .config under <section>: from:.
26
+ export const extensions = [
27
+ { section: 'style', name: '@aliens-syndicate/style' },
28
+ { section: 'icons', name: '@aliens-syndicate/icons', extra: ' style: stroke-rounded\n' },
29
+ { section: 'elements', name: '@aliens-syndicate/elements' }
30
+ ];
31
+
32
+ const paint = code => text => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : String(text);
33
+ export const bold = paint(1);
34
+ export const dim = paint(2);
35
+ export const red = paint(31);
36
+ export const green = paint(32);
37
+ export const yellow = paint(33);
38
+ export const cyan = paint(36);
39
+ export const ok = text => `${green('✓')} ${text}`;
40
+ export const fail = text => `${red('✗')} ${text}`;
41
+ export const warn = text => `${yellow('!')} ${text}`;
42
+
43
+ export class CliError extends Error {}
44
+
45
+ // Reads --flag, --flag=value, --flag value, -f value and --no-flag. Every flag the command does not know is an error.
46
+ export function parseFlags(args, { booleans = [], values = [], aliases = {} } = {}) {
47
+ const flags = {};
48
+ const positionals = [];
49
+ for (let index = 0; index < args.length; index++) {
50
+ const argument = args[index];
51
+ if (!argument.startsWith('-') || argument === '-') {
52
+ positionals.push(argument);
53
+ continue;
54
+ }
55
+ let [name, value] = argument.replace(/^--?/, '').split(/=(.*)/s);
56
+ name = aliases[name] ?? name;
57
+ if (booleans.includes(name)) flags[name] = true;
58
+ else if (name.startsWith('no-') && booleans.includes(name.slice(3))) flags[name.slice(3)] = false;
59
+ else if (values.includes(name)) {
60
+ value ??= args[++index];
61
+ if (value === undefined) throw new CliError(pick(unknownFlag).missing.replace('{flag}', argument));
62
+ flags[name] = value;
63
+ } else throw new CliError(pick(unknownFlag).unknown.replace('{flag}', argument));
64
+ }
65
+ return { flags, positionals };
66
+ }
67
+ const unknownFlag = {
68
+ en: { unknown: 'Unknown option {flag}. Run aliens help to see the options.', missing: '{flag} needs a value.' },
69
+ pt: { unknown: 'Opção desconhecida {flag}. Rode aliens help para ver as opções.', missing: '{flag} precisa de um valor.' },
70
+ es: { unknown: 'Opción desconocida {flag}. Ejecuta aliens help para ver las opciones.', missing: '{flag} necesita un valor.' },
71
+ zh: { unknown: '未知选项 {flag}。运行 aliens help 查看可用选项。', missing: '{flag} 需要一个值。' }
72
+ };
73
+
74
+ export const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY && !process.env.CI);
75
+
76
+ async function question(text) {
77
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
78
+ try {
79
+ return (await reader.question(text)).trim();
80
+ } finally {
81
+ reader.close();
82
+ }
83
+ }
84
+
85
+ export async function ask(text, fallback) {
86
+ const answer = await question(`${cyan('?')} ${bold(text)} ${dim(`(${fallback})`)} `);
87
+ return answer || fallback;
88
+ }
89
+
90
+ export async function confirm(text, fallback = true) {
91
+ const yes = pick({ en: 'y', pt: 's', es: 's', zh: 'y' });
92
+ const hint = fallback ? `${yes.toUpperCase()}/n` : `${yes}/N`;
93
+ const answer = (await question(`${cyan('?')} ${bold(text)} ${dim(`(${hint})`)} `)).toLowerCase();
94
+ if (!answer) return fallback;
95
+ return answer.startsWith('y') || answer.startsWith(yes);
96
+ }
97
+
98
+ export async function select(text, options, fallback = 0) {
99
+ console.log(`${cyan('?')} ${bold(text)}`);
100
+ options.forEach((option, index) => console.log(` ${cyan(index + 1)}. ${option}`));
101
+ while (true) {
102
+ const answer = await question(` ${dim(`1-${options.length} (${fallback + 1})`)} `);
103
+ if (!answer) return fallback;
104
+ const chosen = Number(answer) - 1;
105
+ if (Number.isInteger(chosen) && chosen >= 0 && chosen < options.length) return chosen;
106
+ const named = options.findIndex(option => option === answer);
107
+ if (named >= 0) return named;
108
+ }
109
+ }
110
+
111
+ // A project is the nearest folder, from the current one up, that holds .config and tools/build.mjs.
112
+ export function findProject(from = process.cwd()) {
113
+ let directory = resolve(from);
114
+ while (true) {
115
+ if (existsSync(join(directory, '.config')) && existsSync(join(directory, 'tools', 'build.mjs'))) return directory;
116
+ const parent = dirname(directory);
117
+ if (parent === directory) return null;
118
+ directory = parent;
119
+ }
120
+ }
121
+
122
+ export function requireProject() {
123
+ const root = findProject();
124
+ if (!root) throw new CliError(pick({
125
+ en: 'No Aliens project here: no folder from this one up has .config and tools/build.mjs. Create one with aliens new <name>.',
126
+ pt: 'Nenhum projeto Aliens aqui: nenhuma pasta daqui para cima tem .config e tools/build.mjs. Crie um com aliens new <nome>.',
127
+ es: 'No hay un proyecto Aliens aquí: ninguna carpeta desde esta hacia arriba tiene .config y tools/build.mjs. Crea uno con aliens new <nombre>.',
128
+ zh: '这里没有 Aliens 项目:从当前文件夹向上都没有 .config 和 tools/build.mjs。用 aliens new <名称> 创建一个。'
129
+ }));
130
+ return root;
131
+ }
132
+
133
+ // .config is Space: sections at the first level and key: value pairs under them. Comments start with #.
134
+ export function readConfig(root) {
135
+ const config = {};
136
+ let section = null;
137
+ for (const line of readFileSync(join(root, '.config'), 'utf8').split(/\r?\n/)) {
138
+ const value = line.trim();
139
+ if (!value || value.startsWith('#')) continue;
140
+ const pair = /^([\w.-]+):\s*(.*)$/.exec(value);
141
+ if (!pair) continue;
142
+ if (line === line.trimStart()) {
143
+ section = pair[1];
144
+ config[section] ??= {};
145
+ } else if (section) config[section][pair[1]] = pair[2];
146
+ }
147
+ return config;
148
+ }
149
+
150
+ // npm is npm.cmd on Windows, which spawn only runs through the shell.
151
+ export function runCommand(command, args, options = {}) {
152
+ return new Promise((resolvePromise, reject) => {
153
+ const child = spawn(command, args, { stdio: 'inherit', shell: process.platform === 'win32', ...options });
154
+ child.on('error', reject);
155
+ child.on('exit', code => resolvePromise(code ?? 1));
156
+ });
157
+ }
158
+
159
+ export function captureCommand(command, args, options = {}) {
160
+ return new Promise(resolvePromise => {
161
+ const child = spawn(command, args, { shell: process.platform === 'win32', ...options });
162
+ let output = '';
163
+ let errors = '';
164
+ child.stdout?.on('data', chunk => { output += chunk; });
165
+ child.stderr?.on('data', chunk => { errors += chunk; });
166
+ child.on('error', () => resolvePromise({ code: 1, output: '', errors }));
167
+ child.on('exit', code => resolvePromise({ code: code ?? 1, output: output.trim(), errors }));
168
+ });
169
+ }
170
+
171
+ // The newest version published on npm; false when npm says the package does not exist; null when npm cannot answer.
172
+ export async function latestVersion(name) {
173
+ const timer = AbortSignal.timeout(8000);
174
+ const { code, output, errors } = await captureCommand('npm', ['view', name, 'version'], { signal: timer, stdio: ['ignore', 'pipe', 'pipe'] });
175
+ if (code === 0 && /^\d+\.\d+\.\d+/.test(output)) return output;
176
+ return /E404|404 Not Found/.test(errors) ? false : null;
177
+ }
178
+
179
+ export function compareVersions(left, right) {
180
+ const parts = version => version.split(/[.-]/).slice(0, 3).map(Number);
181
+ const [a, b] = [parts(left), parts(right)];
182
+ for (let index = 0; index < 3; index++) if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;
183
+ return 0;
184
+ }
185
+
186
+ // The build stops with an uncaught Error; this keeps its message (file:line and the fix) and drops Node's stack trace.
187
+ export function buildMessage(stderr) {
188
+ const lines = stderr.split(/\r?\n/);
189
+ const start = lines.findIndex(line => /^\w*Error: /.test(line));
190
+ if (start < 0) return stderr.trim();
191
+ const end = lines.findIndex((line, index) => index > start && /^\s+at /.test(line));
192
+ return lines.slice(start, end < 0 ? undefined : end).join('\n').replace(/^\w*Error: /, '').trim();
193
+ }
194
+
195
+ // Runs the project's own tools/build.mjs and resolves with its exit code; onError receives the build's error message.
196
+ export function runBuild(root, { onError, quiet = false, silentErrors = false } = {}) {
197
+ return new Promise(resolvePromise => {
198
+ const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', join(root, 'tools', 'build.mjs')],
199
+ { cwd: root, stdio: ['ignore', quiet ? 'ignore' : 'inherit', 'pipe'] });
200
+ let errors = '';
201
+ child.stderr.on('data', chunk => { errors += chunk; });
202
+ child.on('exit', code => {
203
+ const message = buildMessage(errors);
204
+ if (code && !silentErrors && message) console.error(red(message));
205
+ else if (!code && errors.trim() && !silentErrors) process.stderr.write(errors);
206
+ if (code && onError) onError(message);
207
+ resolvePromise(code ?? 1);
208
+ });
209
+ });
210
+ }
211
+
212
+ // The version of a package installed for the project: node_modules/<name>/package.json, from the project up.
213
+ // A local extension written as ./path reports "local".
214
+ export function installedVersion(root, name) {
215
+ if (/^\.{1,2}\//.test(name)) return existsSync(join(root, name, 'index.mjs')) ? 'local' : null;
216
+ let directory = root;
217
+ while (true) {
218
+ const manifest = join(directory, 'node_modules', ...name.split('/'), 'package.json');
219
+ if (existsSync(manifest)) {
220
+ try {
221
+ return JSON.parse(readFileSync(manifest, 'utf8')).version ?? '?';
222
+ } catch {
223
+ return '?';
224
+ }
225
+ }
226
+ const parent = dirname(directory);
227
+ if (parent === directory) return null;
228
+ directory = parent;
229
+ }
230
+ }
231
+
232
+ // Accepts HeroCard, heroCard, hero_card or "hero card" and returns hero-card.
233
+ export function kebab(name) {
234
+ return name.trim().replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase();
235
+ }
236
+ export const validName = name => /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name);
237
+ export const pascal = name => name.split(/[.-]/).map(word => word[0].toUpperCase() + word.slice(1)).join('');
package/tools/cli.mjs CHANGED
@@ -1,61 +1,193 @@
1
1
  #!/usr/bin/env node
2
- // Entry point of the @aliens-syndicate/cli package: aliens create <folder> | aliens build | aliens watch | aliens --version.
2
+ // Entry point of the @aliens-syndicate/cli package. aliens help lists the commands; each one lives in its own module.
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
- import { basename, join } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
-
7
- const [command, ...args] = process.argv.slice(2);
8
- const { version } = JSON.parse(readFileSync(join(import.meta.dirname, '..', 'package.json'), 'utf8'));
9
- // Messages follow the system language (ALIENS_LANG overrides it): English, Portuguese, Spanish or Chinese.
10
- const language = (() => {
11
- const tag = (process.env.ALIENS_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG ||
12
- Intl.DateTimeFormat().resolvedOptions().locale || 'en').toLowerCase();
13
- return ['pt', 'es', 'zh'].find(code => tag.startsWith(code)) ?? 'en';
14
- })();
15
- const text = {
16
- en: { usage: 'Usage', create: 'Creates an Aliens project in the given folder.', build: 'Generates the preview in dist/ from the current folder.',
17
- watch: 'Rebuilds dist/ and ai/.map on every saved file.',
18
- version: 'Shows the CLI version.', folder: 'folder', missing: 'No Aliens project in this folder: tools/build.mjs was not found.' },
19
- pt: { usage: 'Uso', create: 'Cria um projeto Aliens na pasta indicada.', build: 'Gera a prévia em dist/ a partir da pasta atual.',
20
- watch: 'Refaz dist/ e ai/.map a cada arquivo salvo.',
21
- version: 'Mostra a versão do CLI.', folder: 'pasta', missing: 'Nenhum projeto Aliens nesta pasta: tools/build.mjs não foi encontrado.' },
22
- es: { usage: 'Uso', create: 'Crea un proyecto Aliens en la carpeta indicada.', build: 'Genera la vista previa en dist/ desde la carpeta actual.',
23
- watch: 'Rehace dist/ y ai/.map con cada archivo guardado.',
24
- version: 'Muestra la versión del CLI.', folder: 'carpeta', missing: 'No hay un proyecto Aliens en esta carpeta: no se encontró tools/build.mjs.' },
25
- zh: { usage: '用法', create: '在指定文件夹中创建 Aliens 项目。', build: '在当前文件夹中生成 dist/ 预览。',
26
- watch: '每次保存文件都会重新生成 dist/ 和 ai/.map。',
27
- version: '显示 CLI 版本。', folder: '文件夹', missing: '此文件夹中没有 Aliens 项目:未找到 tools/build.mjs。' }
28
- }[language];
29
- const create = `aliens create <${text.folder}>`;
30
- const help = `Aliens ${version}
31
-
32
- ${text.usage}:
33
- ${create.padEnd(24)}${text.create}
34
- ${'aliens build'.padEnd(24)}${text.build}
35
- ${'aliens watch'.padEnd(24)}${text.watch}
36
- ${'aliens --version'.padEnd(24)}${text.version}
4
+ import { join } from 'node:path';
5
+ import {
6
+ CliError, bold, captureCommand, cliPackage, cliRoot, cliVersion, installedVersion, cyan, defaultPort, dim, findProject, parseFlags, pick, readConfig, red, requireProject, runBuild
7
+ } from './cli-shared.mjs';
8
+
9
+ const commands = [
10
+ { name: 'new', aliases: ['n', 'create'], usage: 'aliens new <name>', load: async () => (await import('./create.mjs')).create,
11
+ about: { en: 'Creates an Aliens project, asking which extensions to install.', pt: 'Cria um projeto Aliens e pergunta quais extensões instalar.',
12
+ es: 'Crea un proyecto Aliens y pregunta qué extensiones instalar.', zh: '创建 Aliens 项目,并询问要安装哪些扩展。' },
13
+ options: [['-y, --yes', { en: 'Accepts every default without asking', pt: 'Aceita todos os padrões sem perguntar', es: 'Acepta todos los valores por defecto sin preguntar', zh: '不询问,全部使用默认值' }],
14
+ ['--no-style, --no-icons, --no-elements', { en: 'Leaves that extension out', pt: 'Deixa essa extensão de fora', es: 'Deja fuera esa extensión', zh: '不包含该扩展' }],
15
+ ['--skip-install', { en: 'Creates the files without running npm install', pt: 'Cria os arquivos sem rodar o npm install', es: 'Crea los archivos sin ejecutar npm install', zh: '只创建文件,不运行 npm install' }]] },
16
+ { name: 'run', aliases: ['watch'], usage: 'aliens run [--port <number>]', load: async () => (await import('./serve.mjs')).serve,
17
+ about: { en: `Builds, serves on http://localhost:${defaultPort} and rebuilds and reloads the browser on every save.`,
18
+ pt: `Faz o build, serve em http://localhost:${defaultPort} e refaz o build e recarrega o navegador a cada arquivo salvo.`,
19
+ es: `Hace el build, sirve en http://localhost:${defaultPort} y rehace el build y recarga el navegador con cada archivo guardado.`,
20
+ zh: `构建并在 http://localhost:${defaultPort} 上提供服务,每次保存都会重新构建并刷新浏览器。` },
21
+ options: [['-p, --port <number>', { en: `Port of the server (default ${defaultPort}, or serve: port: in .config)`, pt: `Porta do servidor (padrão ${defaultPort}, ou serve: port: no .config)`,
22
+ es: `Puerto del servidor (por defecto ${defaultPort}, o serve: port: en .config)`, zh: `服务器端口(默认 ${defaultPort},或 .config 中的 serve: port:)` }]] },
23
+ { name: 'build', aliases: [], usage: 'aliens build', load: async () => build,
24
+ about: { en: 'Generates the preview in dist/ and the ai/.map index.', pt: 'Gera a prévia em dist/ e o índice ai/.map.', es: 'Genera la vista previa en dist/ y el índice ai/.map.', zh: '在 dist/ 中生成预览,并生成 ai/.map 索引。' } },
25
+ { name: 'generate', aliases: ['g'], usage: 'aliens generate <kind> <name>', load: async () => (await import('./generate.mjs')).generate,
26
+ about: { en: 'Creates Space files. Elements and pages get .markup, .logic, .style and .test; existing files are kept.',
27
+ pt: 'Cria arquivos Space. Elements e páginas ganham .markup, .logic, .style e .test; arquivos que já existem são mantidos.',
28
+ es: 'Crea archivos Space. Elements y páginas reciben .markup, .logic, .style y .test; los archivos existentes se conservan.',
29
+ zh: '创建 Space 文件。Element 和页面会得到 .markup、.logic、.style 和 .test;已存在的文件会保留。' },
30
+ options: [['element (e) <level>/<name>', { en: 'atoms, molecules, organisms or templates; without a level, the CLI asks', pt: 'atoms, molecules, organisms ou templates; sem o nível, a CLI pergunta',
31
+ es: 'atoms, molecules, organisms o templates; sin el nivel, la CLI pregunta', zh: 'atoms、molecules、organisms 或 templates;不写层级时 CLI 会询问' }],
32
+ ['page (p), service (s)', { en: 'A page in pages/ or a .service in services/', pt: 'Uma página em pages/ ou um .service em services/', es: 'Una página en pages/ o un .service en services/', zh: 'pages/ 中的页面,或 services/ 中的 .service' }],
33
+ ['directive (d), interface (i), model (m), validator (v), route (r)', { en: 'And api, animation, enum, error, guard, interceptor, mock, pipe, storage, agent, rule, skill',
34
+ pt: 'E também api, animation, enum, error, guard, interceptor, mock, pipe, storage, agent, rule, skill', es: 'Y también api, animation, enum, error, guard, interceptor, mock, pipe, storage, agent, rule, skill',
35
+ zh: '以及 api、animation、enum、error、guard、interceptor、mock、pipe、storage、agent、rule、skill' }],
36
+ ['--dry-run', { en: 'Shows what would be created without writing', pt: 'Mostra o que seria criado sem gravar', es: 'Muestra lo que se crearía sin escribir', zh: '只显示将创建的内容,不写入' }]] },
37
+ { name: 'doctor', aliases: [], usage: 'aliens doctor', load: async () => (await import('./doctor.mjs')).doctor,
38
+ about: { en: 'Checks Node.js, npm, the CLI version, .config, the packages, the port and the build, with the fix for each problem.',
39
+ pt: 'Verifica Node.js, npm, a versão da CLI, o .config, os pacotes, a porta e o build, com a correção de cada problema.',
40
+ es: 'Revisa Node.js, npm, la versión de la CLI, .config, los paquetes, el puerto y el build, con la corrección de cada problema.',
41
+ zh: '检查 Node.js、npm、CLI 版本、.config、依赖包、端口和构建,并给出每个问题的修复方法。' } },
42
+ { name: 'update', aliases: [], usage: 'aliens update', load: async () => (await import('./update.mjs')).update,
43
+ about: { en: 'Updates the @aliens-syndicate packages of the project and copies the tools/ of the installed CLI.',
44
+ pt: 'Atualiza os pacotes @aliens-syndicate do projeto e copia o tools/ da CLI instalada.',
45
+ es: 'Actualiza los paquetes @aliens-syndicate del proyecto y copia el tools/ de la CLI instalada.',
46
+ zh: '更新项目的 @aliens-syndicate 包,并复制已安装 CLI 的 tools/。' },
47
+ options: [['--dry-run', { en: 'Lists the changes without applying them', pt: 'Lista as mudanças sem aplicar', es: 'Lista los cambios sin aplicarlos', zh: '只列出更改,不应用' }]] },
48
+ { name: 'cache', aliases: [], usage: 'aliens cache', load: async () => (await import('./cache.mjs')).cache,
49
+ about: { en: 'Deletes dist/ and the caches the tools keep.', pt: 'Apaga o dist/ e os caches que as ferramentas guardam.', es: 'Borra dist/ y las cachés que guardan las herramientas.', zh: '删除 dist/ 以及工具保留的缓存。' } },
50
+ { name: 'version', aliases: [], usage: 'aliens version', load: async () => version,
51
+ about: { en: 'Shows the CLI, Node.js and package versions. aliens --version prints only the number.',
52
+ pt: 'Mostra as versões da CLI, do Node.js e dos pacotes. aliens --version mostra só o número.',
53
+ es: 'Muestra las versiones de la CLI, Node.js y los paquetes. aliens --version muestra solo el número.',
54
+ zh: '显示 CLI、Node.js 和依赖包的版本。aliens --version 只输出版本号。' } }
55
+ ];
56
+
57
+ const labels = {
58
+ en: { usage: 'Usage', commands: 'Commands', options: 'Options', aliases: 'alias', more: 'Run aliens <command> --help to see its options.',
59
+ unknown: 'Unknown command "{command}".', suggestion: 'Did you mean {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'System', project: 'Project', packages: 'Packages', packageManager: 'Package Manager', extensions: 'extensions', package: 'Package', version: 'Version', missing: 'not installed', repository: 'this repository', outside: 'Run aliens version inside a project to see its packages.' },
60
+ pt: { usage: 'Uso', commands: 'Comandos', options: 'Opções', aliases: 'atalho', more: 'Rode aliens <comando> --help para ver as opções dele.',
61
+ unknown: 'Comando desconhecido "{command}".', suggestion: 'Você quis dizer {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'Sistema', project: 'Projeto', packages: 'Pacotes', packageManager: 'Gerenciador de pacotes', extensions: 'extensões', package: 'Pacote', version: 'Versão', missing: 'não instalado', repository: 'este repositório', outside: 'Rode aliens version dentro de um projeto para ver os pacotes dele.' },
62
+ es: { usage: 'Uso', commands: 'Comandos', options: 'Opciones', aliases: 'atajo', more: 'Ejecuta aliens <comando> --help para ver sus opciones.',
63
+ unknown: 'Comando desconocido "{command}".', suggestion: '¿Quisiste decir {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'Sistema', project: 'Proyecto', packages: 'Paquetes', packageManager: 'Gestor de paquetes', extensions: 'extensiones', package: 'Paquete', version: 'Versión', missing: 'no instalado', repository: 'este repositorio', outside: 'Ejecuta aliens version dentro de un proyecto para ver sus paquetes.' },
64
+ zh: { usage: '用法', commands: '命令', options: '选项', aliases: '别名', more: '运行 aliens <命令> --help 查看该命令的选项。',
65
+ unknown: '未知命令“{command}”。', suggestion: '你是想输入 {suggestion} 吗?', cli: 'Aliens CLI', node: 'Node.js', os: '系统', project: '项目', packages: '依赖包', packageManager: '包管理器', extensions: '扩展', package: '依赖包', version: '版本', missing: '未安装', repository: '本仓库', outside: '在项目中运行 aliens version 可查看其依赖包。' }
66
+ };
67
+ const label = pick(labels);
68
+
69
+ function help(command) {
70
+ if (command) {
71
+ const lines = [`${bold(command.usage)}${command.aliases.length ? dim(` (${label.aliases}: ${command.aliases.join(', ')})`) : ''}`, '', pick(command.about)];
72
+ if (command.options?.length) {
73
+ lines.push('', bold(label.options));
74
+ const width = Math.max(...command.options.map(([flag]) => flag.length)) + 3;
75
+ for (const [flag, about] of command.options) lines.push(` ${cyan(flag.padEnd(width))}${pick(about)}`);
76
+ }
77
+ return lines.join('\n') + '\n';
78
+ }
79
+ const width = Math.max(...commands.map(entry => entry.usage.length)) + 3;
80
+ return `${bold(`Aliens ${cliVersion}`)}
81
+
82
+ ${bold(label.usage)}: aliens <command> [options]
83
+
84
+ ${bold(label.commands)}
85
+ ${commands.map(entry => ` ${cyan(entry.usage.padEnd(width))}${pick(entry.about)}${entry.aliases.length ? dim(` (${label.aliases}: ${entry.aliases.join(', ')})`) : ''}`).join('\n')}
86
+
87
+ ${dim(label.more)}
37
88
  `;
89
+ }
90
+
91
+ async function build(args) {
92
+ parseFlags(args);
93
+ const root = requireProject();
94
+ const code = await runBuild(root);
95
+ if (code) process.exitCode = code;
96
+ }
97
+
98
+
99
+ // The banner of aliens version, in the figlet Standard font, painted in greens from dark to light like Angular's ng version.
100
+ const banner = [
101
+ ' _ _ _ ____ _ ___',
102
+ ' / \\ | |(_) ___ _ __ ___ / ___|| | |_ _|',
103
+ " / _ \\ | || | / _ \\ | '_ \\ / __| | | | | | |",
104
+ ' / ___ \\ | || || __/ | | | |\\__ \\ | |___ | |___ | |',
105
+ '/_/ \\_\\|_||_| \\___| |_| |_||___/ \\____||_____||___|'
106
+ ];
107
+ const colorful = () => process.stdout.isTTY && !process.env.NO_COLOR;
108
+ const shade = (code, text) => colorful() ? `\x1b[1;38;5;${code}m${text}\x1b[0m` : text;
109
+
110
+ async function version(args) {
111
+ parseFlags(args);
112
+ const npm = await captureCommand('npm', ['--version'], { stdio: ['ignore', 'pipe', 'ignore'] });
113
+ const root = findProject();
114
+ const config = root ? readConfig(root) : null;
115
+ const info = [[label.cli, cliVersion], [label.node, process.versions.node],
116
+ [label.packageManager, npm.code === 0 ? `npm ${npm.output}` : '—'], [label.os, `${process.platform} ${process.arch}`]];
117
+ const extensionPackages = config ? Object.values(config).map(values => values.from).filter(name => name && !/^\.{1,2}\//.test(name)) : [];
118
+ if (config) info.push([label.project, `${config.project?.name ?? '?'} ${config.project?.version ?? ''}`.trim()]);
119
+
120
+ console.log('');
121
+ banner.forEach((line, index) => console.log(shade([22, 28, 34, 40, 46][index], line)));
122
+ console.log('');
123
+ for (const [name, value] of info) console.log(`${name}: ${value}`);
124
+ if (config) {
125
+ const sections = Object.entries(config).filter(([, values]) => values.from).map(([section]) => section);
126
+ if (sections.length) console.log(dim(`... ${label.extensions}: ${sections.join(', ')}`));
127
+ }
128
+
129
+ if (!root) {
130
+ console.log('\n' + dim(label.outside));
131
+ console.log('');
132
+ return;
133
+ }
134
+ // The table lists every @aliens-syndicate package of the project: the ones in package.json and the ones .config declares.
135
+ const manifestPath = join(root, 'package.json');
136
+ const manifest = existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : {};
137
+ const names = new Set([...Object.keys({ ...manifest.dependencies, ...manifest.devDependencies }), ...extensionPackages]
138
+ .filter(name => name.startsWith('@aliens-syndicate/')));
139
+ if (root === cliRoot) names.add(cliPackage);
140
+ const rows = [...names].sort().map(name => {
141
+ const found = name === cliPackage && root === cliRoot ? `${cliVersion} ${dim(`(${label.repository})`)}` : installedVersion(root, name);
142
+ return [name, found ?? red(label.missing)];
143
+ });
144
+ if (!rows.length) {
145
+ console.log('');
146
+ return;
147
+ }
148
+ const width = Math.max(label.package.length, ...rows.map(([name]) => name.length)) + 6;
149
+ console.log(`\n${bold(label.package.padEnd(width))}${bold(label.version)}`);
150
+ console.log(dim('-'.repeat(width + 18)));
151
+ for (const [name, value] of rows) console.log(`${name.padEnd(width)}${value}`);
152
+ console.log('');
153
+ }
38
154
 
39
- // Each script reads its own arguments, so the CLI hands them over through process.argv.
40
- async function run(script, scriptArgs) {
41
- process.argv = [process.argv[0], script, ...scriptArgs];
42
- await import(pathToFileURL(script).href);
155
+ // The closest command name, so a typo like "aliens buidl" points to "aliens build".
156
+ function closest(word) {
157
+ const distance = (a, b) => {
158
+ const row = Array.from({ length: b.length + 1 }, (_, index) => index);
159
+ for (let i = 1; i <= a.length; i++) {
160
+ let previous = row[0]++;
161
+ for (let j = 1; j <= b.length; j++) {
162
+ const current = row[j];
163
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
164
+ previous = current;
165
+ }
166
+ }
167
+ return row[b.length];
168
+ };
169
+ const [best] = commands.flatMap(entry => [entry.name, ...entry.aliases]).map(name => [name, distance(word, name)]).sort((a, b) => a[1] - b[1]);
170
+ return best && best[1] <= 2 ? best[0] : null;
43
171
  }
44
172
 
45
- if (command === 'create') {
46
- await run(join(import.meta.dirname, 'create.mjs'), args);
47
- } else if (command === 'build' || command === 'watch') {
48
- // A project carries its own tools/, so the build always matches the project's version.
49
- const script = join(process.cwd(), 'tools', command === 'build' ? 'build.mjs' : 'watch.mjs');
50
- if (!existsSync(script)) {
51
- console.error(text.missing.replace('tools/build.mjs', 'tools/' + basename(script)));
52
- process.exitCode = 1;
173
+ const [word, ...args] = process.argv.slice(2);
174
+ try {
175
+ if (word === '--version' || word === '-v') console.log(cliVersion);
176
+ else if (!word || word === 'help' || word === '--help' || word === '-h') {
177
+ const topic = commands.find(entry => entry.name === args[0] || entry.aliases.includes(args[0]));
178
+ console.log(help(topic));
53
179
  } else {
54
- await run(script, args);
180
+ const command = commands.find(entry => entry.name === word || entry.aliases.includes(word));
181
+ if (!command) {
182
+ const suggestion = closest(word);
183
+ console.error(red(label.unknown.replace('{command}', word)) + (suggestion ? ' ' + label.suggestion.replace('{suggestion}', bold(`aliens ${suggestion}`)) : ''));
184
+ console.log('\n' + help());
185
+ process.exitCode = 1;
186
+ } else if (args.includes('--help') || args.includes('-h')) console.log(help(command));
187
+ else await (await command.load())(args);
55
188
  }
56
- } else if (command === '--version' || command === '-v') {
57
- console.log(version);
58
- } else {
59
- console.log(help);
60
- if (command && command !== 'help' && command !== '--help' && command !== '-h') process.exitCode = 1;
189
+ } catch (error) {
190
+ if (!(error instanceof CliError)) throw error;
191
+ console.error(red(error.message));
192
+ process.exitCode = 1;
61
193
  }