@aliens-syndicate/cli 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tools/build.mjs CHANGED
@@ -114,14 +114,55 @@ const settings = name => Object.fromEntries(config.find(node => node.value === n
114
114
  }) ?? []);
115
115
  const { entry, assets: assetDirectory, shared: configuredShared, styles, agent: map, environment } = settings('files');
116
116
  const { default: defaultLocale, detection, directory: languageDirectory } = settings('language');
117
- const { from: iconPackage, style: configuredIconStyle } = settings('icons');
118
- if (config.some(node => node.value === 'style:')) throw new Error('.config: style: is now utilities:. Write utilities:\n from: @aliens-syndicate/utilities');
119
- const { from: stylePackage } = settings('utilities');
120
- const { from: elementPackage } = settings('elements');
121
- // Extensions are separate packages that the project installs and declares in .config under <section>: from:, or a
117
+ // Extensions are grouped as in package.json: dependencies: for the packages the app uses (icons, elements, reactive)
118
+ // and devDependencies: for the ones only the build uses (utilities). Each one is a section of its own inside the group,
119
+ // with from: and its settings under it; the build reads both groups the same way.
120
+ const extensionNames = ['utilities', 'icons', 'elements', 'reactive'];
121
+ const extensionGroups = ['dependencies', 'devDependencies'];
122
+ const legacyExtension = config.find(node => [...extensionNames, 'style'].includes(node.value.replace(/:$/, '')));
123
+ if (legacyExtension) {
124
+ const name = legacyExtension.value === 'style:' ? 'utilities' : legacyExtension.value.slice(0, -1);
125
+ const group = name === 'utilities' ? 'devDependencies' : 'dependencies';
126
+ throw new Error(`${legacyExtension.location}: extensions now live under dependencies: or devDependencies:. Write ${group}:\n ${name}:\n from: @aliens-syndicate/${name}`);
127
+ }
128
+ const extensionSettings = {};
129
+ for (const group of config.filter(node => extensionGroups.includes(node.value.replace(/:$/, '')))) {
130
+ if (!group.value.endsWith(':')) throw new Error(`${group.location}: ${group.value.split(':')[0]}: takes its extensions on the lines below it.`);
131
+ for (const node of group.children) {
132
+ const name = node.value.replace(/:$/, '');
133
+ if (!extensionNames.includes(name) || !node.value.endsWith(':')) throw new Error(`${node.location}: ${group.value} accepts ${extensionNames.join(', ')}, not "${node.value}".`);
134
+ if (extensionSettings[name]) throw new Error(`${node.location}: ${name}: is already declared; keep it in dependencies: or devDependencies:, not both.`);
135
+ extensionSettings[name] = Object.fromEntries(node.children.map(child => {
136
+ const [, key, value] = pair.exec(child.value) ?? [];
137
+ if (!key) throw new Error(`${child.location}: ${name}: takes key: value lines, like from: @aliens-syndicate/${name}.`);
138
+ return [key, value];
139
+ }));
140
+ }
141
+ }
142
+ const { from: iconPackage, style: configuredIconStyle } = extensionSettings.icons ?? {};
143
+ const { from: stylePackage } = extensionSettings.utilities ?? {};
144
+ const { from: elementPackage } = extensionSettings.elements ?? {};
145
+ const { from: reactivePackage } = extensionSettings.reactive ?? {};
146
+ // console: prints the Space code of the page in the browser console when it opens, only in the local and dev
147
+ // environments (build: environment:), each with its own toggle, true by default. Other environments never show it.
148
+ // "console: false" (or true) on one line sets both; "console:" with local: and dev: under it sets each one.
149
+ const { environment: buildEnvironment = 'local' } = settings('build');
150
+ const consoleNode = config.find(node => /^console:(\s|$)/.test(node.value));
151
+ const consoleAll = consoleNode?.value.slice('console:'.length).trim();
152
+ if (consoleAll && !['true', 'false'].includes(consoleAll)) throw new Error(`${consoleNode.location}: console: accepts true or false, or local: and dev: under it.`);
153
+ if (consoleAll && consoleNode.children.length) throw new Error(`${consoleNode.location}: console: ${consoleAll} sets local and dev together, so it takes no local: or dev: under it.`);
154
+ const consoleSettings = Object.fromEntries((consoleNode?.children ?? []).map(node => {
155
+ const [, key, value] = pair.exec(node.value) ?? [];
156
+ if (!['local', 'dev'].includes(key)) throw new Error(`${node.location}: console: accepts local: and dev:, not "${node.value}".`);
157
+ if (!['true', 'false'].includes(value)) throw new Error(`${node.location}: console: ${key}: accepts true or false.`);
158
+ return [key, value];
159
+ }));
160
+ const showCode = ['local', 'dev'].includes(buildEnvironment) && (consoleSettings[buildEnvironment] ?? consoleAll ?? 'true') === 'true';
161
+ // Extensions are separate packages that the project installs and declares in .config under <group>: <name>: from:, or a
122
162
  // local folder written as ./path. Icons (usually @aliens-syndicate/icons) let markup draw the icon tag inline (see
123
163
  // renderIcon); utilities (usually @aliens-syndicate/utilities) lets .style list utilities besides plain CSS declarations;
124
- // elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render.
164
+ // elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render; reactive (usually
165
+ // @aliens-syndicate/reactive) adds stream members to .logic, with operators like debounce and switchMap.
125
166
  async function loadExtension(section, name) {
126
167
  let entry;
127
168
  try {
@@ -136,8 +177,10 @@ const styleModule = stylePackage ? await loadExtension('utilities', stylePackage
136
177
  if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`.config: utilities: from: ${stylePackage} is not an Aliens utilities package.`);
137
178
  const elementModule = elementPackage ? await loadExtension('elements', elementPackage) : null;
138
179
  if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(`.config: elements: from: ${elementPackage} is not an Aliens elements package.`);
180
+ const reactiveModule = reactivePackage ? await loadExtension('reactive', reactivePackage) : null;
181
+ if (reactiveModule && typeof reactiveModule.createReactive !== 'function') throw new Error(`.config: reactive: from: ${reactivePackage} is not an Aliens reactive package.`);
139
182
  const noStyle = (where, what) => new Error(`${where}: ${what} need the utilities package. Write CSS as "property: value", or run ` +
140
- 'npm install @aliens-syndicate/utilities and declare it in .config:\nutilities:\n from: @aliens-syndicate/utilities');
183
+ 'npm install @aliens-syndicate/utilities and declare it in .config:\ndevDependencies:\n utilities:\n from: @aliens-syndicate/utilities');
141
184
  // Without the utilities package, .style reads plain CSS declarations only.
142
185
  const resolveUtility = (token, options) => styleModule ? styleModule.resolveUtility(token, options) : { error: 'no utilities package' };
143
186
  const iconRenderer = iconModule?.createIconRenderer();
@@ -145,7 +188,7 @@ const iconCatalog = iconModule ? await iconModule.readCatalog() : null;
145
188
  const iconStyle = iconRenderer ? configuredIconStyle ?? 'stroke-rounded' : null;
146
189
  if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`.config: icons: style: accepts ${iconRenderer.styles.join(', ')}.`);
147
190
  const noIcons = where => new Error(`${where}: icons need a package. Run npm install @aliens-syndicate/icons and declare it in .config:\n` +
148
- 'icons:\n from: @aliens-syndicate/icons\n style: stroke-rounded');
191
+ 'dependencies:\n icons:\n from: @aliens-syndicate/icons\n style: stroke-rounded');
149
192
  // The icon tag: "icon <name> [style] [size-<n>] [color] [second color] [disabled] [hidden]", with id, variant and label
150
193
  // as its only attributes. The first word names the icon and the others may come in any order: one of the ten styles
151
194
  // (the one in .config by default), a size utility, up to two colors (the icon and the second tone of bulk, duotone and
@@ -628,8 +671,8 @@ function render(file, rootProps = {}, ancestry = [], parentScope = null) {
628
671
  return renderNode(nodes[0], true);
629
672
  }
630
673
 
631
- // Inside a selector, "property: value" is a CSS declaration. With the utilities package declared in .config (utilities:
632
- // from: @aliens-syndicate/utilities), 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
674
+ // Inside a selector, "property: value" is a CSS declaration. With the utilities package declared in .config
675
+ // (devDependencies: utilities: from: @aliens-syndicate/utilities), 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
633
676
  // hover: and dark: rewrite the selector; responsive variants such as md: and max-lg: become @media rules, written
634
677
  // after the rest of the file from the widest max-* to the narrowest and then from the narrowest min-width up.
635
678
  const declarationLine = /^-{0,2}[A-Za-z][\w-]*:\s+\S/;
@@ -660,7 +703,7 @@ function compileStyles(nodes, declares) {
660
703
  const utility = resolveUtility(token, { colors: themeColors });
661
704
  if (utility.error) {
662
705
  const hint = /^[-\w]+:\S/.test(token) && !token.includes('[') && !token.includes('(')
663
- ? ' A CSS declaration needs a space after the colon.' : ' See the Style page for the utility names.';
706
+ ? ' A CSS declaration needs a space after the colon.' : ' See the Utilities page for the utility names.';
664
707
  throw new Error(`${line.location}: ${utility.error}.${hint}`);
665
708
  }
666
709
  for (const property of utility.properties) usedProperties.add(property);
@@ -698,22 +741,82 @@ function compileStyles(nodes, declares) {
698
741
 
699
742
  const bindKinds = new Set(['text', 'show', 'pressed', 'expanded']);
700
743
  const kebab = name => name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
744
+ // Reactive Core in .logic: signal holds state, computed derives a value from signals and other computed values,
745
+ // effect runs its body now and whenever a value it read changes, and watch runs its body when one value changes,
746
+ // with the old value as previous. effect and watch take an optional cleanup:, which runs before the next run.
747
+ // The words belong to the language, so import: signal: aliens/core is optional.
748
+ const coreImports = new Set(['signal', 'computed', 'effect', 'watch', 'batch', 'cleanup']);
701
749
  function compileLogic(file) {
702
750
  const { name, children } = declarations.get(file);
703
751
  const element = basename(file, '.logic');
752
+ const lines = sources.get(file).split(/\r?\n/);
753
+ // The lines under body: or cleanup:, without their indentation.
754
+ const block = node => {
755
+ const from = Number(node.location.split(':').at(-1));
756
+ let until = from;
757
+ const indent = (node.level + 1) * indentation.length;
758
+ while (until < lines.length && (!lines[until].trim() || lines[until].startsWith(' '.repeat(indent)))) until++;
759
+ return { code: lines.slice(from, until).map(line => line.slice(indent)).join('\n'), location: node.location };
760
+ };
761
+ const bodies = [];
762
+ const reaction = (member, kind) => {
763
+ const body = member.children.find(node => node.value === 'body:');
764
+ const cleanup = member.children.find(node => node.value === 'cleanup:');
765
+ if (!body?.children.length || (cleanup && !cleanup.children.length) || member.children.length !== (cleanup ? 2 : 1)) {
766
+ throw new Error(`${member.location}: ${kind} takes body: and, optionally, cleanup:.`);
767
+ }
768
+ const compiled = { body: block(body), cleanup: cleanup && block(cleanup) };
769
+ bodies.push(compiled.body, ...(compiled.cleanup ? [compiled.cleanup] : []));
770
+ return compiled;
771
+ };
704
772
  const binds = [];
705
773
  const page = {};
706
- const fieldNames = [];
774
+ const signals = new Map();
775
+ const computed = new Map();
776
+ const streams = new Map();
777
+ const effects = new Map();
778
+ const watches = new Map();
707
779
  const actionNames = [];
708
780
  const members = [];
709
781
  for (const member of children) {
710
- if (member.value === 'import:' && member.children.length === 1 && member.children[0].value === 'signal: aliens/core') continue;
782
+ if (member.value === 'import:' && member.children.length &&
783
+ member.children.every(node => coreImports.has(/^(\w+): aliens\/core$/.exec(node.value)?.[1]))) continue;
711
784
  const field = /^signal ([A-Za-z]\w*): (string|number|boolean) = (.+)$/.exec(member.value);
712
785
  if (field && !member.children.length) {
713
- fieldNames.push(field[1]);
786
+ signals.set(field[1], field[2]);
714
787
  members.push(`${field[1]}: ${field[2]} = ${field[3]};`);
715
788
  continue;
716
789
  }
790
+ const derived = /^computed ([A-Za-z]\w*): (string|number|boolean) = (.+)$/.exec(member.value);
791
+ if (derived && !member.children.length) {
792
+ try { new Function(`return (${derived[3]});`); } catch { throw new Error(`${member.location}: invalid expression.`); }
793
+ if (computed.has(derived[1])) throw new Error(`${member.location}: duplicate computed ${derived[1]}.`);
794
+ computed.set(derived[1], { type: derived[2], expression: derived[3] });
795
+ continue;
796
+ }
797
+ // stream <name>: <type> = <expression>, or "=" at the end of the line and the expression indented below it.
798
+ const flow = /^stream ([A-Za-z]\w*): (.+?) =(?: (.+))?$/.exec(member.value);
799
+ if (flow) {
800
+ if (!reactiveModule) throw new Error(`${member.location}: stream needs the reactive package. Run npm install @aliens-syndicate/reactive and declare it in .config:\ndependencies:\n reactive:\n from: @aliens-syndicate/reactive`);
801
+ if (Boolean(flow[3]) === Boolean(member.children.length)) throw new Error(`${member.location}: write the stream after "=", on the same line or indented below it.`);
802
+ const expression = flow[3] ?? block(member).code;
803
+ try { new Function(`return (${expression});`); } catch { throw new Error(`${member.location}: invalid expression.`); }
804
+ if (streams.has(flow[1])) throw new Error(`${member.location}: duplicate stream ${flow[1]}.`);
805
+ streams.set(flow[1], { type: flow[2], expression });
806
+ continue;
807
+ }
808
+ const effect = /^effect ([A-Za-z]\w*):$/.exec(member.value)?.[1];
809
+ if (effect) {
810
+ if (effects.has(effect)) throw new Error(`${member.location}: duplicate effect ${effect}.`);
811
+ effects.set(effect, reaction(member, 'effect'));
812
+ continue;
813
+ }
814
+ const watch = /^watch ([A-Za-z]\w*):$/.exec(member.value)?.[1];
815
+ if (watch) {
816
+ if (watches.has(watch)) throw new Error(`${member.location}: ${watch} already has a watch; join both bodies in one.`);
817
+ watches.set(watch, { ...reaction(member, 'watch'), location: member.location });
818
+ continue;
819
+ }
717
820
  if (listPattern.test(member.value)) {
718
821
  listsOf(file);
719
822
  continue;
@@ -754,20 +857,26 @@ function compileLogic(file) {
754
857
  !body?.children.length || action.children.length !== 2) {
755
858
  throw new Error(`${action.location}: the Web preview supports actions without parameters that return void.`);
756
859
  }
757
- const lines = sources.get(file).split(/\r?\n/);
758
- const from = Number(body.location.split(':').at(-1));
759
- let until = from;
760
- const indent = (body.level + 1) * indentation.length;
761
- while (until < lines.length && (!lines[until].trim() || lines[until].startsWith(' '.repeat(indent)))) until++;
860
+ const { code, location } = block(body);
861
+ bodies.push({ code, location });
762
862
  actionNames.push(actionName);
763
- members.push(`${actionName}(): void {\n${lines.slice(from, until).map(line => line.slice(indent)).join('\n')}\n}`);
863
+ members.push(`${actionName}(): void {\n${code}\n}`);
764
864
  }
765
865
  }
766
- if (new Set([...fieldNames, ...actionNames]).size !== fieldNames.length + actionNames.length) {
767
- throw new Error(`${file}: duplicate class member.`);
768
- }
866
+ const memberNames = [...signals.keys(), ...computed.keys(), ...streams.keys(), ...actionNames];
867
+ if (new Set(memberNames).size !== memberNames.length) throw new Error(`${file}: duplicate class member.`);
769
868
  for (const [key, field] of Object.entries(page)) {
770
- if (!fieldNames.includes(field)) throw new Error(`${file}: page: ${key} names the missing signal ${field}.`);
869
+ if (!signals.has(field)) throw new Error(`${file}: page: ${key} names the missing signal ${field}.`);
870
+ }
871
+ for (const [target, { location }] of watches) {
872
+ if (!signals.has(target) && !computed.has(target) && !streams.has(target)) throw new Error(`${location}: watch ${target} names no signal, computed or stream of ${element}.`);
873
+ }
874
+ // A computed or a stream is read only: an action, effect or watch that assigns to it stops the build.
875
+ for (const field of [...computed.keys(), ...streams.keys()]) {
876
+ const write = new RegExp(`(?:\\+\\+|--)\\s*this\\.${field}\\b|this\\.${field}\\s*(?:\\+\\+|--|(?:\\*\\*|<<|>>>?|&&|\\|\\||\\?\\?|[-+*/%&|^])?=(?!=))`);
877
+ for (const { code, location } of bodies) {
878
+ if (write.test(code)) throw new Error(`${location}: ${field} is ${computed.has(field) ? 'computed' : 'a stream'}, so it can't be assigned; change what it reads.`);
879
+ }
771
880
  }
772
881
  const standalone = standaloneLogic.has(element);
773
882
  if (standalone && binds.length) throw new Error(`${binds[0].location}: bind: needs tags; ${element} has no .markup.`);
@@ -776,20 +885,35 @@ function compileLogic(file) {
776
885
  for (const bind of binds) {
777
886
  if (!ids.has(bind.id)) throw new Error(`${bind.location}: id "${bind.id}" is not a tag of ${element}.`);
778
887
  }
779
- // An id named "<element>-<signal>" shows that signal without a bind: entry.
780
- for (const field of fieldNames) {
888
+ // An id named "<element>-<signal>" or "<element>-<computed>" shows that value without a bind: entry.
889
+ for (const field of [...signals.keys(), ...computed.keys(), ...streams.keys()]) {
781
890
  const id = `${element}-${kebab(field)}`;
782
891
  if (ids.has(id) && !binds.some(bind => bind.id === id && bind.kind === 'text')) {
783
892
  binds.push({ id, kind: 'text', expression: `this.${field}` });
784
893
  }
785
894
  }
786
895
  }
787
- const implementation = stripTypeScriptTypes(`class ${name} {\n${members.join('\n')}\n}`);
896
+ const typeOf = field => signals.get(field) ?? (computed.get(field) ?? streams.get(field)).type;
897
+ // A stream expression reads the creators of the package, like from and fromEvent, as plain names.
898
+ const streamTools = '{ Stream, from, of, interval, timer, fromEvent, combineLatest, merge, concat, zip }';
899
+ const fn = (parameters, code) => `function (${parameters}) {\n${code}\n}`;
900
+ const optional = cleanup => cleanup ? fn('', cleanup.code) : 'null';
901
+ // create returns the class instance plus the functions the runtime turns into computed values, effects and watches.
902
+ const create = stripTypeScriptTypes(`(function (element) {
903
+ class ${name} {\n${members.join('\n')}\n}
904
+ return {
905
+ state: new ${name}(),
906
+ computed: [${[...computed].map(([field, { type, expression }]) => `[${JSON.stringify(field)}, function (): ${type} { return (${expression}); }]`).join(', ')}],
907
+ streams: [${[...streams].map(([field, { expression }]) => `[${JSON.stringify(field)}, function (${streamTools}) {\nreturn (${expression});\n}]`).join(', ')}],
908
+ effects: [${[...effects].map(([label, { body, cleanup }]) => `[${JSON.stringify(label)}, ${fn('', body.code)}, ${optional(cleanup)}]`).join(', ')}],
909
+ watches: [${[...watches].map(([target, { body, cleanup }]) => `[${JSON.stringify(target)}, ${fn(`previous: ${typeOf(target)}`, body.code)}, ${optional(cleanup)}]`).join(', ')}]
910
+ };
911
+ })`).trim();
788
912
  const compiledBinds = binds.map(({ id, kind, expression }) =>
789
913
  `[${JSON.stringify(id)}, ${JSON.stringify(kind)}, function () { return (${expression}); }]`).join(', ');
790
- const source = `{ create(element) { ${implementation}; return new ${name}(); }, actions: ${JSON.stringify(actionNames)}, ` +
914
+ const source = `{ create: ${create}, signals: ${JSON.stringify([...signals.keys()])}, actions: ${JSON.stringify(actionNames)}, ` +
791
915
  `bind: [${compiledBinds}], page: ${JSON.stringify(page)}, standalone: ${standalone} }`;
792
- return { source, actions: actionNames, page, standalone };
916
+ return { source, actions: actionNames, page, standalone, streams: streams.size > 0 };
793
917
  }
794
918
 
795
919
  const manifest = declarations.get(styles).children;
@@ -885,6 +1009,48 @@ const css = [...[...usedProperties].sort().map(name => styleModule.propertyRule(
885
1009
  ...compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element)).map(entry => entry.css)]
886
1010
  .filter(Boolean).join('\n\n');
887
1011
  const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
1012
+ // The code the console shows: the .markup, .logic and .style of the project and of the package Elements the page
1013
+ // renders, colored like the editor does. To stay small, each file is one string where the private-use character
1014
+ // \uE001 + n starts the color of highlightRoles[n] and \uE000 goes back to plain text.
1015
+ const consoleCode = showCode ? {
1016
+ colors: Object.fromEntries([['light', editorPalette['[*Light*][*light*]'].rules], ['dark', editorPalette.rules]].map(([theme, rules]) =>
1017
+ [theme, highlightRoles.map(role => rules[`${Object.keys(highlightRoleOf).find(type => highlightRoleOf[type] === role)}:space`])])),
1018
+ files: [...declarations.keys()].filter(file => /\.(markup|logic|style)$/.test(file) &&
1019
+ (!packageFiles.has(file) || renderedElements.has(elementOfFile(file)) || usedProviders.has(elementOfFile(file)))).map(file => {
1020
+ const source = sources.get(file).replace(/[\uE000-\uE0FF]/g, '');
1021
+ const { tokens } = analyzeSpace(source, extname(file));
1022
+ let index = 0;
1023
+ let current = -1;
1024
+ const paint = (text, role) => {
1025
+ if (!text) return '';
1026
+ const color = role ? highlightRoles.indexOf(role) : -1;
1027
+ const marker = color === current ? '' : String.fromCharCode(0xE001 + color);
1028
+ current = color;
1029
+ return marker + text;
1030
+ };
1031
+ return [file, source.split(/\r\n|\n|\r/).map((line, lineIndex) => {
1032
+ let start = 0;
1033
+ let output = '';
1034
+ while (tokens[index]?.line === lineIndex) {
1035
+ const token = tokens[index++];
1036
+ output += paint(line.slice(start, token.start));
1037
+ start = token.start + token.length;
1038
+ output += paint(line.slice(token.start, start), token.role);
1039
+ }
1040
+ return output + paint(line.slice(start));
1041
+ }).join('\n')];
1042
+ })
1043
+ } : null;
1044
+ // Which .markup draws each view (a tag with data-view and an id), so the console names the file of the address.
1045
+ if (consoleCode) {
1046
+ consoleCode.views = {};
1047
+ for (const [file] of consoleCode.files.filter(([file]) => file.endsWith('.markup'))) {
1048
+ for (const line of sources.get(file).split(/\r?\n/)) {
1049
+ const id = /\bdata-view\b/.test(line) && /\bid="([^"]+)"/.exec(line)?.[1];
1050
+ if (id) consoleCode.views[id] = file;
1051
+ }
1052
+ }
1053
+ }
888
1054
  const output = join(workspace, 'dist');
889
1055
  const favicon = assetFiles.includes(join(assetDirectory, 'mark.png')) ? '\n <link rel="icon" href="./assets/mark.png">' : '';
890
1056
  await mkdir(output, { recursive: true });
@@ -900,9 +1066,11 @@ const defaultLocale = ${JSON.stringify(defaultLocale)};
900
1066
  const detectLocale = ${detection === 'browser'};
901
1067
  const iconStyle = ${JSON.stringify(iconStyle)};
902
1068
  const iconRenderer = ${iconCatalogUsed ? `(${iconModule.createIconRenderer})()` : 'null'};
1069
+ const reactiveStreams = ${usedLogic.some(([, entry]) => entry.streams) ? `(${reactiveModule.createReactive})` : 'null'};
903
1070
  const copyIcons = ${JSON.stringify(iconRenderer && iconCatalog.icons['copy-01'] && iconCatalog.icons['tick-02'] ? {
904
1071
  copy: inlineIcon('copy-01', iconStyle, 'copy-icon'), copied: inlineIcon('tick-02', iconStyle, 'copied-icon')
905
1072
  } : null)};
1073
+ const consoleCode = ${JSON.stringify(consoleCode)};
906
1074
  ${runtime}`),
907
1075
  writeFile(join(output, 'index.html'), `<!doctype html>
908
1076
  <html lang="${defaultLocale}">
@@ -22,11 +22,15 @@ export const defaultPort = 5151;
22
22
  export const projectToolFiles = ['build.mjs', 'watch.mjs', 'runtime.mjs', 'project-layout.mjs'];
23
23
  export const projectToolDirectories = ['vscode-space'];
24
24
 
25
- // The optional extensions a project can declare in .config under <section>: from:.
25
+ // The optional extensions a project can declare in .config under <group>: <section>: from:. The group follows
26
+ // package.json: dependencies for the packages the app uses, devDependencies for the ones only the build uses.
27
+ // aliens new offers each one with "yes" as the answer by default, except those marked off: reactive adds stream
28
+ // operators, while the Reactive Core (signal, computed, effect, watch, batch and cleanup) comes with every project.
26
29
  export const extensions = [
27
- { section: 'utilities', name: '@aliens-syndicate/utilities' },
28
- { section: 'icons', name: '@aliens-syndicate/icons', extra: ' style: stroke-rounded\n' },
29
- { section: 'elements', name: '@aliens-syndicate/elements' }
30
+ { section: 'utilities', group: 'devDependencies', name: '@aliens-syndicate/utilities' },
31
+ { section: 'icons', group: 'dependencies', name: '@aliens-syndicate/icons', extra: ' style: stroke-rounded\n' },
32
+ { section: 'elements', group: 'dependencies', name: '@aliens-syndicate/elements' },
33
+ { section: 'reactive', group: 'dependencies', name: '@aliens-syndicate/reactive', off: true }
30
34
  ];
31
35
 
32
36
  const paint = code => text => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : String(text);
@@ -130,23 +134,37 @@ export function requireProject() {
130
134
  return root;
131
135
  }
132
136
 
133
- // .config is Space: sections at the first level and key: value pairs under them. Comments start with #.
137
+ // .config is Space: sections at the first level and key: value pairs under them, nested by indentation (dependencies:
138
+ // and devDependencies: hold one section per extension). A key with nothing after the colon opens a section.
139
+ // Comments start with #.
134
140
  export function readConfig(root) {
135
141
  const config = {};
136
- let section = null;
142
+ const stack = [{ indent: -1, values: config }];
137
143
  for (const line of readFileSync(join(root, '.config'), 'utf8').split(/\r?\n/)) {
138
144
  const value = line.trim();
139
145
  if (!value || value.startsWith('#')) continue;
140
146
  const pair = /^([\w.-]+):\s*(.*)$/.exec(value);
141
147
  if (!pair) continue;
142
- if (line === line.trimStart()) {
143
- section = pair[1];
144
- config[section] ??= {};
145
- } else if (section) config[section][pair[1]] = pair[2];
148
+ const indent = line.length - line.trimStart().length;
149
+ while (stack.at(-1).indent >= indent) stack.pop();
150
+ const parent = stack.at(-1).values;
151
+ if (pair[2]) parent[pair[1]] = pair[2];
152
+ else {
153
+ parent[pair[1]] = typeof parent[pair[1]] === 'object' ? parent[pair[1]] : {};
154
+ stack.push({ indent, values: parent[pair[1]] });
155
+ }
146
156
  }
147
157
  return config;
148
158
  }
149
159
 
160
+ // The extensions .config declares under dependencies: and devDependencies:, as { name, group, from, ...settings }.
161
+ export const extensionGroups = ['dependencies', 'devDependencies'];
162
+ export function configExtensions(config) {
163
+ return extensionGroups.flatMap(group => Object.entries(config?.[group] ?? {})
164
+ .filter(([, values]) => typeof values === 'object' && values.from)
165
+ .map(([name, values]) => ({ ...values, name, group })));
166
+ }
167
+
150
168
  // npm is npm.cmd on Windows, which spawn only runs through the shell.
151
169
  export function runCommand(command, args, options = {}) {
152
170
  return new Promise((resolvePromise, reject) => {
package/tools/cli.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import {
6
- CliError, bold, captureCommand, cliPackage, cliRoot, cliVersion, installedVersion, cyan, defaultPort, dim, findProject, parseFlags, pick, readConfig, red, requireProject, runBuild
6
+ CliError, bold, captureCommand, cliPackage, configExtensions, cliRoot, cliVersion, installedVersion, cyan, defaultPort, dim, findProject, parseFlags, pick, readConfig, red, requireProject, runBuild
7
7
  } from './cli-shared.mjs';
8
8
 
9
9
  const commands = [
@@ -12,6 +12,7 @@ const commands = [
12
12
  es: 'Crea un proyecto Aliens y pregunta qué extensiones instalar.', zh: '创建 Aliens 项目,并询问要安装哪些扩展。' },
13
13
  options: [['-y, --yes', { en: 'Accepts every default without asking', pt: 'Aceita todos os padrões sem perguntar', es: 'Acepta todos los valores por defecto sin preguntar', zh: '不询问,全部使用默认值' }],
14
14
  ['--no-utilities, --no-icons, --no-elements', { en: 'Leaves that extension out', pt: 'Deixa essa extensão de fora', es: 'Deja fuera esa extensión', zh: '不包含该扩展' }],
15
+ ['--reactive', { en: 'Adds the stream operators of @aliens-syndicate/reactive', pt: 'Adiciona os operadores de stream do @aliens-syndicate/reactive', es: 'Añade los operadores de stream de @aliens-syndicate/reactive', zh: '添加 @aliens-syndicate/reactive 的 stream 操作符' }],
15
16
  ['--skip-install', { en: 'Creates the files without running npm install', pt: 'Cria os arquivos sem rodar o npm install', es: 'Crea los archivos sin ejecutar npm install', zh: '只创建文件,不运行 npm install' }]] },
16
17
  { name: 'run', aliases: ['watch'], usage: 'aliens run [--port <number>]', load: async () => (await import('./serve.mjs')).serve,
17
18
  about: { en: `Builds, serves on http://localhost:${defaultPort} and rebuilds and reloads the browser on every save.`,
@@ -114,7 +115,7 @@ async function version(args) {
114
115
  const config = root ? readConfig(root) : null;
115
116
  const info = [[label.cli, cliVersion], [label.node, process.versions.node],
116
117
  [label.packageManager, npm.code === 0 ? `npm ${npm.output}` : '—'], [label.os, `${process.platform} ${process.arch}`]];
117
- const extensionPackages = config ? Object.values(config).map(values => values.from).filter(name => name && !/^\.{1,2}\//.test(name)) : [];
118
+ const extensionPackages = configExtensions(config).map(extension => extension.from).filter(name => !/^\.{1,2}\//.test(name));
118
119
  if (config) info.push([label.project, `${config.project?.name ?? '?'} ${config.project?.version ?? ''}`.trim()]);
119
120
 
120
121
  console.log('');
@@ -122,7 +123,7 @@ async function version(args) {
122
123
  console.log('');
123
124
  for (const [name, value] of info) console.log(`${name}: ${value}`);
124
125
  if (config) {
125
- const sections = Object.entries(config).filter(([, values]) => values.from).map(([section]) => section);
126
+ const sections = configExtensions(config).map(extension => extension.name);
126
127
  if (sections.length) console.log(dim(`... ${label.extensions}: ${sections.join(', ')}`));
127
128
  }
128
129
 
package/tools/create.mjs CHANGED
@@ -12,24 +12,28 @@ const text = {
12
12
  en: { usage: 'Usage: aliens new <project-name>', name: 'What is your project named?', fallbackName: 'my-aliens-app',
13
13
  badName: 'Use lowercase words separated by hyphens for the project name, like my-app.', exists: 'The folder {path} already exists.',
14
14
  utilities: 'Use utility classes in .style ({package})?', icons: 'Use the icon library ({package})?', elements: 'Use ready-made Elements ({package})?',
15
+ reactive: 'Add stream operators like debounce and switchMap ({package})? signal, computed and effect already come with Aliens.',
15
16
  creating: 'Creating the Aliens project in {path}', created: 'Aliens project created in {path}', installing: 'Installing the packages with npm…',
16
17
  unpublished: '{package} is not on npm yet, so the project starts without it.', installFailed: 'npm install failed. Enter the folder and run npm install.',
17
18
  skipped: 'Packages not installed (--skip-install). Enter the folder and run npm install.', next: 'Next steps:' },
18
19
  pt: { usage: 'Uso: aliens new <nome-do-projeto>', name: 'Qual é o nome do projeto?', fallbackName: 'meu-app-aliens',
19
20
  badName: 'Use palavras minúsculas separadas por hífen no nome do projeto, como meu-app.', exists: 'A pasta {path} já existe.',
20
21
  utilities: 'Usar classes utilitárias no .style ({package})?', icons: 'Usar a biblioteca de ícones ({package})?', elements: 'Usar Elements prontos ({package})?',
22
+ reactive: 'Adicionar operadores de stream como debounce e switchMap ({package})? signal, computed e effect já vêm com o Aliens.',
21
23
  creating: 'Criando o projeto Aliens em {path}', created: 'Projeto Aliens criado em {path}', installing: 'Instalando os pacotes com o npm…',
22
24
  unpublished: '{package} ainda não está no npm, então o projeto começa sem ele.', installFailed: 'O npm install falhou. Entre na pasta e rode npm install.',
23
25
  skipped: 'Pacotes não instalados (--skip-install). Entre na pasta e rode npm install.', next: 'Próximos passos:' },
24
26
  es: { usage: 'Uso: aliens new <nombre-del-proyecto>', name: '¿Cómo se llama tu proyecto?', fallbackName: 'mi-app-aliens',
25
27
  badName: 'Usa palabras en minúsculas separadas por guiones en el nombre del proyecto, como mi-app.', exists: 'La carpeta {path} ya existe.',
26
28
  utilities: '¿Usar clases utilitarias en .style ({package})?', icons: '¿Usar la biblioteca de íconos ({package})?', elements: '¿Usar Elements listos ({package})?',
29
+ reactive: '¿Añadir operadores de stream como debounce y switchMap ({package})? signal, computed y effect ya vienen con Aliens.',
27
30
  creating: 'Creando el proyecto Aliens en {path}', created: 'Proyecto Aliens creado en {path}', installing: 'Instalando los paquetes con npm…',
28
31
  unpublished: '{package} todavía no está en npm, así que el proyecto empieza sin él.', installFailed: 'npm install falló. Entra en la carpeta y ejecuta npm install.',
29
32
  skipped: 'Paquetes no instalados (--skip-install). Entra en la carpeta y ejecuta npm install.', next: 'Próximos pasos:' },
30
33
  zh: { usage: '用法:aliens new <项目名称>', name: '项目叫什么名字?', fallbackName: 'my-aliens-app',
31
34
  badName: '项目名称请使用以连字符分隔的小写单词,例如 my-app。', exists: '文件夹 {path} 已存在。',
32
35
  utilities: '在 .style 中使用工具类({package})?', icons: '使用图标库({package})?', elements: '使用现成的 Elements({package})?',
36
+ reactive: '添加 debounce、switchMap 等 stream 操作符({package})?signal、computed 和 effect 已内置于 Aliens。',
33
37
  creating: '正在 {path} 中创建 Aliens 项目', created: 'Aliens 项目已创建于 {path}', installing: '正在用 npm 安装依赖包…',
34
38
  unpublished: '{package} 尚未发布到 npm,项目将先不包含它。', installFailed: 'npm install 失败。请进入文件夹运行 npm install。',
35
39
  skipped: '未安装依赖包(--skip-install)。请进入文件夹运行 npm install。', next: '下一步:' }
@@ -81,15 +85,25 @@ Add a \`:root[data-theme="name"]\` block to that file and run the build to make
81
85
  \`.style\` reads plain CSS (\`property: value\`). To write utility classes like \`flex gap-4 md:flex-row\`, run \`npm install @aliens-syndicate/utilities\` and add to \`.config\`:
82
86
 
83
87
  \`\`\`
84
- utilities:
85
- from: @aliens-syndicate/utilities
88
+ devDependencies:
89
+ utilities:
90
+ from: @aliens-syndicate/utilities
86
91
  \`\`\`
87
92
 
88
93
  To use buttons, badges, alerts, cards and fields written in Space, run \`npm install @aliens-syndicate/elements\` and add to \`.config\`:
89
94
 
90
95
  \`\`\`
91
- elements:
92
- from: @aliens-syndicate/elements
96
+ dependencies:
97
+ elements:
98
+ from: @aliens-syndicate/elements
99
+ \`\`\`
100
+
101
+ \`signal\`, \`computed\`, \`effect\`, \`watch\`, \`batch\` and \`cleanup:\` come with Aliens. For stream operators like \`debounce\`, \`switchMap\` and \`combineLatest\`, run \`npm install @aliens-syndicate/reactive\` and add to \`.config\`:
102
+
103
+ \`\`\`
104
+ dependencies:
105
+ reactive:
106
+ from: @aliens-syndicate/reactive
93
107
  \`\`\`
94
108
 
95
109
  Pages and Elements live in \`project/app/pages/\` and \`project/app/elements/\`.
@@ -113,9 +127,14 @@ build:
113
127
  target: web
114
128
  environment: local
115
129
 
130
+ console:
131
+ local: true
132
+ dev: true
133
+
116
134
  serve:
117
135
  port: ${defaultPort}
118
- ${chosen.map(extension => `\n${extension.section}:\n from: ${extension.name}\n${extension.extra ?? ''}`).join('')}
136
+ ${['dependencies', 'devDependencies'].map(group => chosen.filter(extension => extension.group === group)).filter(list => list.length)
137
+ .map(list => `\n${list[0].group}:\n${list.map(extension => ` ${extension.section}:\n from: ${extension.name}\n${extension.extra ?? ''}`).join('')}`).join('')}
119
138
  language:
120
139
  directory: project/language
121
140
  default: en-US
@@ -183,10 +202,11 @@ export async function create(args) {
183
202
  if (!validName(name)) throw new CliError(`${t('badName')} (${kebab(name)}?)`);
184
203
 
185
204
  // Each extension is on unless a flag turns it off; without flags, the prompt asks with "yes" as the default.
205
+ // An extension marked off (reactive) works the other way: --reactive or a "yes" adds it.
186
206
  const chosen = [];
187
207
  for (const extension of extensions) {
188
208
  let use = flags[extension.section];
189
- if (use === undefined) use = asking ? await confirm(t(extension.section, { package: extension.name })) : true;
209
+ if (use === undefined) use = asking ? await confirm(t(extension.section, { package: extension.name }), !extension.off) : !extension.off;
190
210
  if (use) chosen.push(extension);
191
211
  }
192
212
 
@@ -210,12 +230,16 @@ export async function create(args) {
210
230
  chosen.splice(chosen.indexOf(extension), 1);
211
231
  }
212
232
  }
213
- const devDependencies = Object.fromEntries([{ name: cliPackage }, ...chosen]
214
- .filter(entry => flags['skip-install'] || versions.get(entry.name))
215
- .map(entry => [entry.name, entry.name === cliPackage && flags['skip-install'] ? `^${cliVersion}` : versions.get(entry.name) ? `^${versions.get(entry.name)}` : 'latest']));
233
+ // package.json splits the packages the same way .config does; the CLI is a devDependency.
234
+ const range = entry => entry.name === cliPackage && flags['skip-install'] ? `^${cliVersion}` : versions.get(entry.name) ? `^${versions.get(entry.name)}` : 'latest';
235
+ const group = name => Object.fromEntries([{ name: cliPackage, group: 'devDependencies' }, ...chosen]
236
+ .filter(entry => entry.group === name && (flags['skip-install'] || versions.get(entry.name)))
237
+ .map(entry => [entry.name, range(entry)]));
238
+ const dependencies = group('dependencies');
216
239
  const manifest = {
217
240
  name, version: '0.1.0', private: true, type: 'module',
218
- scripts: { dev: 'aliens run', build: 'aliens build', doctor: 'aliens doctor' }, devDependencies
241
+ scripts: { dev: 'aliens run', build: 'aliens build', doctor: 'aliens doctor' },
242
+ ...(Object.keys(dependencies).length ? { dependencies } : {}), devDependencies: group('devDependencies')
219
243
  };
220
244
  await writeFile(join(destination, 'package.json'), JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx' });
221
245
  await writeFile(join(destination, '.config'), config(name, chosen), { flag: 'wx' });
package/tools/doctor.mjs CHANGED
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { toolsDifferences } from './update.mjs';
6
6
  import {
7
7
  bold, captureCommand, installedVersion, cliPackage, cliRoot, cliVersion, compareVersions, cyan, defaultPort, dim, findProject, green,
8
- latestVersion, minimumNode, parseFlags, pick, readConfig, red, runBuild, yellow
8
+ configExtensions, latestVersion, minimumNode, parseFlags, pick, readConfig, red, runBuild, yellow
9
9
  } from './cli-shared.mjs';
10
10
 
11
11
  const text = {
@@ -114,11 +114,10 @@ export async function doctor(args) {
114
114
  else report('warn', t('toolsOld', { version: cliVersion, files: changed.slice(0, 3).join(', ') + (changed.length > 3 ? '…' : '') }), t('toolsFix'));
115
115
  }
116
116
 
117
- for (const [section, values] of Object.entries(config ?? {})) {
118
- if (!values.from) continue;
119
- const version = installedVersion(root, values.from);
120
- if (version) report('ok', t('extension', { name: values.from, version }));
121
- else report('fail', t('extensionMissing', { name: values.from, section }), t('extensionFix', { name: values.from }));
117
+ for (const { name: section, group, from } of configExtensions(config)) {
118
+ const version = installedVersion(root, from);
119
+ if (version) report('ok', t('extension', { name: from, version }));
120
+ else report('fail', t('extensionMissing', { name: from, section: `${group}: ${section}` }), t('extensionFix', { name: group === 'devDependencies' ? `-D ${from}` : from }));
122
121
  }
123
122
 
124
123
  const port = Number(config?.serve?.port ?? defaultPort);
@@ -1,5 +1,5 @@
1
1
  // Generates the Icons page (project/app/pages/icon-docs) from the catalog of the icon package that .config declares
2
- // under icons: from:. The sidebar lists every category; the runtime fills each one with its icons when the page opens,
2
+ // under dependencies: icons: from:. The sidebar lists every category; the runtime fills each one with its icons when the page opens,
3
3
  // so the catalog stays out of index.html. Run it after updating the package: node tools/icon-docs.mjs
4
4
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
5
  import { createRequire } from 'node:module';
@@ -8,8 +8,8 @@ import { pathToFileURL } from 'node:url';
8
8
 
9
9
  const workspace = resolve(import.meta.dirname, '..');
10
10
  const config = await readFile(join(workspace, '.config'), 'utf8');
11
- const from = /^icons:\n(?: {3}.*\n)*? {3}from: (.+)$/m.exec(config)?.[1].trim();
12
- if (!from) throw new Error('icon-docs: declare the icon package in .config under icons: from:.');
11
+ const from = /^ {3}icons:\n(?: {6}.*\n)*? {6}from: (.+)$/m.exec(config)?.[1].trim();
12
+ if (!from) throw new Error('icon-docs: declare the icon package in .config under dependencies: icons: from:.');
13
13
  const entry = /^\.{1,2}\//.test(from) ? join(workspace, from, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(from);
14
14
  const { createIconRenderer, readCatalog } = await import(pathToFileURL(entry).href);
15
15
  const { categories, icons } = await readCatalog();
@@ -88,10 +88,11 @@ for (const [key, code] of [['usageInstall', 'npm install @aliens-syndicate/icons
88
88
  } else if (key === 'usageConfig') {
89
89
  add(6, 'pre variant="icon-docs-code" tabindex="0"');
90
90
  add(7, 'code');
91
- add(8, 'span={icons:} variant="icon-docs-code-line"');
92
- add(8, 'span={ from: @aliens-syndicate/icons} variant="icon-docs-code-line"');
91
+ add(8, 'span={dependencies:} variant="icon-docs-code-line"');
92
+ add(8, 'span={ icons:} variant="icon-docs-code-line"');
93
+ add(8, 'span={ from: @aliens-syndicate/icons} variant="icon-docs-code-line"');
93
94
  add(8, 'span variant="icon-docs-code-line"');
94
- add(9, 'span={ style: }');
95
+ add(9, 'span={ style: }');
95
96
  add(9, 'span={stroke-rounded} data-icon-style-name');
96
97
  } else {
97
98
  add(6, 'pre variant="icon-docs-code" tabindex="0"');