@aliens-syndicate/cli 0.1.1 → 0.1.3

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 (29) hide show
  1. package/README.md +122 -93
  2. package/package.json +6 -2
  3. package/tools/build.mjs +326 -26
  4. package/tools/cli.mjs +31 -9
  5. package/tools/create.mjs +38 -12
  6. package/tools/icon-docs.mjs +132 -0
  7. package/tools/runtime.mjs +216 -8
  8. package/tools/starter/ai/agents/codingbot.agent +5 -0
  9. package/tools/starter/ai/rules/architecture.rule +11 -0
  10. package/tools/starter/ai/skills/create-element.skill +6 -0
  11. package/tools/starter/app/elements/molecules/kit-card-link/kit-card-link.markup +0 -2
  12. package/tools/starter/app/pages/kit-overview/kit-overview.markup +6 -6
  13. package/tools/starter/app/pages/style-guide/style-guide.style +57 -57
  14. package/tools/starter/styles/components/alerts.style +6 -5
  15. package/tools/starter/styles/components/badges.style +6 -5
  16. package/tools/starter/styles/components/borders.style +2 -1
  17. package/tools/starter/styles/components/buttons.style +14 -13
  18. package/tools/starter/styles/components/cards.style +1 -1
  19. package/tools/starter/styles/components/feedback.style +3 -2
  20. package/tools/starter/styles/components/forms.style +5 -4
  21. package/tools/starter/styles/components/tables.style +4 -3
  22. package/tools/starter/styles/components/typography.style +6 -5
  23. package/tools/starter/styles/generic/ui-base.style +1 -1
  24. package/tools/starter/styles/objects/ui-layout.style +1 -1
  25. package/tools/style-docs.mjs +274 -0
  26. package/tools/vscode-space/package.json +5 -8
  27. package/tools/vscode-space/space.tmLanguage.json +1 -1
  28. package/tools/vscode-space/syntax.cjs +103 -62
  29. package/tools/watch.mjs +48 -0
package/tools/build.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { basename, dirname, extname, join, relative, resolve } from 'node:path';
3
- import { stripTypeScriptTypes } from 'node:module';
3
+ import { createRequire, stripTypeScriptTypes } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
4
5
  import { exampleMarker, namedKinds, sharedDirectory } from './project-layout.mjs';
5
6
  import spaceSyntax from './vscode-space/syntax.cjs';
6
7
 
7
- const { analyzeSpace, isSpaceComment } = spaceSyntax;
8
+ const { analyzeSpace, htmlTags, isSpaceComment, roles: highlightRoleOf } = spaceSyntax;
8
9
 
9
10
  const workspace = resolve(import.meta.dirname, '..');
10
11
  const rootConfig = await readFile(join(workspace, '.config'), 'utf8').catch(error => {
@@ -110,6 +111,89 @@ const settings = name => Object.fromEntries(config.find(node => node.value === n
110
111
  }) ?? []);
111
112
  const { entry, assets: assetDirectory, shared: configuredShared, styles, agent: map, environment } = settings('files');
112
113
  const { default: defaultLocale, detection, directory: languageDirectory } = settings('language');
114
+ const { from: iconPackage, style: configuredIconStyle } = settings('icons');
115
+ const { from: stylePackage } = settings('style');
116
+ // Extensions are separate packages that the project installs and declares in .config under <section>: from:, or a
117
+ // local folder written as ./path. Icons (usually @aliens-syndicate/icons) let markup draw the icon tag inline (see
118
+ // renderIcon); style (usually @aliens-syndicate/style) lets .style list utilities besides plain CSS declarations.
119
+ async function loadExtension(section, name) {
120
+ let entry;
121
+ try {
122
+ entry = /^\.{1,2}\//.test(name) ? join(workspace, name, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(name);
123
+ } catch {
124
+ throw new Error(`.config: ${section}: from: ${name} is not installed. Run npm install ${name}.`);
125
+ }
126
+ return import(pathToFileURL(entry).href);
127
+ }
128
+ const iconModule = iconPackage ? await loadExtension('icons', iconPackage) : null;
129
+ const styleModule = stylePackage ? await loadExtension('style', stylePackage) : null;
130
+ if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`.config: style: from: ${stylePackage} is not an Aliens style extension.`);
131
+ const noStyle = (where, what) => new Error(`${where}: ${what} need the style extension. Write CSS as "property: value", or run ` +
132
+ 'npm install @aliens-syndicate/style and declare it in .config:\nstyle:\n from: @aliens-syndicate/style');
133
+ // Without the style extension, .style reads plain CSS declarations only.
134
+ const resolveUtility = (token, options) => styleModule ? styleModule.resolveUtility(token, options) : { error: 'no style extension' };
135
+ const iconRenderer = iconModule?.createIconRenderer();
136
+ const iconCatalog = iconModule ? await iconModule.readCatalog() : null;
137
+ const iconStyle = iconRenderer ? configuredIconStyle ?? 'stroke-rounded' : null;
138
+ if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`.config: icons: style: accepts ${iconRenderer.styles.join(', ')}.`);
139
+ const noIcons = where => new Error(`${where}: icons need a package. Run npm install @aliens-syndicate/icons and declare it in .config:\n` +
140
+ 'icons:\n from: @aliens-syndicate/icons\n style: stroke-rounded');
141
+ // The icon tag: "icon <name> [style] [size-<n>] [color] [second color] [disabled] [hidden]", with id, variant and label
142
+ // as its only attributes. The first word names the icon and the others may come in any order: one of the ten styles
143
+ // (the one in .config by default), a size utility, up to two colors (the icon and the second tone of bulk, duotone and
144
+ // twotone), disabled and hidden. Without label the icon is decorative and hidden from assistive technology.
145
+ const iconTag = /^icon(?=\s|$)/;
146
+ function iconParts(node) {
147
+ const rest = node.value.slice('icon'.length);
148
+ const attributes = [];
149
+ const words = [];
150
+ const part = /\s+(?:([\w:-]+)=("[^"]*"|\{[^}]*\})|(\{[^}]*\})|([^\s"{}=]+))/y;
151
+ for (let offset = 0; offset < rest.length;) {
152
+ part.lastIndex = offset;
153
+ const match = part.exec(rest);
154
+ if (!match) throw new Error(`${node.location}: invalid icon near "${rest.slice(offset).trim()}".`);
155
+ if (match[1]) attributes.push([match[1], match[2]]);
156
+ else words.push(match[3] ?? match[4]);
157
+ offset = part.lastIndex;
158
+ }
159
+ for (const [key] of attributes) {
160
+ if (!['id', 'variant', 'label'].includes(key)) throw new Error(`${node.location}: icon accepts id, variant and label; write the rest as words.`);
161
+ }
162
+ return { attributes, words };
163
+ }
164
+ let iconCount = 0;
165
+ const decorative = ' class="space-icon" aria-hidden="true" focusable="false"';
166
+ function inlineIcon(name, style, id, { tone, attributes = decorative, css = '' } = {}) {
167
+ return iconRenderer.svg(iconCatalog.icons[name], style, { id, tone })
168
+ .replace(/^<svg xmlns='http:\/\/www\.w3\.org\/2000\/svg'/, `<svg${attributes}${css ? ` style="${escape(css)}"` : ''}`);
169
+ }
170
+ function readIcon(words, location) {
171
+ const [name, ...rest] = words;
172
+ if (!name) throw new Error(`${location}: write the icon name after icon, like icon add-01.`);
173
+ if (!iconRenderer) throw noIcons(location);
174
+ if (!Object.hasOwn(iconCatalog.icons, name)) throw new Error(`${location}: there is no icon ${name}; the Icons page lists every name.`);
175
+ const icon = { name, style: null, size: [], colors: [], disabled: false, hidden: false };
176
+ for (const word of rest) {
177
+ if (iconRenderer.styles.includes(word)) {
178
+ if (icon.style) throw new Error(`${location}: the icon has two styles, ${icon.style} and ${word}.`);
179
+ icon.style = word;
180
+ } else if (word === 'disabled') icon.disabled = true;
181
+ else if (word === 'hidden') icon.hidden = true;
182
+ else if (!styleModule) throw noStyle(location, `"${word}" is a utility; icon sizes and colors`);
183
+ else if (word.startsWith('size-')) {
184
+ const utility = resolveUtility(word, { colors: themeColors });
185
+ if (utility.error || utility.variants.length) throw new Error(`${location}: ${utility.error ?? `${word} takes no variant`}.`);
186
+ icon.size = utility.declarations;
187
+ } else {
188
+ const utility = resolveUtility(`text-${word}`, { colors: themeColors });
189
+ const color = !utility.error && !utility.variants.length && utility.declarations.length === 1 && utility.declarations[0][0] === 'color';
190
+ if (!color) throw new Error(`${location}: "${word}" is not an icon style, a size-<n>, a color, disabled or hidden.`);
191
+ if (icon.colors.length === 2) throw new Error(`${location}: an icon takes up to two colors.`);
192
+ icon.colors.push(utility.declarations[0][1]);
193
+ }
194
+ }
195
+ return icon;
196
+ }
113
197
  const appDirectory = dirname(entry);
114
198
  const shared = configuredShared ?? join(dirname(appDirectory), sharedDirectory);
115
199
  const styleDirectory = dirname(styles);
@@ -130,6 +214,19 @@ for (const file of namedFiles) {
130
214
  if (model) declarations.set(file, model);
131
215
  }
132
216
  sourceLines(sources.get(environment), environment);
217
+ // A comment that starts with #AGENT is a directive for AI agents only: the build copies it to the .map, with file
218
+ // and line, and leaves it out of the generated code.
219
+ const agentDirective = /^#\s*AGENT\b:?\s*(.*)$/;
220
+ const directives = new Map();
221
+ for (const file of [...namedFiles, environment]) {
222
+ const found = sources.get(file).split(/\r?\n/).flatMap((line, index) => {
223
+ const match = agentDirective.exec(line.trim());
224
+ if (!match) return [];
225
+ if (!match[1]) throw new Error(`${file}:${index + 1}: write the directive after #AGENT.`);
226
+ return [[index + 1, match[1]]];
227
+ });
228
+ if (found.length) directives.set(file, found);
229
+ }
133
230
  // An Element is the set of files that share a name in one folder. No file is required: .markup renders, .logic
134
231
  // behaves and .style provides styles. A .logic without .markup runs on its own; a .style without .markup provides
135
232
  // variants named after its Element to any markup.
@@ -179,7 +276,9 @@ function resolveValue(value, props, location) {
179
276
  const field = value.slice(1, -1);
180
277
  if (!field.startsWith('$')) return field;
181
278
  const name = field.slice(1);
182
- if (!Object.hasOwn(props, name)) throw new Error(`${location}: missing Element property ${name}.`);
279
+ if (!Object.hasOwn(props, name)) {
280
+ throw new Error(name.includes('.') ? `${location}: the list item has no field ${name.slice(name.indexOf('.') + 1)}.` : `${location}: missing Element property ${name}.`);
281
+ }
183
282
  return props[name];
184
283
  }
185
284
 
@@ -243,15 +342,46 @@ function variantClasses(value, id) {
243
342
  }
244
343
  return classes;
245
344
  }
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
345
  for (const [name, files] of elementFiles) {
252
346
  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
347
  }
254
- const highlightRoles = ['action', 'comment', 'control', 'reactive', 'return', 'type', 'value'];
348
+ // list <name>: in a .logic declares a fixed list. Each item has a name, and that name is its identity: the build writes it
349
+ // as data-key on the first tag of the item, so no track expression is needed. Markup repeats a block with
350
+ // "for <item> in <list>" and reads the fields as {$item.field}, plus {$item.key} and {$item.index}.
351
+ const listPattern = /^list ([a-z][A-Za-z0-9]*):$/;
352
+ const forPattern = /^for ([a-z][A-Za-z0-9]*) in ([a-z][A-Za-z0-9]*)$/;
353
+ const listCache = new Map();
354
+ function listsOf(file) {
355
+ if (listCache.has(file)) return listCache.get(file);
356
+ const lists = new Map();
357
+ for (const member of declarations.get(file).children) {
358
+ const name = listPattern.exec(member.value)?.[1];
359
+ if (!name) continue;
360
+ if (lists.has(name)) throw new Error(`${member.location}: duplicate list ${name}.`);
361
+ if (!member.children.length) throw new Error(`${member.location}: list ${name} has no items.`);
362
+ const keys = new Set();
363
+ const items = member.children.map((item, index) => {
364
+ const key = /^([a-z][a-z0-9]*(?:-[a-z0-9]+)*):$/.exec(item.value)?.[1];
365
+ if (!key || !item.children.length) throw new Error(`${item.location}: name each list item, like agent:, and write its fields below it.`);
366
+ if (keys.has(key)) throw new Error(`${item.location}: duplicate item ${key}; the item name is its identity.`);
367
+ keys.add(key);
368
+ const fields = { key, index: String(index) };
369
+ for (const field of item.children) {
370
+ const match = pair.exec(field.value);
371
+ if (!match || !match[2] || field.children.length) throw new Error(`${field.location}: write each field as name: value.`);
372
+ if (Object.hasOwn(fields, match[1])) {
373
+ throw new Error(`${field.location}: ${['key', 'index'].includes(match[1]) ? `${match[1]} is built in` : `duplicate field ${match[1]}`}.`);
374
+ }
375
+ fields[match[1]] = match[2].replace(/^"(.*)"$/, '$1');
376
+ }
377
+ return fields;
378
+ });
379
+ lists.set(name, items);
380
+ }
381
+ listCache.set(file, lists);
382
+ return lists;
383
+ }
384
+ const highlightRoles = [...new Set(Object.values(highlightRoleOf))].sort();
255
385
  const logicAttributes = new Set(['data-bind', 'data-show', 'data-pressed', 'data-expanded', 'data-state', 'data-theme-control', 'data-language']);
256
386
  const names = new Map();
257
387
  function addName(name, kind, location) {
@@ -269,11 +399,17 @@ function addVariant(token, id, location) {
269
399
  addName(token, 'variant', location);
270
400
  }
271
401
  for (const role of highlightRoles) addName(`space-${role}`, 'variant', 'Space highlighter');
402
+ for (const name of ['space-icon', 'space-icon_disabled']) addName(name, 'variant', 'Icon tag');
272
403
  for (const [file, { children }] of declarations) {
273
404
  if (!file.endsWith('.markup')) continue;
274
405
  (function visit(nodes) {
275
406
  for (const node of nodes) {
276
- for (const [key, raw] of parseNode(node).attributes) {
407
+ if (forPattern.test(node.value)) {
408
+ visit(node.children);
409
+ continue;
410
+ }
411
+ const parts = iconTag.test(node.value) ? iconParts(node) : parseNode(node);
412
+ for (const [key, raw] of parts.attributes) {
277
413
  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
414
  if (logicAttributes.has(key)) {
279
415
  throw new Error(`${node.location}: give the tag an id and declare ${key.slice(5)} under bind: in the .logic.`);
@@ -282,7 +418,7 @@ for (const [file, { children }] of declarations) {
282
418
  const value = raw.slice(1, -1);
283
419
  if (key === 'id') addName(value, 'id', node.location);
284
420
  }
285
- const attributes = Object.fromEntries(parseNode(node).attributes.filter(([, raw]) => raw?.startsWith('"')).map(([key, raw]) => [key, raw.slice(1, -1)]));
421
+ const attributes = Object.fromEntries(parts.attributes.filter(([, raw]) => raw?.startsWith('"')).map(([key, raw]) => [key, raw.slice(1, -1)]));
286
422
  for (const token of (attributes.variant ?? '').split(/\s+/).filter(Boolean)) addVariant(token, attributes.id, node.location);
287
423
  visit(node.children);
288
424
  }
@@ -316,7 +452,7 @@ const usedProviders = new Set();
316
452
  const actionCalls = [];
317
453
  const logicIds = new Map();
318
454
  const dependencies = new Map();
319
- function render(file, props = {}, ancestry = [], parentScope = null) {
455
+ function render(file, rootProps = {}, ancestry = [], parentScope = null) {
320
456
  if (!sources.has(file)) throw new Error(`Missing markup: ${file}`);
321
457
  if (ancestry.includes(file)) throw new Error(`Circular Element reference: ${[...ancestry, file].join(' → ')}`);
322
458
  const nodes = declarations.get(file).children;
@@ -336,7 +472,62 @@ function render(file, props = {}, ancestry = [], parentScope = null) {
336
472
  const rootBinding = declarations.has(file.replace(/\.markup$/, '.logic')) ? name : null;
337
473
  if (rootBinding && !logicIds.has(name)) logicIds.set(name, new Set());
338
474
  const scope = rootBinding ? logicIds.get(name) : parentScope;
339
- function renderNode(node, isRoot = false) {
475
+ // A list comes from the .logic of this Element or of the Elements around it, nearest first.
476
+ const findList = (listName, location) => {
477
+ for (const element of [name, ...ancestors]) {
478
+ const logicFile = elementFiles.get(element)?.logic;
479
+ const list = logicFile && listsOf(logicFile).get(listName);
480
+ if (list) return list;
481
+ }
482
+ throw new Error(`${location}: no .logic of this Element or of the Elements around it declares list ${listName}.`);
483
+ };
484
+ function renderIcon(node, props) {
485
+ if (node.children.length) throw new Error(`${node.location}: icon takes no children.`);
486
+ const { attributes: parsed, words } = iconParts(node);
487
+ const values = Object.fromEntries(parsed.map(([key, raw]) => [key, raw.startsWith('"') ? raw.slice(1, -1) : resolveValue(raw, props, node.location)]));
488
+ const icon = readIcon(words.flatMap(word => String(word.startsWith('{') ? resolveValue(word, props, node.location) : word)
489
+ .split(/\s+/).filter(Boolean)), node.location);
490
+ let attributes = '';
491
+ const classes = icon.disabled ? ['space-icon', 'space-icon_disabled'] : ['space-icon'];
492
+ if (typeof values.variant === 'string') {
493
+ for (const token of values.variant.split(/\s+/).filter(Boolean)) {
494
+ checkOwner(token, node.location);
495
+ addVariant(token, values.id, node.location);
496
+ }
497
+ classes.push(...variantClasses(values.variant, values.id));
498
+ }
499
+ attributes += ` class="${escape(classes.join(' '))}"`;
500
+ if (typeof values.id === 'string') {
501
+ checkOwner(values.id, node.location);
502
+ addName(values.id, 'id', node.location);
503
+ if (renderedIds.has(values.id)) throw new Error(`${node.location}: id "${values.id}" is already on the page at ${renderedIds.get(values.id)}.`);
504
+ renderedIds.set(values.id, node.location);
505
+ scope?.add(values.id);
506
+ attributes += ` id="${escape(values.id)}"`;
507
+ }
508
+ const label = typeof values.label === 'string' ? values.label : null;
509
+ const key = label && translation(label, node.location);
510
+ attributes += label
511
+ ? ` role="img"${key ? ` data-i18n-aria-label="${escape(key)}"` : ''} aria-label="${escape(key ? languages[defaultLocale][key] : label)}"`
512
+ : ' aria-hidden="true"';
513
+ attributes += ` focusable="false"${icon.disabled ? ' aria-disabled="true"' : ''}${icon.hidden ? ' hidden' : ''}`;
514
+ const css = [...icon.size.map(([property, value]) => `${property}: ${value}`), ...(icon.colors[0] ? [`color: ${icon.colors[0]}`] : [])].join('; ');
515
+ return inlineIcon(icon.name, icon.style ?? iconStyle, `icon${++iconCount}`, { tone: icon.colors[1], attributes, css });
516
+ }
517
+ function renderNode(node, isRoot = false, props = rootProps) {
518
+ const loop = forPattern.exec(node.value);
519
+ if (loop) {
520
+ const [, item, listName] = loop;
521
+ if (isRoot) throw new Error(`${node.location}: for repeats tags inside the root; wrap it in a tag.`);
522
+ if (!node.children.length) throw new Error(`${node.location}: write the tags to repeat below for.`);
523
+ if (Object.keys(props).some(key => key.startsWith(item + '.'))) throw new Error(`${node.location}: ${item} is already a list item here.`);
524
+ return findList(listName, node.location).map(fields => {
525
+ const scoped = { ...props, ...Object.fromEntries(Object.entries(fields).map(([field, value]) => [`${item}.${field}`, value])) };
526
+ return node.children.map(child => renderNode(child, false, scoped)).join('')
527
+ .replace(/^<([a-z][\w-]*)/, `<$1 data-key="${escape(fields.key)}"`);
528
+ }).join('');
529
+ }
530
+ if (iconTag.test(node.value)) return renderIcon(node, props);
340
531
  const { tag, inline, attributes: parsed } = parseNode(node);
341
532
  const attributes = Object.create(null);
342
533
  for (const [key, raw] of parsed) {
@@ -396,25 +587,79 @@ function render(file, props = {}, ancestry = [], parentScope = null) {
396
587
  if (label) markup += ` data-i18n="${escape(label)}"`;
397
588
  markup += '>';
398
589
  if (voidTags.has(tag)) return markup;
399
- const children = node.children.map(child => renderNode(child)).join('');
590
+ const children = node.children.map(child => renderNode(child, false, props)).join('');
400
591
  const content = source === undefined ? escape(label ? languages[defaultLocale][label] : text) : highlightSpace(text, source);
401
592
  return markup + content + children + '</' + tag + '>';
402
593
  }
403
594
  return renderNode(nodes[0], true);
404
595
  }
405
596
 
597
+ // Inside a selector, "property: value" is a CSS declaration. With the style extension declared in .config (style:
598
+ // from: @aliens-syndicate/style), any other line lists utilities with the Tailwind CSS names: "flex items-center gap-4 max-md:flex-col hover:bg-surface". State variants such as
599
+ // hover: and dark: rewrite the selector; responsive variants such as md: and max-lg: become @media rules, written
600
+ // after the rest of the file from the widest max-* to the narrowest and then from the narrowest min-width up.
601
+ const declarationLine = /^-{0,2}[A-Za-z][\w-]*:\s+\S/;
602
+ const themeColors = new Set();
603
+ const usedProperties = new Set();
604
+ const usedKeyframes = new Set();
605
+ const ruleText = (selector, declarations) => `${selector} {\n${declarations.map(entry => ' ' + entry + ';').join('\n')}\n}`;
406
606
  function compileStyles(nodes, declares) {
407
- return nodes.map(node => {
408
- const scope = node.value.startsWith('@media ');
607
+ const base = [];
608
+ const states = [];
609
+ const responsive = [];
610
+ for (const node of nodes) {
611
+ if (node.value.startsWith('@media ') || node.value.startsWith('@supports ')) {
612
+ base.push(`${node.value} {\n${compileStyles(node.children, declares)}\n}`);
613
+ continue;
614
+ }
409
615
  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.`);
616
+ const plain = [];
617
+ const variantGroups = new Map();
618
+ for (const line of node.children) {
619
+ if (line.children.length) throw new Error(`${line.location}: expected a CSS declaration or a list of utilities.`);
620
+ if (declarationLine.test(line.value) || node.value.startsWith('@')) {
621
+ plain.push(line.value);
622
+ continue;
623
+ }
624
+ if (!styleModule) throw noStyle(line.location, `"${line.value}" is not a CSS declaration; utilities`);
625
+ for (const token of line.value.split(/\s+/)) {
626
+ const utility = resolveUtility(token, { colors: themeColors });
627
+ if (utility.error) {
628
+ const hint = /^[-\w]+:\S/.test(token) && !token.includes('[') && !token.includes('(')
629
+ ? ' A CSS declaration needs a space after the colon.' : ' See the Style page for the utility names.';
630
+ throw new Error(`${line.location}: ${utility.error}.${hint}`);
631
+ }
632
+ for (const property of utility.properties) usedProperties.add(property);
633
+ if (utility.keyframes) usedKeyframes.add(utility.keyframes);
634
+ const declarations = utility.declarations.map(([property, value]) => `${property}: ${value}`);
635
+ if (!utility.variants.length && !utility.child) {
636
+ plain.push(...declarations);
637
+ continue;
638
+ }
639
+ if (!variantGroups.has(utility.key)) variantGroups.set(utility.key, { utility, declarations: [] });
640
+ variantGroups.get(utility.key).declarations.push(...declarations);
413
641
  }
414
- return ' ' + declaration.value + ';';
415
- }).join('\n');
416
- return `${selector} {\n${css}\n}`;
417
- }).join('\n\n');
642
+ }
643
+ if (plain.length) base.push(ruleText(selector, plain));
644
+ for (const { utility, declarations } of variantGroups.values()) {
645
+ const selectors = styleModule.splitSelectors(selector).map(part => utility.variants
646
+ .filter(found => found.selector).reduce((current, found) => found.selector(current), part) + utility.child);
647
+ const rule = ruleText(selectors.join(', '), declarations);
648
+ const wrappers = utility.variants.filter(found => found.media || found.supports)
649
+ .map(found => found.media ? `@media ${found.media}` : `@supports ${found.supports}`);
650
+ if (!wrappers.length) states.push(rule);
651
+ else responsive.push({ wrappers, order: utility.variants.find(found => found.order).order, rule });
652
+ }
653
+ }
654
+ responsive.sort((left, right) => left.order[0] - right.order[0] || left.order[1] - right.order[1]);
655
+ const scoped = [];
656
+ for (const entry of responsive) {
657
+ const key = entry.wrappers.join(' ');
658
+ if (scoped.at(-1)?.key === key) scoped.at(-1).rules.push(entry.rule);
659
+ else scoped.push({ key, wrappers: entry.wrappers, rules: [entry.rule] });
660
+ }
661
+ const media = scoped.map(({ wrappers, rules }) => wrappers.reduceRight((inner, wrapper) => `${wrapper} {\n${inner}\n}`, rules.join('\n\n')));
662
+ return [...base, ...states, ...media].join('\n\n');
418
663
  }
419
664
 
420
665
  const bindKinds = new Set(['text', 'show', 'pressed', 'expanded']);
@@ -435,6 +680,10 @@ function compileLogic(file) {
435
680
  members.push(`${field[1]}: ${field[2]} = ${field[3]};`);
436
681
  continue;
437
682
  }
683
+ if (listPattern.test(member.value)) {
684
+ listsOf(file);
685
+ continue;
686
+ }
438
687
  if (member.value === 'page:') {
439
688
  for (const entry of member.children) {
440
689
  const match = /^(theme|locale): ([A-Za-z]\w*)$/.exec(entry.value);
@@ -525,6 +774,15 @@ if (stylesheetFiles.includes(themeFile)) {
525
774
  for (const match of value.matchAll(/:root\[data-theme="([a-z][a-z0-9-]*)"\]/g)) themeNames.add(match[1]);
526
775
  }
527
776
  }
777
+ // Every --color-<name> in the global styles becomes a color utility, like bg-<name> and text-<name>.
778
+ for (const file of globalStyles.filter(path => declarations.has(path))) {
779
+ for (const rule of declarations.get(file).children) {
780
+ for (const line of rule.children) {
781
+ const name = /^--color-([a-z][a-z0-9-]*):\s/.exec(line.value)?.[1];
782
+ if (name) themeColors.add(name);
783
+ }
784
+ }
785
+ }
528
786
  const html = render(markupEntry);
529
787
  const logic = new Map();
530
788
  for (const file of [...appFiles, ...sharedFiles].filter(file => file.endsWith('.logic') && declarations.has(file))) {
@@ -554,21 +812,61 @@ const compiledStyles = stylesheetFiles.map(file => {
554
812
  const declares = globalStyles.includes(file) ? libraryElement : styleProviders.has(element) ? element : null;
555
813
  return { file, element, css: compileStyles(declarations.get(file).children, declares) };
556
814
  });
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
815
  const runtime = await readFile(join(import.meta.dirname, 'runtime.mjs'), 'utf8');
816
+ const iconCatalogUsed = html.includes(' data-icon-catalog');
817
+ if (iconCatalogUsed && !iconRenderer) throw noIcons('The Icons page');
818
+ // Every icon tag renders an inline svg with class space-icon; space-icon_disabled marks the disabled ones.
819
+ const iconCss = iconRenderer ? `.space-icon {
820
+ display: inline-block;
821
+ width: 1em;
822
+ height: 1em;
823
+ flex-shrink: 0;
824
+ vertical-align: -0.125em;
825
+ }
826
+
827
+ .space-icon_disabled {
828
+ opacity: 0.4;
829
+ }
830
+
831
+ .space-icon[hidden] {
832
+ display: none;
833
+ }` : '';
834
+ // The site highlights Space with the colors the editor extension declares, read from its package.json, so a color
835
+ // changes in one place. Every token type of a role must share one color in each theme.
836
+ const editorPalette = JSON.parse(await readFile(join(import.meta.dirname, 'vscode-space', 'package.json'), 'utf8'))
837
+ .contributes.configurationDefaults['editor.semanticTokenColorCustomizations'];
838
+ const highlightTheme = rules => highlightRoles.map(role => {
839
+ const colors = new Set(Object.entries(highlightRoleOf).filter(([, owner]) => owner === role)
840
+ .map(([type]) => rules[`${type}:space`]).filter(Boolean));
841
+ if (colors.size !== 1) throw new Error(`tools/vscode-space/package.json: the Space types of the ${role} role need one color, found ${[...colors].join(', ') || 'none'}.`);
842
+ return ` --space-${role}: ${[...colors][0]};`;
843
+ }).join('\n');
844
+ const highlightCss = `:root {\n${highlightTheme(editorPalette['[*Light*][*light*]'].rules)}\n}\n\n` +
845
+ `:root[data-theme="dark"] {\n${highlightTheme(editorPalette.rules)}\n}`;
846
+ const highlightUsed = new RegExp(`var\\(--space-(?:${highlightRoles.join('|')})\\)`);
847
+ const css = [...[...usedProperties].sort().map(name => styleModule.propertyRule(name)), ...usedKeyframes, iconCss,
848
+ compiledStyles.some(entry => highlightUsed.test(entry.css)) ? highlightCss : '',
849
+ ...compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element)).map(entry => entry.css)]
850
+ .filter(Boolean).join('\n\n');
851
+ const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
561
852
  const output = join(workspace, 'dist');
562
853
  const favicon = assetFiles.includes(join(assetDirectory, 'mark.png')) ? '\n <link rel="icon" href="./assets/mark.png">' : '';
563
854
  await mkdir(output, { recursive: true });
564
855
  await Promise.all([
565
856
  cp(join(root, assetDirectory), join(output, 'assets'), { recursive: true }),
566
857
  writeFile(join(output, 'main.css'), css + '\n'),
858
+ // The Icons page loads the whole catalog when it opens, so other pages never download it.
859
+ ...(iconCatalogUsed ? [writeFile(join(output, 'icons.json'), JSON.stringify({ categories: iconCatalog.categories, icons: iconCatalog.icons }))] : []),
567
860
  writeFile(join(output, 'app.js'), `const logic = { ${compiledLogic} };
568
861
  const languages = ${JSON.stringify(languages)};
569
862
  const availableThemes = ${JSON.stringify([...themeNames])};
570
863
  const defaultLocale = ${JSON.stringify(defaultLocale)};
571
864
  const detectLocale = ${detection === 'browser'};
865
+ const iconStyle = ${JSON.stringify(iconStyle)};
866
+ const iconRenderer = ${iconCatalogUsed ? `(${iconModule.createIconRenderer})()` : 'null'};
867
+ const copyIcons = ${JSON.stringify(iconRenderer && iconCatalog.icons['copy-01'] && iconCatalog.icons['tick-02'] ? {
868
+ copy: inlineIcon('copy-01', iconStyle, 'copy-icon'), copied: inlineIcon('tick-02', iconStyle, 'copied-icon')
869
+ } : null)};
572
870
  ${runtime}`),
573
871
  writeFile(join(output, 'index.html'), `<!doctype html>
574
872
  <html lang="${defaultLocale}">
@@ -601,6 +899,8 @@ ${[[appDirectory, appFiles], [assetDirectory, assetFiles], [shared, sharedFiles]
601
899
  .map(([directory, files]) => [`${indentation}${directory}:`, ...files.map(file => indentation.repeat(2) + relative(directory, file))].join('\n')).join('\n')}
602
900
  dependencies:
603
901
  ${[...dependencies].map(([file, uses]) => `${indentation}${file}:\n${[...uses].map(name => indentation.repeat(2) + name).join('\n')}`).join('\n')}
902
+ directives:
903
+ ${[...directives].map(([file, found]) => `${indentation}${file}:\n${found.map(([line, text]) => `${indentation.repeat(2)}${line}: ${text}`).join('\n')}`).join('\n')}
604
904
  validation:
605
905
  web_preview: passed
606
906
  `);
package/tools/cli.mjs CHANGED
@@ -1,17 +1,39 @@
1
1
  #!/usr/bin/env node
2
- // Entry point of the @aliens-syndicate/cli package: aliens create <folder> | aliens build | aliens --version.
2
+ // Entry point of the @aliens-syndicate/cli package: aliens create <folder> | aliens build | aliens watch | aliens --version.
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
- import { join } from 'node:path';
4
+ import { basename, join } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
 
7
7
  const [command, ...args] = process.argv.slice(2);
8
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}>`;
9
30
  const help = `Aliens ${version}
10
31
 
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.
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}
15
37
  `;
16
38
 
17
39
  // Each script reads its own arguments, so the CLI hands them over through process.argv.
@@ -22,11 +44,11 @@ async function run(script, scriptArgs) {
22
44
 
23
45
  if (command === 'create') {
24
46
  await run(join(import.meta.dirname, 'create.mjs'), args);
25
- } else if (command === 'build') {
47
+ } else if (command === 'build' || command === 'watch') {
26
48
  // A project carries its own tools/, so the build always matches the project's version.
27
- const script = join(process.cwd(), 'tools', 'build.mjs');
49
+ const script = join(process.cwd(), 'tools', command === 'build' ? 'build.mjs' : 'watch.mjs');
28
50
  if (!existsSync(script)) {
29
- console.error('Nenhum projeto Aliens nesta pasta: tools/build.mjs não foi encontrado.');
51
+ console.error(text.missing.replace('tools/build.mjs', 'tools/' + basename(script)));
30
52
  process.exitCode = 1;
31
53
  } else {
32
54
  await run(script, args);
package/tools/create.mjs CHANGED
@@ -2,15 +2,32 @@ import { copyFile, cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/p
2
2
  import { basename, join, resolve } from 'node:path';
3
3
  import { createProjectDirectories, styleLayers } from './project-layout.mjs';
4
4
 
5
+ // Messages follow the system language (ALIENS_LANG overrides it): English, Portuguese, Spanish or Chinese.
6
+ const language = (() => {
7
+ const tag = (process.env.ALIENS_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG ||
8
+ Intl.DateTimeFormat().resolvedOptions().locale || 'en').toLowerCase();
9
+ return ['pt', 'es', 'zh'].find(code => tag.startsWith(code)) ?? 'en';
10
+ })();
11
+ const messages = {
12
+ en: { usage: 'Usage: node tools/create.mjs <new-project-folder>', name: 'Use a single-line folder name without leading or trailing spaces.',
13
+ created: 'Aliens project created in', exists: 'The destination folder already exists.' },
14
+ pt: { usage: 'Uso: node tools/create.mjs <pasta-do-novo-projeto>', name: 'Use um nome de pasta em uma única linha, sem espaços nas pontas.',
15
+ created: 'Projeto Aliens criado em', exists: 'A pasta de destino já existe.' },
16
+ es: { usage: 'Uso: node tools/create.mjs <carpeta-del-nuevo-proyecto>', name: 'Usa un nombre de carpeta en una sola línea, sin espacios en los extremos.',
17
+ created: 'Proyecto Aliens creado en', exists: 'La carpeta de destino ya existe.' },
18
+ zh: { usage: '用法:node tools/create.mjs <新项目文件夹>', name: '请使用单行文件夹名称,首尾不要有空格。',
19
+ created: 'Aliens 项目已创建于', exists: '目标文件夹已存在。' }
20
+ }[language];
21
+
5
22
  const starter = join(import.meta.dirname, 'starter');
6
23
  const editorExtension = join(import.meta.dirname, 'vscode-space');
7
24
 
8
25
  async function create([path, ...extra]) {
9
- if (!path || extra.length) throw new Error('Uso: node tools/create.mjs <pasta-do-novo-projeto>');
26
+ if (!path || extra.length) throw new Error(messages.usage);
10
27
  const destination = resolve(path);
11
28
  const name = basename(destination);
12
29
  if (!name || /[\r\n\u2028\u2029]/u.test(name) || name !== name.trim()) {
13
- throw new Error('Use um nome de pasta em uma única linha, sem espaços nas pontas.');
30
+ throw new Error(messages.name);
14
31
  }
15
32
 
16
33
  await mkdir(destination);
@@ -21,12 +38,15 @@ async function create([path, ...extra]) {
21
38
  await cp(join(starter, 'app'), join(project, 'app'), { recursive: true });
22
39
  await cp(join(starter, 'styles'), join(project, 'styles'), { recursive: true });
23
40
  await createProjectDirectories(destination);
41
+ // The agent, rule, and skill an AI needs to start working come ready in ai/.
42
+ await cp(join(starter, 'ai'), join(destination, 'ai'), { recursive: true });
24
43
  await mkdir(join(project, 'app', 'pages', 'home'));
25
44
  await mkdir(tools);
26
45
  await mkdir(join(destination, '.vscode'));
27
46
  const manifest = JSON.parse(await readFile(join(editorExtension, 'package.json'), 'utf8'));
28
47
  const paletteSetting = 'editor.semanticTokenColorCustomizations';
29
- const editorSettings = { [paletteSetting]: manifest.contributes.configurationDefaults[paletteSetting] };
48
+ const editorDefaults = manifest.contributes.configurationDefaults;
49
+ const editorSettings = { '[space]': editorDefaults['[space]'], [paletteSetting]: editorDefaults[paletteSetting] };
30
50
 
31
51
  const translations = Object.fromEntries(await Promise.all(
32
52
  (await readdir(join(starter, 'language'))).filter(file => /^\.[a-z]{2}-[A-Z]{2}$/.test(file)).map(async file => [
@@ -38,13 +58,20 @@ async function create([path, ...extra]) {
38
58
  ...translations,
39
59
  'README.md': `# ${name}
40
60
 
41
- Use \`node tools/build.mjs\` para gerar a prévia em \`dist/\`.
61
+ Run \`node tools/build.mjs\` to generate the preview in \`dist/\`.
62
+
63
+ The configuration lives in \`.config\` and the build generates the \`ai/.map\` index.
64
+ The Home includes the style library, with tokens in \`project/styles/settings/\`, components in \`project/styles/components/\` and themes in \`project/styles/settings/theme.style\`.
65
+ Add a \`:root[data-theme="name"]\` block to that file and run the build to make the theme available in the picker.
66
+
67
+ \`.style\` reads plain CSS (\`property: value\`). To write utility classes like \`flex gap-4 md:flex-row\`, run \`npm install @aliens-syndicate/style\` and add to \`.config\`:
42
68
 
43
- A configuração fica em \`.config\` e o build gera o índice \`ai/.map\`.
44
- A Home inclui a biblioteca de estilos, com tokens em \`project/styles/settings/\`, componentes em \`project/styles/components/\` e temas em \`project/styles/settings/theme.style\`.
45
- Adicione um bloco \`:root[data-theme="nome"]\` nesse arquivo e execute o build para disponibilizar o tema no seletor.
69
+ \`\`\`
70
+ style:
71
+ from: @aliens-syndicate/style
72
+ \`\`\`
46
73
 
47
- As páginas e os Elements ficam em \`project/app/pages/\` e \`project/app/elements/\`.
74
+ Pages and Elements live in \`project/app/pages/\` and \`project/app/elements/\`.
48
75
  `,
49
76
  '.config': `project:
50
77
  name: ${name}
@@ -76,10 +103,9 @@ language:
76
103
 
77
104
  const results = await Promise.allSettled([
78
105
  ...Object.entries(template).map(([file, content]) => writeFile(join(destination, file), content, { flag: 'wx' })),
79
- ...['build.mjs', 'runtime.mjs', 'create.mjs', 'project-layout.mjs'].map(file =>
106
+ ...['build.mjs', 'watch.mjs', 'runtime.mjs', 'project-layout.mjs'].map(file =>
80
107
  copyFile(join(import.meta.dirname, file), join(tools, file))
81
108
  ),
82
- cp(starter, join(tools, 'starter'), { recursive: true }),
83
109
  cp(editorExtension, join(tools, 'vscode-space'), { recursive: true }),
84
110
  writeFile(join(destination, '.vscode', 'settings.json'), JSON.stringify(editorSettings, null, 3) + '\n'),
85
111
  writeFile(join(destination, '.gitignore'), 'dist/\n.DS_Store\nproject/.env\n')
@@ -91,12 +117,12 @@ language:
91
117
  throw error;
92
118
  }
93
119
 
94
- console.log(`Projeto Aliens criado em ${destination}`);
120
+ console.log(`${messages.created} ${destination}`);
95
121
  }
96
122
 
97
123
  try {
98
124
  await create(process.argv.slice(2));
99
125
  } catch (error) {
100
- console.error(error.code === 'EEXIST' ? 'A pasta de destino já existe.' : error.message);
126
+ console.error(error.code === 'EEXIST' ? messages.exists : error.message);
101
127
  process.exitCode = 1;
102
128
  }