@aliens-syndicate/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/package.json +31 -4
  4. package/tools/build.mjs +607 -0
  5. package/tools/cli.mjs +39 -0
  6. package/tools/create.mjs +102 -0
  7. package/tools/project-layout.mjs +41 -0
  8. package/tools/runtime.mjs +294 -0
  9. package/tools/starter/app/animations/hero-enter.animation +8 -0
  10. package/tools/starter/app/apis/hero.api +9 -0
  11. package/tools/starter/app/directives/hero-highlight.directive +8 -0
  12. package/tools/starter/app/elements/atoms/kit-nav-link/kit-nav-link.markup +2 -0
  13. package/tools/starter/app/elements/molecules/hero-card/hero-card.logic +15 -0
  14. package/tools/starter/app/elements/molecules/hero-card/hero-card.markup +8 -0
  15. package/tools/starter/app/elements/molecules/hero-card/hero-card.style +12 -0
  16. package/tools/starter/app/elements/molecules/hero-card/hero-card.test +8 -0
  17. package/tools/starter/app/elements/molecules/kit-button-demo/kit-button-demo.logic +14 -0
  18. package/tools/starter/app/elements/molecules/kit-button-demo/kit-button-demo.markup +8 -0
  19. package/tools/starter/app/elements/molecules/kit-card-link/kit-card-link.markup +6 -0
  20. package/tools/starter/app/elements/organisms/kit-navigation/kit-navigation.markup +19 -0
  21. package/tools/starter/app/enums/hero-status.enum +7 -0
  22. package/tools/starter/app/errors/hero-not-found.error +7 -0
  23. package/tools/starter/app/guards/hero-editor.guard +8 -0
  24. package/tools/starter/app/interceptors/hero-request.interceptor +8 -0
  25. package/tools/starter/app/interfaces/hero.interface +8 -0
  26. package/tools/starter/app/mocks/hero.mock +8 -0
  27. package/tools/starter/app/models/hero.model +8 -0
  28. package/tools/starter/app/pages/kit-border/kit-border.markup +38 -0
  29. package/tools/starter/app/pages/kit-color/kit-color.markup +58 -0
  30. package/tools/starter/app/pages/kit-components/kit-components.markup +95 -0
  31. package/tools/starter/app/pages/kit-overview/kit-overview.markup +25 -0
  32. package/tools/starter/app/pages/kit-radius/kit-radius.markup +34 -0
  33. package/tools/starter/app/pages/kit-space/kit-space.markup +61 -0
  34. package/tools/starter/app/pages/kit-type/kit-type.markup +48 -0
  35. package/tools/starter/app/pages/style-guide/style-guide.markup +10 -0
  36. package/tools/starter/app/pages/style-guide/style-guide.style +252 -0
  37. package/tools/starter/app/pipes/hero-label.pipe +6 -0
  38. package/tools/starter/app/routes/hero-archive.route +8 -0
  39. package/tools/starter/app/routes/hero-detail.route +11 -0
  40. package/tools/starter/app/routes/hero-edit.route +14 -0
  41. package/tools/starter/app/routes/hero-filter.route +14 -0
  42. package/tools/starter/app/routes/hero-list.route +9 -0
  43. package/tools/starter/app/routes/hero-not-found.route +7 -0
  44. package/tools/starter/app/routes/hero-preview.route +11 -0
  45. package/tools/starter/app/routes/hero-redirect.route +8 -0
  46. package/tools/starter/app/routes/hero-search.route +15 -0
  47. package/tools/starter/app/routes/hero-tabs.route +17 -0
  48. package/tools/starter/app/routes/hero-team.route +11 -0
  49. package/tools/starter/app/services/hero-roster.service +8 -0
  50. package/tools/starter/app/storage/hero-favorite.storage +8 -0
  51. package/tools/starter/app/validators/hero-energy.validator +8 -0
  52. package/tools/starter/language/.en-US +73 -0
  53. package/tools/starter/language/.es-ES +73 -0
  54. package/tools/starter/language/.pt-BR +73 -0
  55. package/tools/starter/language/.zh-CN +73 -0
  56. package/tools/starter/styles/components/alerts.style +16 -0
  57. package/tools/starter/styles/components/badges.style +18 -0
  58. package/tools/starter/styles/components/borders.style +11 -0
  59. package/tools/starter/styles/components/buttons.style +34 -0
  60. package/tools/starter/styles/components/cards.style +9 -0
  61. package/tools/starter/styles/components/feedback.style +21 -0
  62. package/tools/starter/styles/components/forms.style +38 -0
  63. package/tools/starter/styles/components/spacing.style +13 -0
  64. package/tools/starter/styles/components/tables.style +17 -0
  65. package/tools/starter/styles/components/typography.style +51 -0
  66. package/tools/starter/styles/generic/ui-base.style +12 -0
  67. package/tools/starter/styles/objects/ui-layout.style +13 -0
  68. package/tools/starter/styles/settings/border-tokens.style +9 -0
  69. package/tools/starter/styles/settings/color-tokens.style +40 -0
  70. package/tools/starter/styles/settings/elevation-tokens.style +8 -0
  71. package/tools/starter/styles/settings/radius-tokens.style +8 -0
  72. package/tools/starter/styles/settings/space-tokens.style +11 -0
  73. package/tools/starter/styles/settings/theme.style +52 -0
  74. package/tools/starter/styles/settings/type-tokens.style +18 -0
  75. package/tools/vscode-space/extension.cjs +56 -0
  76. package/tools/vscode-space/language-configuration.json +9 -0
  77. package/tools/vscode-space/package.json +129 -0
  78. package/tools/vscode-space/space.tmLanguage.json +32 -0
  79. package/tools/vscode-space/style-colors.cjs +69 -0
  80. package/tools/vscode-space/syntax.cjs +122 -0
  81. package/tools/vscode-space/vendor/color-name.LICENSE +8 -0
  82. package/tools/vscode-space/vendor/color-name.cjs +152 -0
@@ -0,0 +1,607 @@
1
+ import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { basename, dirname, extname, join, relative, resolve } from 'node:path';
3
+ import { stripTypeScriptTypes } from 'node:module';
4
+ import { exampleMarker, namedKinds, sharedDirectory } from './project-layout.mjs';
5
+ import spaceSyntax from './vscode-space/syntax.cjs';
6
+
7
+ const { analyzeSpace, isSpaceComment } = spaceSyntax;
8
+
9
+ const workspace = resolve(import.meta.dirname, '..');
10
+ const rootConfig = await readFile(join(workspace, '.config'), 'utf8').catch(error => {
11
+ if (error.code === 'ENOENT') return undefined;
12
+ throw error;
13
+ });
14
+ const root = rootConfig === undefined ? join(workspace, 'project') : workspace;
15
+ const read = file => readFile(join(root, file), 'utf8');
16
+ const indentation = ' ';
17
+ async function filesIn(directory, { optional = false } = {}) {
18
+ let entries;
19
+ try {
20
+ entries = await readdir(join(root, directory), { withFileTypes: true });
21
+ } catch (error) {
22
+ if (optional && error.code === 'ENOENT') return [];
23
+ throw error;
24
+ }
25
+ const files = await Promise.all(entries.map(entry => {
26
+ const path = join(directory, entry.name);
27
+ return entry.isDirectory() ? filesIn(path) : entry.isFile() ? [path] : [];
28
+ }));
29
+ return files.flat().sort();
30
+ }
31
+
32
+ function sourceLines(source, file, { css = false } = {}) {
33
+ return source.split(/\r?\n/).flatMap((line, index) => {
34
+ const value = line.trim();
35
+ const indent = line.length - line.trimStart().length;
36
+ const location = `${file}:${index + 1}`;
37
+ if (indent % indentation.length || !/^ *$/.test(line.slice(0, indent))) {
38
+ throw new Error(`${location}: Space requires three spaces per level and no tabs.`);
39
+ }
40
+ if (line !== line.trimEnd()) throw new Error(`${location}: remove trailing whitespace.`);
41
+ if (!value || isSpaceComment(value, css)) return [];
42
+ return [{ level: indent / indentation.length, value, location }];
43
+ });
44
+ }
45
+
46
+ function tree(source, file, options) {
47
+ const nodes = [];
48
+ const parents = [{ children: nodes }];
49
+ for (const line of sourceLines(source, file, options)) {
50
+ const parent = parents[line.level];
51
+ if (!parent) throw new Error(`${line.location}: skipped indentation level.`);
52
+ const node = { ...line, children: [] };
53
+ parent.children.push(node);
54
+ parents.splice(line.level + 1, parents.length, node);
55
+ }
56
+ return nodes;
57
+ }
58
+
59
+ function declaration(source, file, allowExample) {
60
+ const extension = extname(file);
61
+ const kind = extension.slice(1);
62
+ if (kind !== kind.toLowerCase()) throw new Error(`${file}: use a lowercase Space extension.`);
63
+ const stem = basename(file, extension);
64
+ if (!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(stem)) {
65
+ throw new Error(`${file}: use a lowercase file name with dots or hyphens between words.`);
66
+ }
67
+ const name = stem.split(/[.-]/).map(word => word[0].toUpperCase() + word.slice(1)).join('');
68
+ const type = kind[0].toUpperCase() + kind.slice(1);
69
+ let nodes = tree(source, file, { css: kind === 'style' });
70
+ const lines = source.split(/\r?\n/);
71
+ const example = allowExample && nodes.length === 0 && lines[0] === exampleMarker;
72
+ if (example) {
73
+ const divider = lines.indexOf('#');
74
+ if (divider < 1) throw new Error(`${file}: place a standalone # before the example code.`);
75
+ const content = lines.map((line, index) => index <= divider ? '' : line.replace(/^#(?: |$)/, '')).join('\n');
76
+ nodes = tree(content, file, { css: kind === 'style' });
77
+ }
78
+ const header = nodes[0];
79
+ if (nodes.length !== 1 || header.value !== `${type} ${name}`) {
80
+ throw new Error(`${header?.location ?? file}: expected one Space declaration headed "${type} ${name}".`);
81
+ }
82
+ return example ? null : { name: type + name, children: header.children };
83
+ }
84
+
85
+ const escape = value => String(value).replace(/[&<>"']/g, character =>
86
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
87
+
88
+ function highlightSpace(source, file) {
89
+ const { tokens } = analyzeSpace(source, extname(file));
90
+ let index = 0;
91
+ return source.split(/\r\n|\n|\r/).map((line, lineIndex) => {
92
+ let start = 0;
93
+ let output = '';
94
+ while (tokens[index]?.line === lineIndex) {
95
+ const token = tokens[index++];
96
+ output += escape(line.slice(start, token.start));
97
+ start = token.start + token.length;
98
+ output += `<span class="space-${token.role}">${escape(line.slice(token.start, start))}</span>`;
99
+ }
100
+ return output + escape(line.slice(start));
101
+ }).join('\n');
102
+ }
103
+
104
+ const pair = /^([\w.-]+):\s*(.*)$/;
105
+
106
+ const config = tree(rootConfig ?? await read('.config'), '.config');
107
+ const settings = name => Object.fromEntries(config.find(node => node.value === name + ':')?.children.map(node => {
108
+ const [, key, value] = pair.exec(node.value);
109
+ return [key, value];
110
+ }) ?? []);
111
+ const { entry, assets: assetDirectory, shared: configuredShared, styles, agent: map, environment } = settings('files');
112
+ const { default: defaultLocale, detection, directory: languageDirectory } = settings('language');
113
+ const appDirectory = dirname(entry);
114
+ const shared = configuredShared ?? join(dirname(appDirectory), sharedDirectory);
115
+ const styleDirectory = dirname(styles);
116
+ const agentDirectory = dirname(map);
117
+ const markupEntry = entry.replace(/\.logic$/, '.markup');
118
+ const [appFiles, assetFiles, globalStyles, agentFiles, languageFiles, sharedFiles] = await Promise.all([
119
+ ...[appDirectory, assetDirectory, styleDirectory, agentDirectory, languageDirectory].map(directory => filesIn(directory)),
120
+ filesIn(shared, { optional: true })
121
+ ]);
122
+ const projectFiles = [...appFiles, ...sharedFiles, ...globalStyles, ...agentFiles];
123
+ const namedFiles = projectFiles.filter(file => namedKinds.has(extname(file).slice(1).toLowerCase()));
124
+ const unsupported = projectFiles.find(file => /\.(styles|mockup)$/i.test(file));
125
+ if (unsupported) throw new Error(`${unsupported}: use the registered Space extensions .style and .mock.`);
126
+ const sources = new Map(await Promise.all([...namedFiles, ...languageFiles, environment].map(async file => [file, await read(file)])));
127
+ const declarations = new Map();
128
+ for (const file of namedFiles) {
129
+ const model = declaration(sources.get(file), file, file.startsWith(appDirectory + '/') || file.startsWith(shared + '/'));
130
+ if (model) declarations.set(file, model);
131
+ }
132
+ sourceLines(sources.get(environment), environment);
133
+ // An Element is the set of files that share a name in one folder. No file is required: .markup renders, .logic
134
+ // behaves and .style provides styles. A .logic without .markup runs on its own; a .style without .markup provides
135
+ // variants named after its Element to any markup.
136
+ const elements = new Map();
137
+ const elementFiles = new Map();
138
+ const componentDirectories = [join(appDirectory, 'pages'), join(appDirectory, 'elements'), join(shared, 'elements')];
139
+ for (const file of declarations.keys()) {
140
+ const kind = extname(file).slice(1);
141
+ if (!['markup', 'logic', 'style'].includes(kind) || !componentDirectories.some(directory => file.startsWith(directory + '/'))) continue;
142
+ const name = basename(file, '.' + kind);
143
+ const entry = elementFiles.get(name) ?? { directory: dirname(file) };
144
+ if (entry[kind] || entry.directory !== dirname(file)) throw new Error(`Duplicate Element name: ${name}.`);
145
+ entry[kind] = file;
146
+ elementFiles.set(name, entry);
147
+ if (kind === 'markup') elements.set(name, file);
148
+ }
149
+ const styleProviders = new Set([...elementFiles].filter(([, files]) => files.style && !files.markup).map(([name]) => name));
150
+ const standaloneLogic = new Set([...elementFiles].filter(([, files]) => files.logic && !files.markup).map(([name]) => name));
151
+ const languages = Object.fromEntries(languageFiles.filter(file => /^\.[a-z]{2}-[A-Z]{2}$/.test(basename(file))).map(file => {
152
+ const translated = Object.create(null);
153
+ function visit(nodes, prefix = '') {
154
+ for (const node of nodes) {
155
+ const match = pair.exec(node.value);
156
+ if (!match) throw new Error(`${node.location}: invalid translation entry.`);
157
+ const [, key, value] = match;
158
+ if (value && !node.children.length) {
159
+ if (Object.hasOwn(translated, prefix + key)) throw new Error(`${node.location}: duplicate translation.`);
160
+ translated[prefix + key] = value;
161
+ } else if (!value && node.children.length) visit(node.children, prefix + key + '.');
162
+ else throw new Error(`${node.location}: expected text or a translation group.`);
163
+ }
164
+ }
165
+ visit(tree(sources.get(file), file));
166
+ return [basename(file).slice(1), translated];
167
+ }));
168
+ if (!languages[defaultLocale]) throw new Error(`Missing default language: ${defaultLocale}`);
169
+ const reference = Object.keys(languages[defaultLocale]).sort().join('\n');
170
+ for (const [language, dictionary] of Object.entries(languages)) {
171
+ if (Object.keys(dictionary).sort().join('\n') !== reference) {
172
+ throw new Error(`${language} must declare the same translation keys as ${defaultLocale}.`);
173
+ }
174
+ }
175
+
176
+ const voidTags = new Set(['img', 'input', 'hr', 'br']);
177
+ function resolveValue(value, props, location) {
178
+ if (!value.startsWith('{')) return value;
179
+ const field = value.slice(1, -1);
180
+ if (!field.startsWith('$')) return field;
181
+ const name = field.slice(1);
182
+ if (!Object.hasOwn(props, name)) throw new Error(`${location}: missing Element property ${name}.`);
183
+ return props[name];
184
+ }
185
+
186
+ function translation(value, location) {
187
+ if (!value.startsWith('@')) return null;
188
+ const key = value.slice(1);
189
+ if (!Object.hasOwn(languages[defaultLocale], key)) throw new Error(`${location}: missing translation ${key}.`);
190
+ return key;
191
+ }
192
+
193
+ function parseNode(node) {
194
+ const head = /^([a-z][\w-]*)(?:=(\{[^}]*\}))?(.*)$/.exec(node.value);
195
+ if (!head) throw new Error(`${node.location}: invalid markup.`);
196
+ const [, tag, inline, attrs] = head;
197
+ const attributes = [];
198
+ const attribute = /\s+([\w:-]+)(?:=("(?:[^"]*)"|\{[^}]*\}))?/y;
199
+ let offset = 0;
200
+ while (offset < attrs.length) {
201
+ attribute.lastIndex = offset;
202
+ const match = attribute.exec(attrs);
203
+ if (!match) throw new Error(`${node.location}: invalid attribute near "${attrs.slice(offset)}".`);
204
+ const [, key, raw] = match;
205
+ if (attributes.some(([name]) => name === key)) throw new Error(`${node.location}: duplicate attribute ${key}.`);
206
+ attributes.push([key, raw]);
207
+ offset = attribute.lastIndex;
208
+ }
209
+ return { tag, inline, attributes };
210
+ }
211
+
212
+ // Native tags accept the same short properties as Elements: variant, action, label and text.
213
+ const shorthands = { variant: 'class', action: 'data-action', label: 'aria-label' };
214
+ const nativeLabels = new Set(['option', 'optgroup', 'track']);
215
+ function expandShorthands(tag, attributes, location) {
216
+ if (typeof attributes.variant === 'string') attributes.variant = variantClasses(attributes.variant, attributes.id).join(' ');
217
+ for (const [key, target] of Object.entries(shorthands)) {
218
+ if (!Object.hasOwn(attributes, key) || (key === 'label' && nativeLabels.has(tag))) continue;
219
+ const value = attributes[key];
220
+ delete attributes[key];
221
+ if (Object.hasOwn(attributes, target)) throw new Error(`${location}: use either ${key} or ${target}.`);
222
+ else attributes[target] = value;
223
+ }
224
+ if (tag === 'button' && !Object.hasOwn(attributes, 'type')) attributes.type = 'button';
225
+ }
226
+
227
+ // The markup names every tag that .style and .logic reach: id names one tag, variant names a style shared by several.
228
+ // Every name follows element-child_modifier:state, in lowercase: "-" before each child, "_" before the modifier and ":"
229
+ // before the state, which stays a CSS pseudo-class in .style (site-header-logo_large:hover). The Element is matched by
230
+ // name, so site-header-logo belongs to site-header. A .style selector writes the name without a prefix; the build turns
231
+ // ids into [id="name"] and variants into .name, so both weigh the same in the cascade.
232
+ const nameGrammar = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:_[a-z0-9]+(?:-[a-z0-9]+)*)?$/;
233
+ const libraryElement = 'space';
234
+ const ownedBy = (name, owner) => name === owner || name.startsWith(owner + '-') || name.startsWith(owner + '_');
235
+ const baseOf = name => name.includes('_') ? name.slice(0, name.indexOf('_')) : null;
236
+ // A modifier brings its base along: variant="counter-button_increase" renders class="counter-button counter-button_increase".
237
+ function variantClasses(value, id) {
238
+ const classes = [];
239
+ for (const token of value.split(/\s+/).filter(Boolean)) {
240
+ const base = baseOf(token);
241
+ if (base && base !== id && !classes.includes(base)) classes.push(base);
242
+ if (!classes.includes(token)) classes.push(token);
243
+ }
244
+ return classes;
245
+ }
246
+ const htmlTags = new Set(('a abbr address article aside audio b blockquote body br button canvas caption cite code col ' +
247
+ 'colgroup data datalist dd del details dfn dialog div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 ' +
248
+ 'head header hgroup hr html i iframe img input ins kbd label legend li link main mark menu meter nav noscript object ol ' +
249
+ 'optgroup option output p picture pre progress q rp rt ruby s samp search section select slot small source span strong ' +
250
+ 'sub summary sup svg table tbody td template textarea tfoot th thead time tr track u ul var video wbr').split(' '));
251
+ for (const [name, files] of elementFiles) {
252
+ if (htmlTags.has(name)) throw new Error(`${files.markup ?? files.logic ?? files.style}: an Element can't take the name of the HTML tag ${name}.`);
253
+ }
254
+ const highlightRoles = ['action', 'comment', 'control', 'reactive', 'return', 'type', 'value'];
255
+ const logicAttributes = new Set(['data-bind', 'data-show', 'data-pressed', 'data-expanded', 'data-state', 'data-theme-control', 'data-language']);
256
+ const names = new Map();
257
+ function addName(name, kind, location) {
258
+ if (!nameGrammar.test(name)) throw new Error(`${location}: "${name}" must follow element-child_modifier in lowercase, like counter-button_increase.`);
259
+ if (htmlTags.has(name)) throw new Error(`${location}: "${name}" is an HTML tag; choose another ${kind} name.`);
260
+ const known = names.get(name);
261
+ if (known && known.kind !== kind) {
262
+ throw new Error(`${location}: "${name}" is already ${known.kind === 'id' ? 'an id' : 'a variant'} at ${known.location}.`);
263
+ }
264
+ if (!known) names.set(name, { kind, location });
265
+ }
266
+ function addVariant(token, id, location) {
267
+ const base = baseOf(token);
268
+ if (base && base !== id) addName(base, 'variant', location);
269
+ addName(token, 'variant', location);
270
+ }
271
+ for (const role of highlightRoles) addName(`space-${role}`, 'variant', 'Space highlighter');
272
+ for (const [file, { children }] of declarations) {
273
+ if (!file.endsWith('.markup')) continue;
274
+ (function visit(nodes) {
275
+ for (const node of nodes) {
276
+ for (const [key, raw] of parseNode(node).attributes) {
277
+ if (key === 'class') throw new Error(`${node.location}: Space has no class attribute; name the tag with id or share a style with variant.`);
278
+ if (logicAttributes.has(key)) {
279
+ throw new Error(`${node.location}: give the tag an id and declare ${key.slice(5)} under bind: in the .logic.`);
280
+ }
281
+ if (!raw?.startsWith('"')) continue;
282
+ const value = raw.slice(1, -1);
283
+ if (key === 'id') addName(value, 'id', node.location);
284
+ }
285
+ const attributes = Object.fromEntries(parseNode(node).attributes.filter(([, raw]) => raw?.startsWith('"')).map(([key, raw]) => [key, raw.slice(1, -1)]));
286
+ for (const token of (attributes.variant ?? '').split(/\s+/).filter(Boolean)) addVariant(token, attributes.id, node.location);
287
+ visit(node.children);
288
+ }
289
+ })(children);
290
+ }
291
+
292
+ const selectorToken = /"[^"]*"|'[^']*'|\[[^\]]*\]|:(?:nth-[\w-]+|lang|dir)\([^)]*\)|([.#])(-?[A-Za-z_][\w-]*)|::?-?[A-Za-z_][\w-]*|(-?[A-Za-z_][\w-]*)|[\s\S]/g;
293
+ // Global styles declare the library's space- variants and a style-only Element declares variants named after itself;
294
+ // any other style only uses names that a markup declares.
295
+ function compileSelector(selector, location, declares) {
296
+ return selector.replace(selectorToken, (token, prefix, prefixed, bare) => {
297
+ if (prefix) throw new Error(`${location}: write ${prefixed} without "${prefix}"; the markup id or variant names the tag.`);
298
+ if (!bare) return token;
299
+ const known = names.get(bare);
300
+ if (known) return known.kind === 'id' ? `[id="${bare}"]` : `.${bare}`;
301
+ if (htmlTags.has(bare)) return token;
302
+ if (declares) {
303
+ if (!ownedBy(bare, declares)) {
304
+ throw new Error(`${location}: ${declares === libraryElement ? 'library names' : 'names in this style'} start with ${declares}, like ${declares}-item_large.`);
305
+ }
306
+ addName(bare, 'variant', location);
307
+ return `.${bare}`;
308
+ }
309
+ throw new Error(`${location}: "${bare}" is not an id or variant in the markup, nor an HTML tag.`);
310
+ });
311
+ }
312
+
313
+ const renderedIds = new Map();
314
+ const renderedElements = new Set();
315
+ const usedProviders = new Set();
316
+ const actionCalls = [];
317
+ const logicIds = new Map();
318
+ const dependencies = new Map();
319
+ function render(file, props = {}, ancestry = [], parentScope = null) {
320
+ if (!sources.has(file)) throw new Error(`Missing markup: ${file}`);
321
+ if (ancestry.includes(file)) throw new Error(`Circular Element reference: ${[...ancestry, file].join(' → ')}`);
322
+ const nodes = declarations.get(file).children;
323
+ if (nodes.length !== 1) throw new Error(`${file}: expected a single root inside the declaration.`);
324
+ const name = file.split('/').at(-1).slice(0, -7);
325
+ renderedElements.add(name);
326
+ const ancestors = ancestry.map(path => path.split('/').at(-1).slice(0, -7));
327
+ // A name belongs to the Element that writes it, to an Element that renders it, to a style-only Element or to the library.
328
+ const owners = new Set([name, libraryElement, ...styleProviders, ...ancestors]);
329
+ const checkOwner = (value, location) => {
330
+ const owner = [...owners].find(candidate => ownedBy(value, candidate));
331
+ if (!owner) throw new Error(`${location}: "${value}" must start with ${name}, an Element that renders it, a style-only Element or ${libraryElement}.`);
332
+ if (styleProviders.has(owner)) usedProviders.add(owner);
333
+ };
334
+ // Actions resolve like the runtime: the nearest Element with .logic that declares them, from this tag upwards.
335
+ const actionOwners = [name, ...ancestors.reverse()].filter(element => elementFiles.get(element)?.logic);
336
+ const rootBinding = declarations.has(file.replace(/\.markup$/, '.logic')) ? name : null;
337
+ if (rootBinding && !logicIds.has(name)) logicIds.set(name, new Set());
338
+ const scope = rootBinding ? logicIds.get(name) : parentScope;
339
+ function renderNode(node, isRoot = false) {
340
+ const { tag, inline, attributes: parsed } = parseNode(node);
341
+ const attributes = Object.create(null);
342
+ for (const [key, raw] of parsed) {
343
+ attributes[key] = raw?.startsWith('"') ? raw.slice(1, -1) : raw ? resolveValue(raw, props, node.location) : true;
344
+ }
345
+ if (elements.has(tag)) {
346
+ if (inline || node.children.length) throw new Error(`${node.location}: Element references accept properties.`);
347
+ if (!dependencies.has(file)) dependencies.set(file, new Set());
348
+ dependencies.get(file).add(tag);
349
+ return render(elements.get(tag), attributes, [...ancestry, file], scope);
350
+ }
351
+ if (elementFiles.has(tag)) {
352
+ throw new Error(`${node.location}: ${tag} has no .markup to render; ${styleProviders.has(tag) ? `use variant="${tag}"` : `call it with action="${tag}.<action>"`}.`);
353
+ }
354
+ if (!htmlTags.has(tag)) throw new Error(`${node.location}: "${tag}" is neither an HTML tag nor an Element.`);
355
+ if (typeof attributes.id === 'string') {
356
+ checkOwner(attributes.id, node.location);
357
+ addName(attributes.id, 'id', node.location);
358
+ if (renderedIds.has(attributes.id)) {
359
+ throw new Error(`${node.location}: id "${attributes.id}" is already on the page at ${renderedIds.get(attributes.id)}; use variant for shared styles.`);
360
+ }
361
+ renderedIds.set(attributes.id, node.location);
362
+ scope?.add(attributes.id);
363
+ }
364
+ if (typeof attributes.variant === 'string') {
365
+ for (const token of attributes.variant.split(/\s+/).filter(Boolean)) {
366
+ checkOwner(token, node.location);
367
+ addVariant(token, attributes.id, node.location);
368
+ }
369
+ }
370
+ expandShorthands(tag, attributes, node.location);
371
+ if (typeof attributes['data-action'] === 'string') {
372
+ actionCalls.push({ action: attributes['data-action'], owners: actionOwners, location: node.location });
373
+ }
374
+ if (isRoot && rootBinding) attributes['data-element'] = rootBinding;
375
+ let text = inline ? resolveValue(inline, props, node.location) : '';
376
+ if (Object.hasOwn(attributes, 'text')) {
377
+ if (inline) throw new Error(`${node.location}: use either inline text or text.`);
378
+ text = String(attributes.text);
379
+ delete attributes.text;
380
+ }
381
+ const source = attributes['data-source'];
382
+ if (source !== undefined) {
383
+ if (tag !== 'code' || inline || node.children.length || !sources.has(source) ||
384
+ !declarations.has(source)) throw new Error(`${node.location}: invalid source reference.`);
385
+ delete attributes['data-source'];
386
+ text = sources.get(source).trimEnd();
387
+ }
388
+ let markup = '<' + tag;
389
+ for (const [key, value] of Object.entries(attributes)) {
390
+ const label = typeof value === 'string' && translation(value, node.location);
391
+ if (label) markup += ` data-i18n-${key}="${escape(label)}"`;
392
+ markup += value === true ? ` ${key}` : ` ${key}="${escape(label ? languages[defaultLocale][label] : value)}"`;
393
+ }
394
+ const label = source === undefined && translation(text, node.location);
395
+ if (label && node.children.length) throw new Error(`${node.location}: place translated text in its own node.`);
396
+ if (label) markup += ` data-i18n="${escape(label)}"`;
397
+ markup += '>';
398
+ if (voidTags.has(tag)) return markup;
399
+ const children = node.children.map(child => renderNode(child)).join('');
400
+ const content = source === undefined ? escape(label ? languages[defaultLocale][label] : text) : highlightSpace(text, source);
401
+ return markup + content + children + '</' + tag + '>';
402
+ }
403
+ return renderNode(nodes[0], true);
404
+ }
405
+
406
+ function compileStyles(nodes, declares) {
407
+ return nodes.map(node => {
408
+ const scope = node.value.startsWith('@media ');
409
+ const selector = node.value.startsWith('@') ? node.value : compileSelector(node.value, node.location, declares);
410
+ const css = scope ? compileStyles(node.children, declares) : node.children.map(declaration => {
411
+ if (!/^[-\w]+:\s*\S/.test(declaration.value) || declaration.children.length) {
412
+ throw new Error(`${declaration.location}: expected a CSS declaration.`);
413
+ }
414
+ return ' ' + declaration.value + ';';
415
+ }).join('\n');
416
+ return `${selector} {\n${css}\n}`;
417
+ }).join('\n\n');
418
+ }
419
+
420
+ const bindKinds = new Set(['text', 'show', 'pressed', 'expanded']);
421
+ const kebab = name => name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
422
+ function compileLogic(file) {
423
+ const { name, children } = declarations.get(file);
424
+ const element = basename(file, '.logic');
425
+ const binds = [];
426
+ const page = {};
427
+ const fieldNames = [];
428
+ const actionNames = [];
429
+ const members = [];
430
+ for (const member of children) {
431
+ if (member.value === 'import:' && member.children.length === 1 && member.children[0].value === 'signal: aliens/core') continue;
432
+ const field = /^signal ([A-Za-z]\w*): (string|number|boolean) = (.+)$/.exec(member.value);
433
+ if (field && !member.children.length) {
434
+ fieldNames.push(field[1]);
435
+ members.push(`${field[1]}: ${field[2]} = ${field[3]};`);
436
+ continue;
437
+ }
438
+ if (member.value === 'page:') {
439
+ for (const entry of member.children) {
440
+ const match = /^(theme|locale): ([A-Za-z]\w*)$/.exec(entry.value);
441
+ if (!match || entry.children.length || page[match[1]]) {
442
+ throw new Error(`${entry.location}: page: accepts theme: <signal> and locale: <signal> once each.`);
443
+ }
444
+ page[match[1]] = match[2];
445
+ }
446
+ continue;
447
+ }
448
+ if (member.value === 'bind:') {
449
+ for (const target of member.children) {
450
+ const id = /^([^\s:]+):$/.exec(target.value)?.[1];
451
+ if (!id || !nameGrammar.test(id) || id.includes('_') || !target.children.length) throw new Error(`${target.location}: bind: lists tag ids followed by ":".`);
452
+ for (const entry of target.children) {
453
+ const match = /^(_?[a-z0-9-]+): (.+)$/.exec(entry.value);
454
+ if (!match || !(bindKinds.has(match[1]) || /^_[a-z0-9]+(?:-[a-z0-9]+)*$/.test(match[1])) || entry.children.length) {
455
+ throw new Error(`${entry.location}: bind: accepts ${[...bindKinds].join(', ')} and _modifier.`);
456
+ }
457
+ if (match[1].startsWith('_')) addName(id + match[1], 'variant', entry.location);
458
+ if (binds.some(bind => bind.id === id && bind.kind === match[1])) throw new Error(`${entry.location}: duplicate ${match[1]} for ${id}.`);
459
+ try { new Function(`return (${match[2]});`); } catch { throw new Error(`${entry.location}: invalid expression.`); }
460
+ binds.push({ id, kind: match[1], expression: match[2], location: entry.location });
461
+ }
462
+ }
463
+ continue;
464
+ }
465
+ if (member.value !== 'actions:') throw new Error(`${member.location}: unsupported logic in the Web preview.`);
466
+ for (const action of member.children) {
467
+ const actionName = /^([A-Za-z]\w*):$/.exec(action.value)?.[1];
468
+ const returns = action.children.find(node => node.value.startsWith('returns: '));
469
+ const body = action.children.find(node => node.value === 'body:' || node.value === 'body: |');
470
+ if (!actionName || actionName === 'constructor' || returns?.value !== 'returns: void' ||
471
+ !body?.children.length || action.children.length !== 2) {
472
+ throw new Error(`${action.location}: the Web preview supports actions without parameters that return void.`);
473
+ }
474
+ const lines = sources.get(file).split(/\r?\n/);
475
+ const from = Number(body.location.split(':').at(-1));
476
+ let until = from;
477
+ const indent = (body.level + 1) * indentation.length;
478
+ while (until < lines.length && (!lines[until].trim() || lines[until].startsWith(' '.repeat(indent)))) until++;
479
+ actionNames.push(actionName);
480
+ members.push(`${actionName}(): void {\n${lines.slice(from, until).map(line => line.slice(indent)).join('\n')}\n}`);
481
+ }
482
+ }
483
+ if (new Set([...fieldNames, ...actionNames]).size !== fieldNames.length + actionNames.length) {
484
+ throw new Error(`${file}: duplicate class member.`);
485
+ }
486
+ for (const [key, field] of Object.entries(page)) {
487
+ if (!fieldNames.includes(field)) throw new Error(`${file}: page: ${key} names the missing signal ${field}.`);
488
+ }
489
+ const standalone = standaloneLogic.has(element);
490
+ if (standalone && binds.length) throw new Error(`${binds[0].location}: bind: needs tags; ${element} has no .markup.`);
491
+ const ids = logicIds.get(element);
492
+ if (ids) {
493
+ for (const bind of binds) {
494
+ if (!ids.has(bind.id)) throw new Error(`${bind.location}: id "${bind.id}" is not a tag of ${element}.`);
495
+ }
496
+ // An id named "<element>-<signal>" shows that signal without a bind: entry.
497
+ for (const field of fieldNames) {
498
+ const id = `${element}-${kebab(field)}`;
499
+ if (ids.has(id) && !binds.some(bind => bind.id === id && bind.kind === 'text')) {
500
+ binds.push({ id, kind: 'text', expression: `this.${field}` });
501
+ }
502
+ }
503
+ }
504
+ const implementation = stripTypeScriptTypes(`class ${name} {\n${members.join('\n')}\n}`);
505
+ const compiledBinds = binds.map(({ id, kind, expression }) =>
506
+ `[${JSON.stringify(id)}, ${JSON.stringify(kind)}, function () { return (${expression}); }]`).join(', ');
507
+ const source = `{ create(element) { ${implementation}; return new ${name}(); }, actions: ${JSON.stringify(actionNames)}, ` +
508
+ `bind: [${compiledBinds}], page: ${JSON.stringify(page)}, standalone: ${standalone} }`;
509
+ return { source, actions: actionNames, page, standalone };
510
+ }
511
+
512
+ const manifest = declarations.get(styles).children;
513
+ const stylesheetFiles = manifest.flatMap(section => {
514
+ const entries = section.children.map(node => node.value);
515
+ if (section.value === 'default:') return entries.flatMap(folder => globalStyles
516
+ .filter(file => file.startsWith(join(styleDirectory, folder) + '/') && file.endsWith('.style')));
517
+ if (section.value === 'import:') return entries.map(file => join(styleDirectory, file));
518
+ throw new Error(`${section.location}: unsupported stylesheet manifest entry.`);
519
+ });
520
+ stylesheetFiles.push(...[...sharedFiles, ...appFiles].filter(file => file.endsWith('.style') && declarations.has(file)));
521
+ const themeFile = join(styleDirectory, 'settings', 'theme.style');
522
+ const themeNames = new Set(['light', 'dark']);
523
+ if (stylesheetFiles.includes(themeFile)) {
524
+ for (const { value } of declarations.get(themeFile).children) {
525
+ for (const match of value.matchAll(/:root\[data-theme="([a-z][a-z0-9-]*)"\]/g)) themeNames.add(match[1]);
526
+ }
527
+ }
528
+ const html = render(markupEntry);
529
+ const logic = new Map();
530
+ for (const file of [...appFiles, ...sharedFiles].filter(file => file.endsWith('.logic') && declarations.has(file))) {
531
+ const name = basename(file, '.logic');
532
+ if (logic.has(name)) throw new Error(`Duplicate Logic name: ${name}.`);
533
+ logic.set(name, compileLogic(file));
534
+ }
535
+ // Validation by need: every action a rendered tag calls must exist. "element.action" reaches a .logic without .markup.
536
+ const usedStandalone = new Set();
537
+ for (const { action, owners, location } of actionCalls) {
538
+ const qualified = /^([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\.([A-Za-z]\w*)$/.exec(action);
539
+ if (qualified) {
540
+ const [, element, method] = qualified;
541
+ if (!standaloneLogic.has(element)) throw new Error(`${location}: "${element}" is not an Element with .logic and no .markup.`);
542
+ if (!logic.get(element).actions.includes(method)) throw new Error(`${location}: ${element}.logic has no action ${method}.`);
543
+ usedStandalone.add(element);
544
+ } else if (!owners.some(element => logic.get(element)?.actions.includes(action))) {
545
+ throw new Error(`${location}: no .logic for this tag or the Elements around it declares the action ${action}.`);
546
+ }
547
+ }
548
+ // Selective compilation: everything is validated above, but the output keeps only what the page uses.
549
+ const usedLogic = [...logic].filter(([name, entry]) => logicIds.has(name) || usedStandalone.has(name) ||
550
+ (entry.standalone && Object.keys(entry.page).length));
551
+ const elementOfFile = file => componentDirectories.some(directory => file.startsWith(directory + '/')) ? basename(file, '.style') : null;
552
+ const compiledStyles = stylesheetFiles.map(file => {
553
+ const element = elementOfFile(file);
554
+ const declares = globalStyles.includes(file) ? libraryElement : styleProviders.has(element) ? element : null;
555
+ return { file, element, css: compileStyles(declarations.get(file).children, declares) };
556
+ });
557
+ const css = compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element))
558
+ .map(entry => entry.css).join('\n\n');
559
+ const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
560
+ const runtime = await readFile(join(import.meta.dirname, 'runtime.mjs'), 'utf8');
561
+ const output = join(workspace, 'dist');
562
+ const favicon = assetFiles.includes(join(assetDirectory, 'mark.png')) ? '\n <link rel="icon" href="./assets/mark.png">' : '';
563
+ await mkdir(output, { recursive: true });
564
+ await Promise.all([
565
+ cp(join(root, assetDirectory), join(output, 'assets'), { recursive: true }),
566
+ writeFile(join(output, 'main.css'), css + '\n'),
567
+ writeFile(join(output, 'app.js'), `const logic = { ${compiledLogic} };
568
+ const languages = ${JSON.stringify(languages)};
569
+ const availableThemes = ${JSON.stringify([...themeNames])};
570
+ const defaultLocale = ${JSON.stringify(defaultLocale)};
571
+ const detectLocale = ${detection === 'browser'};
572
+ ${runtime}`),
573
+ writeFile(join(output, 'index.html'), `<!doctype html>
574
+ <html lang="${defaultLocale}">
575
+ <head>
576
+ <meta charset="utf-8">
577
+ <meta name="viewport" content="width=device-width, initial-scale=1">
578
+ <meta name="theme-color" content="#ffffff">
579
+ <meta name="description" content="${escape(languages[defaultLocale]['home.description'])}">
580
+ <title>${escape(languages[defaultLocale]['site.title'])}</title>
581
+ <meta property="og:type" content="website">
582
+ <meta property="og:title" content="${escape(languages[defaultLocale]['site.title'])}">
583
+ <meta property="og:description" content="${escape(languages[defaultLocale]['home.description'])}">
584
+ <meta name="twitter:card" content="summary">${favicon}
585
+ <link rel="stylesheet" href="./main.css">
586
+ <script defer src="./app.js"></script>
587
+ </head>
588
+ <body>${html}</body>
589
+ </html>\n`)
590
+ ]);
591
+ const configurationRoot = root === workspace ? 'the workspace root' : 'project/';
592
+ await writeFile(join(root, map), `# Generated by the Aliens Web preview. Paths are relative to ${configurationRoot}.
593
+ entrypoints:
594
+ config: .config
595
+ app: ${entry}
596
+ assets: ${assetDirectory}
597
+ styles: ${styles}
598
+ architecture:
599
+ ${[[appDirectory, appFiles], [assetDirectory, assetFiles], [shared, sharedFiles], [styleDirectory, globalStyles], [languageDirectory, languageFiles], [agentDirectory, agentFiles.filter(file => file !== map)]]
600
+ .filter(([directory, files]) => directory !== shared || files.length > 0)
601
+ .map(([directory, files]) => [`${indentation}${directory}:`, ...files.map(file => indentation.repeat(2) + relative(directory, file))].join('\n')).join('\n')}
602
+ dependencies:
603
+ ${[...dependencies].map(([file, uses]) => `${indentation}${file}:\n${[...uses].map(name => indentation.repeat(2) + name).join('\n')}`).join('\n')}
604
+ validation:
605
+ web_preview: passed
606
+ `);
607
+ console.log(`Aliens Web preview generated in ${output}`);
package/tools/cli.mjs ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Entry point of the @aliens-syndicate/cli package: aliens create <folder> | aliens build | aliens --version.
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { 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
+ const help = `Aliens ${version}
10
+
11
+ Uso:
12
+ aliens create <pasta> Cria um projeto Aliens na pasta indicada.
13
+ aliens build Gera a prévia em dist/ a partir da pasta atual.
14
+ aliens --version Mostra a versão do CLI.
15
+ `;
16
+
17
+ // Each script reads its own arguments, so the CLI hands them over through process.argv.
18
+ async function run(script, scriptArgs) {
19
+ process.argv = [process.argv[0], script, ...scriptArgs];
20
+ await import(pathToFileURL(script).href);
21
+ }
22
+
23
+ if (command === 'create') {
24
+ await run(join(import.meta.dirname, 'create.mjs'), args);
25
+ } else if (command === 'build') {
26
+ // A project carries its own tools/, so the build always matches the project's version.
27
+ const script = join(process.cwd(), 'tools', 'build.mjs');
28
+ if (!existsSync(script)) {
29
+ console.error('Nenhum projeto Aliens nesta pasta: tools/build.mjs não foi encontrado.');
30
+ process.exitCode = 1;
31
+ } else {
32
+ await run(script, args);
33
+ }
34
+ } else if (command === '--version' || command === '-v') {
35
+ console.log(version);
36
+ } else {
37
+ console.log(help);
38
+ if (command && command !== 'help' && command !== '--help' && command !== '-h') process.exitCode = 1;
39
+ }