@aliens-syndicate/cli 0.1.3 → 0.1.4
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.es-ES.md +265 -0
- package/README.md +19 -3
- package/README.pt-BR.md +265 -0
- package/README.zh-CN.md +265 -0
- package/package.json +2 -1
- package/tools/build.mjs +47 -11
- package/tools/cache.mjs +41 -0
- package/tools/cli-shared.mjs +237 -0
- package/tools/cli.mjs +145 -53
- package/tools/create.mjs +202 -82
- package/tools/doctor.mjs +139 -0
- package/tools/generate.mjs +175 -0
- package/tools/project-layout.mjs +3 -3
- package/tools/serve.mjs +152 -0
- package/tools/starter/ai/rules/architecture.rule +1 -0
- package/tools/starter/ai/skills/create-element.skill +2 -1
- package/tools/update.mjs +110 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// aliens generate (g) <kind> <name>: writes Space files that already follow the declaration, folder and name rules.
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join, relative } from 'node:path';
|
|
5
|
+
import { agentByType, applicationByType, elementLevels } from './project-layout.mjs';
|
|
6
|
+
import {
|
|
7
|
+
CliError, bold, cyan, dim, green, interactive, kebab, parseFlags, pascal, pick, readConfig, requireProject, select,
|
|
8
|
+
ask, validName, yellow
|
|
9
|
+
} from './cli-shared.mjs';
|
|
10
|
+
|
|
11
|
+
const text = {
|
|
12
|
+
en: {
|
|
13
|
+
usage: 'Usage: aliens generate <kind> <name>. Kinds: {kinds}.', kind: 'What do you want to generate?', name: 'Name',
|
|
14
|
+
unknownKind: 'Unknown kind "{kind}". Kinds: {kinds}.', badName: '"{name}" is not a valid name. Use lowercase words separated by hyphens, like hero-card.',
|
|
15
|
+
level: 'Which level is the Element?', needLevel: 'Tell the level in the name, like aliens g element molecules/{name}. Levels: {levels}.',
|
|
16
|
+
badLevel: '"{level}" is not a level. Levels: {levels}.', exists: 'already exists', create: 'CREATE', skip: 'SKIP',
|
|
17
|
+
nothing: 'Nothing to create: every file of {name} already exists.', conflict: '{name} already exists as {other} in {path}. Choose another name.',
|
|
18
|
+
dryRun: 'Dry run: no file was written.', renamed: 'Using the name {name}.',
|
|
19
|
+
useElement: 'Use it in any .markup with the tag {name}.', usePage: 'Add it to project/app/app.route to open it at a path.',
|
|
20
|
+
useFile: 'Run aliens build: ai/.map will list the new file.'
|
|
21
|
+
},
|
|
22
|
+
pt: {
|
|
23
|
+
usage: 'Uso: aliens generate <tipo> <nome>. Tipos: {kinds}.', kind: 'O que você quer gerar?', name: 'Nome',
|
|
24
|
+
unknownKind: 'Tipo desconhecido "{kind}". Tipos: {kinds}.', badName: '"{name}" não é um nome válido. Use palavras minúsculas separadas por hífen, como hero-card.',
|
|
25
|
+
level: 'Em qual nível fica o Element?', needLevel: 'Informe o nível no nome, como aliens g element molecules/{name}. Níveis: {levels}.',
|
|
26
|
+
badLevel: '"{level}" não é um nível. Níveis: {levels}.', exists: 'já existe', create: 'CRIADO', skip: 'IGNORADO',
|
|
27
|
+
nothing: 'Nada para criar: todos os arquivos de {name} já existem.', conflict: '{name} já existe como {other} em {path}. Escolha outro nome.',
|
|
28
|
+
dryRun: 'Simulação: nenhum arquivo foi gravado.', renamed: 'Usando o nome {name}.',
|
|
29
|
+
useElement: 'Use em qualquer .markup com a tag {name}.', usePage: 'Adicione em project/app/app.route para abrir num caminho.',
|
|
30
|
+
useFile: 'Rode aliens build: o ai/.map vai listar o arquivo novo.'
|
|
31
|
+
},
|
|
32
|
+
es: {
|
|
33
|
+
usage: 'Uso: aliens generate <tipo> <nombre>. Tipos: {kinds}.', kind: '¿Qué quieres generar?', name: 'Nombre',
|
|
34
|
+
unknownKind: 'Tipo desconocido "{kind}". Tipos: {kinds}.', badName: '"{name}" no es un nombre válido. Usa palabras en minúsculas separadas por guiones, como hero-card.',
|
|
35
|
+
level: '¿En qué nivel va el Element?', needLevel: 'Indica el nivel en el nombre, como aliens g element molecules/{name}. Niveles: {levels}.',
|
|
36
|
+
badLevel: '"{level}" no es un nivel. Niveles: {levels}.', exists: 'ya existe', create: 'CREADO', skip: 'OMITIDO',
|
|
37
|
+
nothing: 'Nada que crear: todos los archivos de {name} ya existen.', conflict: '{name} ya existe como {other} en {path}. Elige otro nombre.',
|
|
38
|
+
dryRun: 'Simulación: no se escribió ningún archivo.', renamed: 'Usando el nombre {name}.',
|
|
39
|
+
useElement: 'Úsalo en cualquier .markup con la etiqueta {name}.', usePage: 'Agrégala en project/app/app.route para abrirla en una ruta.',
|
|
40
|
+
useFile: 'Ejecuta aliens build: ai/.map listará el archivo nuevo.'
|
|
41
|
+
},
|
|
42
|
+
zh: {
|
|
43
|
+
usage: '用法:aliens generate <类型> <名称>。类型:{kinds}。', kind: '要生成什么?', name: '名称',
|
|
44
|
+
unknownKind: '未知类型“{kind}”。类型:{kinds}。', badName: '“{name}”不是有效名称。请使用以连字符分隔的小写单词,例如 hero-card。',
|
|
45
|
+
level: 'Element 放在哪个层级?', needLevel: '请在名称中写明层级,例如 aliens g element molecules/{name}。层级:{levels}。',
|
|
46
|
+
badLevel: '“{level}”不是层级。层级:{levels}。', exists: '已存在', create: '已创建', skip: '已跳过',
|
|
47
|
+
nothing: '无需创建:{name} 的所有文件都已存在。', conflict: '{name} 已作为 {other} 存在于 {path}。请换一个名称。',
|
|
48
|
+
dryRun: '试运行:没有写入任何文件。', renamed: '使用名称 {name}。',
|
|
49
|
+
useElement: '在任意 .markup 中用标签 {name} 使用它。', usePage: '把它加到 project/app/app.route,即可通过路径打开。',
|
|
50
|
+
useFile: '运行 aliens build:ai/.map 会列出新文件。'
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
|
|
54
|
+
|
|
55
|
+
// Short aliases for the kinds people generate most. The other kinds go by their full name.
|
|
56
|
+
const aliases = { e: 'element', p: 'page', s: 'service', d: 'directive', i: 'interface', m: 'model', v: 'validator', r: 'route' };
|
|
57
|
+
const componentKinds = ['element', 'page'];
|
|
58
|
+
const fileKinds = [...Object.keys(applicationByType), ...Object.keys(agentByType)];
|
|
59
|
+
const kinds = [...componentKinds, ...fileKinds];
|
|
60
|
+
const kindList = () => kinds.map(kind => {
|
|
61
|
+
const alias = Object.entries(aliases).find(([, value]) => value === kind)?.[0];
|
|
62
|
+
return alias ? `${kind} (${alias})` : kind;
|
|
63
|
+
}).join(', ');
|
|
64
|
+
const levelOf = word => elementLevels.find(level => level === word || level === word + 's');
|
|
65
|
+
|
|
66
|
+
const camel = name => name.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
67
|
+
|
|
68
|
+
// Each template matches the shape of the Hero examples, so the file builds as soon as it is written.
|
|
69
|
+
const bodies = {
|
|
70
|
+
markup: name => ` section id="${name}"\n p={${name} works}\n`,
|
|
71
|
+
logic: () => ' import:\n signal: aliens/core\n',
|
|
72
|
+
style: name => ` ${name}\n display: block\n`,
|
|
73
|
+
test: name => ` scenario: ${name} renders\n given: The page shows ${name}\n when: The page opens\n then: ${name} is visible\n`,
|
|
74
|
+
animation: () => ' durationMs: number = 180\n easing: string = "ease-out"\n fromOpacity: number = 0\n toOpacity: number = 1\n',
|
|
75
|
+
api: name => ` method: string = "GET"\n timeoutMs: number = 5000\n\n function path(id: number): string\n return "/api/${name}/" + id\n`,
|
|
76
|
+
directive: name => ` function className(active: boolean): string\n if active\n return "${name}-active"\n return "${name}"\n`,
|
|
77
|
+
enum: () => ' Active: string = "active"\n Inactive: string = "inactive"\n',
|
|
78
|
+
error: name => ` code: string = "${name.replaceAll('-', '_').toUpperCase()}"\n httpStatus: number = 500\n message: string = "${pascal(name)} failed."\n`,
|
|
79
|
+
guard: name => ` guard:\n name: ${name}\n require: authenticated\n redirectTo: home\n`,
|
|
80
|
+
interceptor: name => ` header: string = "X-Request-Id"\n\n function headerValue(id: number): string\n return "${name}-" + id\n`,
|
|
81
|
+
interface: () => ' id: number\n name: string\n',
|
|
82
|
+
mock: () => ' id: number = 1\n name: string = "Example"\n',
|
|
83
|
+
model: () => ' id: number = 0\n name: string = ""\n',
|
|
84
|
+
pipe: () => ' function transform(value: string): string\n return value\n',
|
|
85
|
+
route: name => ` routes:\n ${camel(name)}:\n path: /${name}\n element: ${name}\n`,
|
|
86
|
+
service: name => ` function describe(): string\n return "${name}"\n`,
|
|
87
|
+
storage: name => ` prefix: string = "${name}."\n\n function key(id: number): string\n return prefix + id\n`,
|
|
88
|
+
validator: () => ' function validate(value: string): boolean\n return value.length > 0\n',
|
|
89
|
+
agent: () => ' # Describe what this agent does, which files it reads first and which rules it follows.\n',
|
|
90
|
+
rule: () => ' # Write one rule per comment line, as a plain instruction.\n',
|
|
91
|
+
skill: () => ' # List the steps of this skill, one per comment line.\n'
|
|
92
|
+
};
|
|
93
|
+
const source = (kind, name) => `${pascal(kind)} ${pascal(name)}\n${bodies[kind](name)}`;
|
|
94
|
+
|
|
95
|
+
async function folders(directory) {
|
|
96
|
+
if (!existsSync(directory)) return [];
|
|
97
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
98
|
+
const found = await Promise.all(entries.filter(entry => entry.isDirectory()).map(async entry => {
|
|
99
|
+
const path = join(directory, entry.name);
|
|
100
|
+
return [path, ...await folders(path)];
|
|
101
|
+
}));
|
|
102
|
+
return found.flat();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function generate(args) {
|
|
106
|
+
const { flags, positionals } = parseFlags(args, { booleans: ['dry-run'] });
|
|
107
|
+
if (positionals.length > 2) throw new CliError(t('usage', { kinds: kindList() }));
|
|
108
|
+
const root = requireProject();
|
|
109
|
+
const config = readConfig(root);
|
|
110
|
+
const appDirectory = dirname(config.files?.entry ?? 'project/app/app.logic');
|
|
111
|
+
const agentDirectory = dirname(config.files?.agent ?? 'ai/.map');
|
|
112
|
+
|
|
113
|
+
let [kind, target] = positionals;
|
|
114
|
+
if (!kind) {
|
|
115
|
+
if (!interactive()) throw new CliError(t('usage', { kinds: kindList() }));
|
|
116
|
+
kind = kinds[await select(t('kind'), kinds)];
|
|
117
|
+
}
|
|
118
|
+
kind = aliases[kind] ?? kind;
|
|
119
|
+
if (!kinds.includes(kind)) throw new CliError(t('unknownKind', { kind, kinds: kindList() }));
|
|
120
|
+
if (!target) {
|
|
121
|
+
if (!interactive()) throw new CliError(t('usage', { kinds: kindList() }));
|
|
122
|
+
target = await ask(t('name'), kind === 'element' ? 'molecules/my-element' : `my-${kind}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const parts = target.split(/[\\/]/).filter(Boolean);
|
|
126
|
+
const name = kebab(parts.pop() ?? '');
|
|
127
|
+
if (!validName(name)) throw new CliError(t('badName', { name: target }));
|
|
128
|
+
if (name !== target.split(/[\\/]/).pop()) console.log(dim(t('renamed', { name })));
|
|
129
|
+
|
|
130
|
+
// Pages and Elements share one namespace: the build stops on two Elements with the same name.
|
|
131
|
+
const componentFolders = [...await folders(join(root, appDirectory, 'pages')), ...await folders(join(root, appDirectory, 'elements'))];
|
|
132
|
+
const existing = componentFolders.find(folder => folder.split(/[\\/]/).pop() === name && !elementLevels.includes(name));
|
|
133
|
+
let files;
|
|
134
|
+
if (kind === 'element' || kind === 'page') {
|
|
135
|
+
let folder;
|
|
136
|
+
if (existing) {
|
|
137
|
+
const other = existing.startsWith(join(root, appDirectory, 'pages')) ? 'page' : 'element';
|
|
138
|
+
if (other !== kind) throw new CliError(t('conflict', { name, other, path: relative(root, existing) }));
|
|
139
|
+
folder = existing;
|
|
140
|
+
} else if (kind === 'page') {
|
|
141
|
+
folder = join(root, appDirectory, 'pages', name);
|
|
142
|
+
} else {
|
|
143
|
+
let level = parts.length ? levelOf(parts[0]) : null;
|
|
144
|
+
if (parts.length && !level) throw new CliError(t('badLevel', { level: parts[0], levels: elementLevels.join(', ') }));
|
|
145
|
+
if (!level) {
|
|
146
|
+
if (!interactive()) throw new CliError(t('needLevel', { name, levels: elementLevels.join(', ') }));
|
|
147
|
+
level = elementLevels[await select(t('level'), elementLevels, 1)];
|
|
148
|
+
}
|
|
149
|
+
folder = join(root, appDirectory, 'elements', level, ...parts.slice(1).map(kebab), name);
|
|
150
|
+
}
|
|
151
|
+
files = ['markup', 'logic', 'style', 'test'].map(extension => [join(folder, `${name}.${extension}`), source(extension, name)]);
|
|
152
|
+
} else {
|
|
153
|
+
const directory = applicationByType[kind] ? join(root, appDirectory, applicationByType[kind]) : join(root, agentDirectory, agentByType[kind]);
|
|
154
|
+
files = [[join(directory, `${name}.${kind}`), source(kind, name)]];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const pending = files.filter(([path]) => !existsSync(path));
|
|
158
|
+
for (const [path] of files) {
|
|
159
|
+
const shown = relative(root, path);
|
|
160
|
+
console.log(pending.some(([file]) => file === path) ? `${green(t('create').padEnd(9))}${shown}` : `${yellow(t('skip').padEnd(9))}${shown} ${dim(`(${t('exists')})`)}`);
|
|
161
|
+
}
|
|
162
|
+
if (!pending.length) {
|
|
163
|
+
console.log(t('nothing', { name }));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (flags['dry-run']) {
|
|
167
|
+
console.log(dim(t('dryRun')));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
for (const [path, content] of pending) {
|
|
171
|
+
await mkdir(dirname(path), { recursive: true });
|
|
172
|
+
await writeFile(path, content, { flag: 'wx' });
|
|
173
|
+
}
|
|
174
|
+
console.log('\n' + (kind === 'element' ? t('useElement', { name: bold(cyan(name)) }) : kind === 'page' ? t('usePage') : t('useFile')));
|
|
175
|
+
}
|
package/tools/project-layout.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdir } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
|
|
4
|
-
const applicationByType = {
|
|
4
|
+
export const applicationByType = {
|
|
5
5
|
animation: 'animations',
|
|
6
6
|
api: 'apis',
|
|
7
7
|
directive: 'directives',
|
|
@@ -18,13 +18,13 @@ const applicationByType = {
|
|
|
18
18
|
storage: 'storage',
|
|
19
19
|
validator: 'validators'
|
|
20
20
|
};
|
|
21
|
-
const agentByType = { agent: 'agents', rule: 'rules', skill: 'skills' };
|
|
21
|
+
export const agentByType = { agent: 'agents', rule: 'rules', skill: 'skills' };
|
|
22
22
|
|
|
23
23
|
export const namedKinds = new Set([...Object.keys(applicationByType), ...Object.keys(agentByType), 'logic', 'markup', 'style', 'test']);
|
|
24
24
|
export const sharedDirectory = 'shared';
|
|
25
25
|
export const exampleMarker = '# Aliens example: Hero';
|
|
26
26
|
export const styleLayers = ['settings', 'tools', 'generic', 'elements', 'objects', 'components', 'utilities'];
|
|
27
|
-
const elementLevels = ['atoms', 'molecules', 'organisms', 'templates'];
|
|
27
|
+
export const elementLevels = ['atoms', 'molecules', 'organisms', 'templates'];
|
|
28
28
|
|
|
29
29
|
export async function createProjectDirectories(workspace) {
|
|
30
30
|
const directories = [
|
package/tools/serve.mjs
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// aliens run: builds the project, serves dist/ on port 5151 and rebuilds and reloads the browser on every saved file.
|
|
2
|
+
import { watch } from 'node:fs';
|
|
3
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { networkInterfaces } from 'node:os';
|
|
6
|
+
import { extname, join, normalize, relative, sep } from 'node:path';
|
|
7
|
+
import {
|
|
8
|
+
CliError, bold, cyan, defaultPort, dim, green, parseFlags, pick, readConfig, red, requireProject, runBuild
|
|
9
|
+
} from './cli-shared.mjs';
|
|
10
|
+
|
|
11
|
+
const text = {
|
|
12
|
+
en: { ready: 'Aliens dev server ready', local: 'Local', network: 'Network', watching: 'Watching files. Each save rebuilds and reloads the browser (Ctrl+C to stop).',
|
|
13
|
+
rebuilt: 'Rebuilt in {ms} ms', failed: 'Build failed. Fix the error above; the browser shows it too.', badPort: '--port takes a number from 1 to 65535.',
|
|
14
|
+
inUse: 'Port {port} is in use. Stop the other server or run aliens run --port <number>.',
|
|
15
|
+
denied: 'This system does not let you open port {port} without administrator rights. Run aliens run --port <number>, or set serve: port: in .config.' },
|
|
16
|
+
pt: { ready: 'Servidor Aliens pronto', local: 'Local', network: 'Rede', watching: 'Observando os arquivos. Cada arquivo salvo refaz o build e recarrega o navegador (Ctrl+C para parar).',
|
|
17
|
+
rebuilt: 'Build refeito em {ms} ms', failed: 'O build falhou. Corrija o erro acima; o navegador também mostra o erro.', badPort: '--port recebe um número de 1 a 65535.',
|
|
18
|
+
inUse: 'A porta {port} está em uso. Pare o outro servidor ou rode aliens run --port <número>.',
|
|
19
|
+
denied: 'Este sistema não deixa abrir a porta {port} sem permissão de administrador. Rode aliens run --port <número> ou defina serve: port: no .config.' },
|
|
20
|
+
es: { ready: 'Servidor Aliens listo', local: 'Local', network: 'Red', watching: 'Observando los archivos. Cada archivo guardado rehace el build y recarga el navegador (Ctrl+C para detener).',
|
|
21
|
+
rebuilt: 'Build rehecho en {ms} ms', failed: 'El build falló. Corrige el error de arriba; el navegador también lo muestra.', badPort: '--port recibe un número de 1 a 65535.',
|
|
22
|
+
inUse: 'El puerto {port} está en uso. Detén el otro servidor o ejecuta aliens run --port <número>.',
|
|
23
|
+
denied: 'Este sistema no permite abrir el puerto {port} sin permisos de administrador. Ejecuta aliens run --port <número> o define serve: port: en .config.' },
|
|
24
|
+
zh: { ready: 'Aliens 开发服务器已就绪', local: '本机', network: '网络', watching: '正在监听文件。每次保存都会重新构建并刷新浏览器(按 Ctrl+C 停止)。',
|
|
25
|
+
rebuilt: '{ms} 毫秒内完成重新构建', failed: '构建失败。请修复上面的错误;浏览器中也会显示。', badPort: '--port 接受 1 到 65535 之间的数字。',
|
|
26
|
+
inUse: '端口 {port} 已被占用。请停止另一个服务器,或运行 aliens run --port <端口>。',
|
|
27
|
+
denied: '此系统不允许在没有管理员权限的情况下打开端口 {port}。请运行 aliens run --port <端口>,或在 .config 中设置 serve: port:。' }
|
|
28
|
+
};
|
|
29
|
+
const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
|
|
30
|
+
|
|
31
|
+
const types = {
|
|
32
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
|
|
33
|
+
'.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
34
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
|
|
35
|
+
'.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
|
|
36
|
+
'.txt': 'text/plain; charset=utf-8', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wasm': 'application/wasm'
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// The page listens to /__aliens/events: "reload" after a good build, "build-error" with the message after a failed one.
|
|
40
|
+
const client = `<script>(() => {
|
|
41
|
+
const events = new EventSource('/__aliens/events');
|
|
42
|
+
let box;
|
|
43
|
+
events.addEventListener('reload', () => location.reload());
|
|
44
|
+
events.addEventListener('build-error', event => {
|
|
45
|
+
if (!event.data) return;
|
|
46
|
+
box ??= document.body.appendChild(Object.assign(document.createElement('pre'), { id: 'aliens-build-error' }));
|
|
47
|
+
box.style.cssText = 'position:fixed;inset:auto 16px 16px 16px;z-index:2147483647;max-height:60vh;overflow:auto;margin:0;padding:16px 18px;' +
|
|
48
|
+
'border:1px solid #f87171;border-radius:10px;background:#1f1416;color:#fecaca;font:13px/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere';
|
|
49
|
+
box.textContent = event.data;
|
|
50
|
+
});
|
|
51
|
+
})();</script>`;
|
|
52
|
+
|
|
53
|
+
function addresses(port) {
|
|
54
|
+
const found = Object.values(networkInterfaces()).flat().filter(entry => entry && entry.family === 'IPv4' && !entry.internal);
|
|
55
|
+
return found.map(entry => `http://${entry.address}:${port}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function serve(args) {
|
|
59
|
+
const { flags } = parseFlags(args, { values: ['port'], aliases: { p: 'port' } });
|
|
60
|
+
const root = requireProject();
|
|
61
|
+
const configured = readConfig(root).serve?.port;
|
|
62
|
+
const port = Number(flags.port ?? configured ?? defaultPort);
|
|
63
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError(t('badPort'));
|
|
64
|
+
const output = join(root, 'dist');
|
|
65
|
+
const clients = new Set();
|
|
66
|
+
let lastError = '';
|
|
67
|
+
const send = (event, data = '') => {
|
|
68
|
+
const payload = `event: ${event}\ndata: ${data.split('\n').join('\ndata: ')}\n\n`;
|
|
69
|
+
for (const response of clients) response.write(payload);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const server = createServer(async (request, response) => {
|
|
73
|
+
const path = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
|
|
74
|
+
if (path === '/__aliens/events') {
|
|
75
|
+
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
|
76
|
+
response.write(lastError ? `event: build-error\ndata: ${lastError.split('\n').join('\ndata: ')}\n\n` : ': connected\n\n');
|
|
77
|
+
clients.add(response);
|
|
78
|
+
request.on('close', () => clients.delete(response));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
// Paths without an extension open index.html, so a route reloads on its own address.
|
|
82
|
+
let file = normalize(join(output, path.endsWith('/') || !extname(path) ? 'index.html' : path));
|
|
83
|
+
if (relative(output, file).startsWith('..')) file = join(output, 'index.html');
|
|
84
|
+
try {
|
|
85
|
+
if (!(await stat(file)).isFile()) throw new Error('not a file');
|
|
86
|
+
let body = await readFile(file);
|
|
87
|
+
if (file.endsWith('.html')) body = body.toString('utf8').replace('</body>', `${client}\n</body>`);
|
|
88
|
+
response.writeHead(200, { 'Content-Type': types[extname(file).toLowerCase()] ?? 'application/octet-stream', 'Cache-Control': 'no-store' });
|
|
89
|
+
response.end(body);
|
|
90
|
+
} catch {
|
|
91
|
+
// Before the first good build there is no index.html: an empty page still shows the error and reloads.
|
|
92
|
+
const page = file.endsWith('index.html');
|
|
93
|
+
response.writeHead(page ? 200 : 404, { 'Content-Type': page ? types['.html'] : 'text/plain; charset=utf-8' });
|
|
94
|
+
response.end(page ? `<!doctype html><meta charset="utf-8"><title>Aliens</title><body>${client}</body>` : '404');
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const firstBuild = await runBuild(root, { quiet: true, onError: message => { lastError = message; } });
|
|
99
|
+
if (firstBuild) console.error(red(t('failed')));
|
|
100
|
+
|
|
101
|
+
// The server listens on every interface, so the Network address opens the site on other devices.
|
|
102
|
+
await new Promise((resolvePromise, reject) => {
|
|
103
|
+
server.once('error', error => reject(error.code === 'EADDRINUSE' ? new CliError(t('inUse', { port }))
|
|
104
|
+
: error.code === 'EACCES' ? new CliError(t('denied', { port })) : error));
|
|
105
|
+
server.listen(port, resolvePromise);
|
|
106
|
+
});
|
|
107
|
+
console.log(`\n ${green('▲')} ${bold(t('ready'))}\n`);
|
|
108
|
+
console.log(` ${t('local').padEnd(9)}${cyan(`http://localhost:${port}`)}`);
|
|
109
|
+
for (const address of addresses(port)) console.log(` ${t('network').padEnd(9)}${dim(address)}`);
|
|
110
|
+
console.log(`\n ${dim(t('watching'))}\n`);
|
|
111
|
+
|
|
112
|
+
// The build writes dist/ and the .map itself, so those changes never start another build.
|
|
113
|
+
const ignored = new Set(['dist', 'node_modules', '.git', '.DS_Store']);
|
|
114
|
+
const skip = file => file.split(sep).some(part => ignored.has(part)) || file.endsWith('.map');
|
|
115
|
+
let running = false;
|
|
116
|
+
let pending = false;
|
|
117
|
+
let timer;
|
|
118
|
+
async function rebuild() {
|
|
119
|
+
if (running) {
|
|
120
|
+
pending = true;
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
running = true;
|
|
124
|
+
const started = Date.now();
|
|
125
|
+
lastError = '';
|
|
126
|
+
const code = await runBuild(root, { quiet: true, onError: message => { lastError = message; } });
|
|
127
|
+
if (code) {
|
|
128
|
+
console.error(red(t('failed')));
|
|
129
|
+
send('build-error', lastError);
|
|
130
|
+
} else {
|
|
131
|
+
console.log(`${green('✓')} ${t('rebuilt', { ms: Date.now() - started })}`);
|
|
132
|
+
send('reload');
|
|
133
|
+
}
|
|
134
|
+
running = false;
|
|
135
|
+
if (pending) {
|
|
136
|
+
pending = false;
|
|
137
|
+
rebuild();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
watch(root, { recursive: true }, (event, file) => {
|
|
141
|
+
if (!file || skip(file)) return;
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
timer = setTimeout(rebuild, 120);
|
|
144
|
+
});
|
|
145
|
+
// Keep the process alive until Ctrl+C; close the event streams so the browser does not wait on them.
|
|
146
|
+
process.on('SIGINT', () => {
|
|
147
|
+
for (const response of clients) response.end();
|
|
148
|
+
server.close();
|
|
149
|
+
process.exit(0);
|
|
150
|
+
});
|
|
151
|
+
await new Promise(() => {});
|
|
152
|
+
}
|
|
@@ -9,3 +9,4 @@ Rule Architecture
|
|
|
9
9
|
# Keep the .markup, .logic, .style, and .test files of an Element together in its folder.
|
|
10
10
|
# Use .style for element stylesheets and the global layers declared in project/styles/main.style.
|
|
11
11
|
# In .style, write plain CSS as property: value. Utility class names, like flex gap-4 md:flex-row, need npm install @aliens-syndicate/style and style: from: @aliens-syndicate/style in .config.
|
|
12
|
+
# Ready-made Elements, like ui-button and ui-card, need npm install @aliens-syndicate/elements and elements: from: @aliens-syndicate/elements in .config; ai/.map then lists them.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Skill CreateElement
|
|
2
2
|
# Create an Element in project/app/elements/<level>/<name>/, where level is atoms, molecules, organisms, or templates.
|
|
3
|
+
# Start with aliens g element <level>/<name>: it writes the four files with their declarations and keeps any file that already exists.
|
|
3
4
|
# Name every file after its folder: <name>.markup renders, <name>.logic behaves, <name>.style styles, <name>.test lists checks.
|
|
4
5
|
# Start each file with its declaration, like Markup ProductCard for product-card.markup.
|
|
5
6
|
# Prefix every id and variant with the Element name, like product-card-title.
|
|
6
|
-
# Run node tools/build.mjs and fix each error by file and line.
|
|
7
|
+
# Run aliens build (or node tools/build.mjs) and fix each error by file and line.
|
package/tools/update.mjs
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// aliens update: brings the project's @aliens-syndicate packages to their latest versions and its tools/ to the CLI's.
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { cp, readdir, readFile } from 'node:fs/promises';
|
|
4
|
+
import { join, relative } from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
bold, cliPackage, cliRoot, installedVersion, cliVersion, compareVersions, cyan, dim, green, latestVersion, parseFlags, pick,
|
|
7
|
+
projectToolDirectories, projectToolFiles, red, requireProject, runCommand, yellow, CliError
|
|
8
|
+
} from './cli-shared.mjs';
|
|
9
|
+
|
|
10
|
+
const text = {
|
|
11
|
+
en: { tools: 'Project tools', packages: 'Packages', update: 'UPDATE', same: 'tools/ already matches the CLI {version}.',
|
|
12
|
+
self: 'This is the framework repository: its tools/ is the CLI itself.', none: 'No @aliens-syndicate package to update.',
|
|
13
|
+
current: '{name} {version} is the latest', newer: '{name} {from} → {to}', local: '{name} comes from {spec} and is not updated from npm',
|
|
14
|
+
offline: 'Could not reach npm to check {name}.', unpublished: '{name} is not published on npm.', installing: 'Running npm install…', installFailed: 'npm install failed. Fix the error above and run aliens update again.',
|
|
15
|
+
dryRun: 'Dry run: nothing was changed. Run aliens update to apply.', done: 'Project updated.', cliNewer: 'Aliens CLI {latest} is available (you have {version}): npm install -g {package}@latest' },
|
|
16
|
+
pt: { tools: 'Ferramentas do projeto', packages: 'Pacotes', update: 'ATUALIZADO', same: 'tools/ já está igual ao da CLI {version}.',
|
|
17
|
+
self: 'Este é o repositório do framework: o tools/ dele é a própria CLI.', none: 'Nenhum pacote @aliens-syndicate para atualizar.',
|
|
18
|
+
current: '{name} {version} é a mais recente', newer: '{name} {from} → {to}', local: '{name} vem de {spec} e não é atualizado pelo npm',
|
|
19
|
+
offline: 'Não foi possível consultar o npm para {name}.', unpublished: '{name} não está publicado no npm.', installing: 'Rodando npm install…', installFailed: 'O npm install falhou. Corrija o erro acima e rode aliens update de novo.',
|
|
20
|
+
dryRun: 'Simulação: nada foi alterado. Rode aliens update para aplicar.', done: 'Projeto atualizado.', cliNewer: 'A Aliens CLI {latest} está disponível (você tem a {version}): npm install -g {package}@latest' },
|
|
21
|
+
es: { tools: 'Herramientas del proyecto', packages: 'Paquetes', update: 'ACTUALIZADO', same: 'tools/ ya coincide con la CLI {version}.',
|
|
22
|
+
self: 'Este es el repositorio del framework: su tools/ es la propia CLI.', none: 'Ningún paquete @aliens-syndicate para actualizar.',
|
|
23
|
+
current: '{name} {version} es la más reciente', newer: '{name} {from} → {to}', local: '{name} viene de {spec} y no se actualiza desde npm',
|
|
24
|
+
offline: 'No se pudo consultar npm para {name}.', unpublished: '{name} no está publicado en npm.', installing: 'Ejecutando npm install…', installFailed: 'npm install falló. Corrige el error de arriba y ejecuta aliens update otra vez.',
|
|
25
|
+
dryRun: 'Simulación: no se cambió nada. Ejecuta aliens update para aplicar.', done: 'Proyecto actualizado.', cliNewer: 'La Aliens CLI {latest} está disponible (tienes la {version}): npm install -g {package}@latest' },
|
|
26
|
+
zh: { tools: '项目工具', packages: '依赖包', update: '已更新', same: 'tools/ 已与 CLI {version} 一致。',
|
|
27
|
+
self: '这是框架仓库:它的 tools/ 就是 CLI 本身。', none: '没有需要更新的 @aliens-syndicate 包。',
|
|
28
|
+
current: '{name} {version} 已是最新', newer: '{name} {from} → {to}', local: '{name} 来自 {spec},不会从 npm 更新',
|
|
29
|
+
offline: '无法连接 npm 检查 {name}。', unpublished: '{name} 尚未发布到 npm。', installing: '正在运行 npm install…', installFailed: 'npm install 失败。请修复上面的错误后再次运行 aliens update。',
|
|
30
|
+
dryRun: '试运行:没有做任何更改。运行 aliens update 以应用。', done: '项目已更新。', cliNewer: 'Aliens CLI {latest} 已发布(当前为 {version}):npm install -g {package}@latest' }
|
|
31
|
+
};
|
|
32
|
+
const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
|
|
33
|
+
|
|
34
|
+
async function filesUnder(directory) {
|
|
35
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
36
|
+
const files = await Promise.all(entries.map(entry => entry.isDirectory() ? filesUnder(join(directory, entry.name)) : [join(directory, entry.name)]));
|
|
37
|
+
return files.flat();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The tool files of the project that are missing or differ from the CLI's, as paths relative to the project.
|
|
41
|
+
export async function toolsDifferences(root) {
|
|
42
|
+
const source = join(cliRoot, 'tools');
|
|
43
|
+
const files = [...projectToolFiles.map(file => join(source, file)),
|
|
44
|
+
...(await Promise.all(projectToolDirectories.map(directory => filesUnder(join(source, directory))))).flat()];
|
|
45
|
+
const changed = [];
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
const target = join(root, 'tools', relative(source, file));
|
|
48
|
+
if (!existsSync(target) || !(await readFile(file)).equals(await readFile(target))) changed.push(relative(root, target));
|
|
49
|
+
}
|
|
50
|
+
return changed;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
export async function update(args) {
|
|
55
|
+
const { flags } = parseFlags(args, { booleans: ['dry-run'] });
|
|
56
|
+
const dryRun = Boolean(flags['dry-run']);
|
|
57
|
+
const root = requireProject();
|
|
58
|
+
|
|
59
|
+
console.log(bold(t('tools')));
|
|
60
|
+
if (root === cliRoot) console.log(dim(t('self')));
|
|
61
|
+
else {
|
|
62
|
+
const changed = await toolsDifferences(root);
|
|
63
|
+
for (const file of changed) {
|
|
64
|
+
console.log(`${green(t('update').padEnd(11))}${file}`);
|
|
65
|
+
if (!dryRun) await cp(join(cliRoot, 'tools', relative(join(root, 'tools'), join(root, file))), join(root, file));
|
|
66
|
+
}
|
|
67
|
+
if (!changed.length) console.log(dim(t('same', { version: cliVersion })));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
console.log('\n' + bold(t('packages')));
|
|
71
|
+
const manifestPath = join(root, 'package.json');
|
|
72
|
+
const manifest = existsSync(manifestPath) ? JSON.parse(await readFile(manifestPath, 'utf8')) : {};
|
|
73
|
+
const wanted = { dependencies: [], devDependencies: [] };
|
|
74
|
+
for (const group of Object.keys(wanted)) {
|
|
75
|
+
for (const [name, spec] of Object.entries(manifest[group] ?? {})) {
|
|
76
|
+
if (!name.startsWith('@aliens-syndicate/')) continue;
|
|
77
|
+
if (/^(file|link|git|github|http|https):|^\.{0,2}\//.test(spec)) {
|
|
78
|
+
console.log(dim(t('local', { name, spec })));
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const latest = await latestVersion(name);
|
|
82
|
+
const installed = installedVersion(root, name);
|
|
83
|
+
if (latest === false) console.log(yellow(t('unpublished', { name })));
|
|
84
|
+
else if (!latest) console.log(yellow(t('offline', { name })));
|
|
85
|
+
else if (installed && compareVersions(installed, latest) >= 0) console.log(dim(t('current', { name, version: installed })));
|
|
86
|
+
else {
|
|
87
|
+
console.log(`${green(t('update').padEnd(11))}${t('newer', { name, from: installed ?? spec, to: cyan(latest) })}`);
|
|
88
|
+
wanted[group].push(`${name}@${latest}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const toInstall = wanted.dependencies.length + wanted.devDependencies.length;
|
|
93
|
+
if (!toInstall && !Object.keys({ ...manifest.dependencies, ...manifest.devDependencies }).some(name => name.startsWith('@aliens-syndicate/'))) {
|
|
94
|
+
console.log(dim(t('none')));
|
|
95
|
+
}
|
|
96
|
+
if (toInstall && !dryRun) {
|
|
97
|
+
console.log(dim(t('installing')));
|
|
98
|
+
for (const [group, packages] of Object.entries(wanted)) {
|
|
99
|
+
if (!packages.length) continue;
|
|
100
|
+
const code = await runCommand('npm', ['install', ...(group === 'devDependencies' ? ['--save-dev'] : []), ...packages], { cwd: root });
|
|
101
|
+
if (code) throw new CliError(red(t('installFailed')));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const latestCli = await latestVersion(cliPackage);
|
|
106
|
+
if (latestCli && compareVersions(cliVersion, latestCli) < 0) {
|
|
107
|
+
console.log('\n' + yellow(t('cliNewer', { latest: latestCli, version: cliVersion, package: cliPackage })));
|
|
108
|
+
}
|
|
109
|
+
console.log('\n' + (dryRun ? dim(t('dryRun')) : green(t('done'))));
|
|
110
|
+
}
|