clarusjs 0.12.0 → 0.14.0

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 (45) hide show
  1. package/README.md +2 -0
  2. package/dist/check/generate.js +54 -11
  3. package/dist/cli/check.js +15 -4
  4. package/dist/compiler/class-style.d.ts +2 -0
  5. package/dist/compiler/class-style.js +53 -0
  6. package/dist/compiler/emit-client.js +24 -4
  7. package/dist/compiler/emit-server.js +15 -5
  8. package/dist/compiler/html-expr.d.ts +10 -2
  9. package/dist/compiler/html-expr.js +31 -17
  10. package/dist/compiler/icon.d.ts +24 -0
  11. package/dist/compiler/icon.js +83 -0
  12. package/dist/compiler/index.d.ts +4 -0
  13. package/dist/compiler/index.js +53 -9
  14. package/dist/compiler/ir.d.ts +23 -0
  15. package/dist/compiler/ir.js +69 -2
  16. package/dist/compiler/lint.js +12 -1
  17. package/dist/compiler/parse.d.ts +24 -0
  18. package/dist/compiler/parse.js +66 -0
  19. package/dist/compiler/script.d.ts +10 -1
  20. package/dist/compiler/script.js +17 -3
  21. package/dist/fetch/index.d.ts +157 -3
  22. package/dist/fetch/index.js +135 -14
  23. package/dist/icons.d.ts +59 -0
  24. package/dist/icons.js +112 -0
  25. package/dist/runtime/attrs.d.ts +27 -0
  26. package/dist/runtime/attrs.js +66 -0
  27. package/dist/runtime/dom.d.ts +15 -0
  28. package/dist/runtime/dom.js +50 -1
  29. package/dist/runtime/html.d.ts +6 -0
  30. package/dist/runtime/html.js +19 -1
  31. package/dist/runtime/index.d.ts +3 -2
  32. package/dist/runtime/index.js +3 -2
  33. package/dist/runtime/server.d.ts +14 -1
  34. package/dist/runtime/server.js +36 -2
  35. package/dist/server/handler.d.ts +1 -1
  36. package/dist/server/handler.js +5 -2
  37. package/dist/server/views.d.ts +1 -1
  38. package/dist/server/views.js +1 -1
  39. package/dist/vite/node.d.ts +2 -0
  40. package/dist/vite/node.js +13 -0
  41. package/dist/vite/plugin.d.ts +6 -1
  42. package/dist/vite/plugin.js +114 -17
  43. package/dist/vite/sitemap.d.ts +20 -1
  44. package/dist/vite/sitemap.js +27 -3
  45. package/package.json +5 -1
package/README.md CHANGED
@@ -6,6 +6,8 @@
6
6
 
7
7
  <p align="center"><strong>Clear, compiled views.</strong></p>
8
8
 
9
+ <p align="center">Pronounced <strong>KLAIR-us</strong> (/ˈklɛər.əs/), from the Latin <em>clarus</em>, “clear, bright”.</p>
10
+
9
11
  <p align="center"><a href="https://clarusjs.com">Documentation</a> · <a href="https://clarusjs.com/guide/getting-started">Getting started</a> · <a href="https://www.npmjs.com/package/clarusjs">npm</a></p>
10
12
 
11
13
  Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
@@ -21,7 +21,9 @@ export function generateTs(source, file, options = {}) {
21
21
  emit('declare function __cl_use(value: unknown): void\n');
22
22
  emit('declare const __cl_bool: boolean\n');
23
23
  const text = 'string | number | boolean | null | undefined';
24
- emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
24
+ emit(`export type __cl_Class = ${text} | readonly __cl_Class[] | { [name: string]: unknown }\n`);
25
+ emit(`export type __cl_Style = ${text} | __cl_Style[] | { [property: string]: ${text} }\n`);
26
+ emit(`type __cl_AttrOf<T extends string, P extends string> = P extends '...' ? { [name: string]: unknown } | null | undefined : P extends 'class' ? __cl_Class : P extends \`class.\${string}\` ? unknown : P extends 'style' ? __cl_Style : T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
25
27
  emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
26
28
  emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
27
29
  emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
@@ -46,6 +48,13 @@ export function generateTs(source, file, options = {}) {
46
48
  emit('\n');
47
49
  }
48
50
  }
51
+ const serverScript = parsed.serverScript ? splitImports(parsed.serverScript.code, file, source, parsed.serverScript.start, true) : null;
52
+ if (parsed.serverScript && serverScript) {
53
+ for (const imp of serverScript.imports) {
54
+ copy(imp.text, parsed.serverScript.start + imp.start);
55
+ emit('\n');
56
+ }
57
+ }
49
58
  for (const t of parsed.types) {
50
59
  emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
51
60
  copy(t.type, t.typeStart);
@@ -74,7 +83,8 @@ export function generateTs(source, file, options = {}) {
74
83
  emit('\n');
75
84
  }
76
85
  emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
77
- emit('\nexport default function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n');
86
+ const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
87
+ emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
78
88
  for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
79
89
  if (!list.length)
80
90
  continue;
@@ -91,23 +101,27 @@ export function generateTs(source, file, options = {}) {
91
101
  emit(' } = __cl_props\n');
92
102
  emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
93
103
  }
94
- if (parsed.script && script) {
95
- const body = script.body;
104
+ const copyScript = (from, split) => {
105
+ const body = split.body;
96
106
  const cuts = [
97
- ...script.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
98
- ...untypedParams(parsed.script.code).map((e) => ({ ...e, end: e.at })),
107
+ ...split.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
108
+ ...untypedParams(from.code).map((e) => ({ ...e, end: e.at })),
99
109
  ].sort((a, b) => a.at - b.at);
100
110
  let pos = 0;
101
111
  for (const cut of cuts) {
102
112
  if (cut.at > pos)
103
- copy(body.slice(pos, cut.at), parsed.script.start + pos);
113
+ copy(body.slice(pos, cut.at), from.start + pos);
104
114
  emit(cut.text);
105
115
  pos = Math.max(pos, cut.end);
106
116
  }
107
117
  if (body.length > pos)
108
- copy(body.slice(pos), parsed.script.start + pos);
118
+ copy(body.slice(pos), from.start + pos);
109
119
  emit('\n;\n');
110
- }
120
+ };
121
+ if (parsed.serverScript && serverScript)
122
+ copyScript(parsed.serverScript, serverScript);
123
+ if (parsed.script && script)
124
+ copyScript(parsed.script, script);
111
125
  const use = (expr, start) => {
112
126
  emit(' __cl_use((');
113
127
  copy(expr, at(expr, start));
@@ -157,6 +171,28 @@ export function generateTs(source, file, options = {}) {
157
171
  emit(' }\n');
158
172
  });
159
173
  return;
174
+ case 'await': {
175
+ emit(' { const __cl_aw = (');
176
+ copy(node.expr, at(node.expr, node.exprStart));
177
+ emit(');\n');
178
+ emit(' {\n');
179
+ node.pending.forEach(visit);
180
+ emit(' }\n');
181
+ for (const [b, type] of [[node.then, 'Awaited<typeof __cl_aw>'], [node.catch, 'any']]) {
182
+ if (!b)
183
+ continue;
184
+ emit(' { const ');
185
+ copy(b.name, b.nameStart);
186
+ emit(`: ${type} = null!; __cl_use(${b.name})\n`);
187
+ const outer = guards.splice(0);
188
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([b.name]))));
189
+ b.children.forEach(visit);
190
+ guards.splice(0, guards.length, ...outer);
191
+ emit(' }\n');
192
+ }
193
+ emit(' }\n');
194
+ return;
195
+ }
160
196
  case 'for': {
161
197
  emit(' for (const ');
162
198
  copy(node.item, node.itemStart);
@@ -184,7 +220,14 @@ export function generateTs(source, file, options = {}) {
184
220
  point('__cl_p', node.start, node.tag.length + 1);
185
221
  emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
186
222
  for (const a of node.attrs) {
187
- if (a.kind !== 'prop' && a.kind !== 'model')
223
+ if (a.kind !== 'prop' || a.name !== '...')
224
+ continue;
225
+ emit('...(');
226
+ copy(a.expr, at(a.expr, attrValueStart(a)));
227
+ emit('), ');
228
+ }
229
+ for (const a of node.attrs) {
230
+ if ((a.kind !== 'prop' && a.kind !== 'model') || a.name === '...')
188
231
  continue;
189
232
  copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
190
233
  emit(': (');
@@ -277,7 +320,7 @@ export function viewsDeclaration(views) {
277
320
  const ns = `__cl_v${i}`;
278
321
  const body = [];
279
322
  for (const t of parsed.typeImports) {
280
- const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
323
+ const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from.startsWith('~/') ? `../src/${t.from.slice(2)}` : t.from;
281
324
  const clause = t.clause.trim();
282
325
  if (clause.startsWith('{')) {
283
326
  for (const part of clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '')).filter(Boolean)) {
package/dist/cli/check.js CHANGED
@@ -4,6 +4,9 @@ import { createRequire } from 'node:module';
4
4
  import { basename, dirname, relative, resolve, sep } from 'node:path';
5
5
  import { ClarusError } from '../compiler/errors.js';
6
6
  import { lint } from '../compiler/lint.js';
7
+ import { checkIcons } from '../compiler/icon.js';
8
+ import { parse } from '../compiler/parse.js';
9
+ import { resolveIcon } from '../icons.js';
7
10
  import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
8
11
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
9
12
  import { projectAliases, resolveAlias } from '../vite/aliases.js';
@@ -77,6 +80,12 @@ export function check(options) {
77
80
  }
78
81
  catch { }
79
82
  }
83
+ const located = (err) => {
84
+ const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
85
+ const lines = source.split('\n');
86
+ const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
87
+ diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
88
+ };
80
89
  try {
81
90
  const loader = loaderOf(path);
82
91
  const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
@@ -88,11 +97,13 @@ export function check(options) {
88
97
  catch (err) {
89
98
  if (!(err instanceof ClarusError))
90
99
  throw err;
91
- const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
92
- const lines = source.split('\n');
93
- const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
94
- diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
100
+ located(err);
101
+ }
102
+ try {
103
+ for (const err of checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, path)))
104
+ located(err);
95
105
  }
106
+ catch { }
96
107
  }
97
108
  const appRoot = realpathSync(root);
98
109
  const paths = {};
@@ -0,0 +1,2 @@
1
+ import { type TemplateNode } from './parse.ts';
2
+ export declare function foldClass(nodes: TemplateNode[], components: Set<string>): void;
@@ -0,0 +1,53 @@
1
+ import { awaitLists } from './parse.js';
2
+ const spreadOf = (node) => node.attrs.find((a) => a.kind === 'prop' && a.name === '...')?.expr;
3
+ const isSource = (a, name) => a.name === name && a.kind !== 'event';
4
+ function part(a) {
5
+ if (a.kind === 'static')
6
+ return JSON.stringify(a.value === true ? '' : a.value);
7
+ if (a.kind === 'interp')
8
+ return `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
9
+ return `(${a.expr})`;
10
+ }
11
+ function foldStyle(node) {
12
+ const props = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('style.'));
13
+ const sources = node.attrs.filter((a) => isSource(a, 'style'));
14
+ const spread = spreadOf(node);
15
+ if (!spread && !props.length && !(sources.length > 1 && sources.some((a) => a.kind === 'prop')))
16
+ return;
17
+ const exprs = [...(spread ? [`((${spread}) || {}).style`] : []), ...sources.map(part), ...props.map((p) => `{ ${JSON.stringify(p.name.slice(6))}: (${p.expr}) }`)];
18
+ const start = (sources[0] ?? props[0] ?? node.attrs.find((a) => a.name === '...')).start;
19
+ node.attrs = [...node.attrs.filter((a) => !isSource(a, 'style') && !props.includes(a)), { kind: 'prop', name: 'style', expr: `__cl_styleValue([${exprs.join(', ')}])`, start }];
20
+ }
21
+ export function foldClass(nodes, components) {
22
+ for (const node of nodes) {
23
+ if (node.type === 'element') {
24
+ if (!components.has(node.tag))
25
+ foldStyle(node);
26
+ if (!components.has(node.tag)) {
27
+ const toggles = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('class.'));
28
+ const sources = node.attrs.filter((a) => isSource(a, 'class'));
29
+ const mixed = sources.length > 1 && sources.some((a) => a.kind === 'prop');
30
+ const spread = spreadOf(node);
31
+ if (toggles.length || mixed || spread) {
32
+ const exprs = [...(spread ? [`((${spread}) || {}).class`] : []), ...sources.map(part), ...toggles.map((t) => `{ ${JSON.stringify(t.name.slice(6))}: (${t.expr}) }`)];
33
+ const start = (sources[0] ?? toggles[0] ?? node.attrs.find((a) => a.name === '...')).start;
34
+ node.attrs = [...node.attrs.filter((a) => !isSource(a, 'class') && !toggles.includes(a)), { kind: 'prop', name: 'class', expr: `__cl_classValue([${exprs.join(', ')}])`, start }];
35
+ }
36
+ }
37
+ foldClass(node.children, components);
38
+ }
39
+ else if (node.type === 'if')
40
+ for (const b of node.branches)
41
+ foldClass(b.children, components);
42
+ else if (node.type === 'for') {
43
+ foldClass(node.children, components);
44
+ if (node.empty)
45
+ foldClass(node.empty, components);
46
+ }
47
+ else if (node.type === 'fill')
48
+ foldClass(node.children, components);
49
+ else if (node.type === 'await')
50
+ for (const kids of awaitLists(node))
51
+ foldClass(kids, components);
52
+ }
53
+ }
@@ -8,7 +8,7 @@ export function emitClient(ir, hot) {
8
8
  const kinds = new Set(ir.signals.values());
9
9
  const all = walk(ir.nodes);
10
10
  const hasHoles = all.some((n) => n.kind === 'hole' && n.reactive);
11
- const hasBlocks = all.some((n) => n.kind === 'if' && n.block >= 0);
11
+ const hasBlocks = all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0);
12
12
  const hasFors = all.some((n) => n.kind === 'for' && n.block >= 0);
13
13
  const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
14
14
  const rendersHtml = hasBlocks || hasFors || hasRegions;
@@ -19,8 +19,10 @@ export function emitClient(ir, hot) {
19
19
  hasHoles && 'holes as __cl_holes',
20
20
  hasHoles && 'text as __cl_text',
21
21
  ir.events.length > 0 && 'on as __cl_on',
22
- all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
22
+ all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
23
+ all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
23
24
  hasBlocks && 'block as __cl_block',
25
+ all.some((n) => n.kind === 'await' && n.block >= 0) && 'awaited as __cl_awaited',
24
26
  hasFors && 'forBlock as __cl_for',
25
27
  all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
26
28
  hasRegions && 'region as __cl_region',
@@ -28,10 +30,13 @@ export function emitClient(ir, hot) {
28
30
  kinds.has('model') && 'modelInput as __cl_modelInput',
29
31
  ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
30
32
  rendersHtml && 'escape as __cl_escape',
31
- rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
33
+ rendersHtml && all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attrHtml as __cl_attrHtml',
34
+ rendersHtml && all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
32
35
  rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
33
36
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
34
37
  hasRegions && 'regionHtml as __cl_regionHtml',
38
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
39
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
35
40
  ].filter(Boolean);
36
41
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
37
42
  if (hot)
@@ -86,7 +91,9 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
86
91
  for (const h of [...holes].sort((a, b) => a.index - b.index))
87
92
  lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
88
93
  for (const a of nodes) {
89
- if (a.kind === 'attr' && a.reactive)
94
+ if (a.kind === 'attr' && a.reactive && a.name === '...')
95
+ lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
96
+ else if (a.kind === 'attr' && a.reactive)
90
97
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
91
98
  if (a.kind === 'connect')
92
99
  lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
@@ -108,6 +115,19 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
108
115
  const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
109
116
  lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
110
117
  }
118
+ if (n.kind === 'await' && n.block >= 0) {
119
+ const a = `__cl_a${n.block}`;
120
+ lines.push(`const ${a} = __cl_awaited(() => ${wrapExpr(rw.expr(n.expr))})`);
121
+ const named = (b, k) => {
122
+ if (!b)
123
+ return ` { html: () => "", wire: () => {} },`;
124
+ const plain = rw.without([b.name]);
125
+ const wire = wiring(ir, b.nodes, `${n.block}.${k}`, ctx, new Map([...signals].filter(([name]) => name !== b.name)), depth);
126
+ return ` { html: () => ((${b.name}) => ${htmlExpr(b.nodes, plain)})(${a}.v()), wire: ${fn('', wire.length ? [`const ${b.name} = ${a}.v()`, ...wire] : [])} },`;
127
+ };
128
+ const branches = [` { html: () => ${htmlExpr(n.pending, rw)}, wire: ${fn('', wiring(ir, n.pending, `${n.block}.0`, ctx, signals, depth))} },`, named(n.then, 1), named(n.catch, 2)];
129
+ lines.push(`__cl_block(${ctx}, ${n.block}, () => ${a}.k(), [\n${branches.join('\n')}\n ])`);
130
+ }
111
131
  if (n.kind === 'for' && n.block >= 0) {
112
132
  const rowCtx = `__cl_c${depth + 1}`;
113
133
  const names = rowNames(n, ir.events);
@@ -1,17 +1,24 @@
1
- import { htmlExpr, walk } from './html-expr.js';
1
+ import { asWritten, htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
3
  import { indentScript, inputsLine, renderName } from './shared.js';
4
4
  export function emitServer(ir, clientUrl, renderImports = false, loader) {
5
5
  const all = walk(ir.nodes);
6
+ const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null });
6
7
  const runtime = [
7
8
  'escape as __cl_escape',
8
9
  all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
9
10
  ir.stateful && 'island as __cl_island',
10
- all.some((n) => n.kind === 'attr') && 'attr as __cl_attrHtml',
11
- all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
11
+ all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attr as __cl_attrHtml',
12
+ all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
13
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
14
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
15
+ all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
16
+ all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
12
17
  all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
13
18
  all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
14
19
  loader && 'loaded as __cl_loaded',
20
+ html.includes('__cl_join(') && 'join as __cl_join',
21
+ html.includes('__cl_sync(') && 'sync as __cl_sync',
15
22
  ].filter(Boolean).join(', ');
16
23
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
17
24
  for (const imp of ir.imports)
@@ -20,9 +27,10 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
20
27
  out += `import ${d.clause} from '${d.from}'\n`;
21
28
  for (const line of ir.scriptImports)
22
29
  out += `${line}\n`;
23
- const html = htmlExpr(ir.nodes);
30
+ for (const line of ir.server?.imports ?? [])
31
+ out += `${line}\n`;
24
32
  const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
25
- out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
33
+ out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
26
34
  if (ir.stateful)
27
35
  out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
28
36
  else {
@@ -35,6 +43,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
35
43
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
36
44
  if (ir.script)
37
45
  out += indentScript(rewriteServer(ir.script));
46
+ if (ir.server)
47
+ out += indentScript(ir.server.body);
38
48
  out += ir.stateful
39
49
  ? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach, __cl_opts?.paths)\n`
40
50
  : ` return ${html}\n`;
@@ -8,11 +8,19 @@ export type Rewriter = {
8
8
  without(names: string[]): Rewriter;
9
9
  };
10
10
  export declare const asWritten: Rewriter;
11
- export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter): string;
11
+ /**
12
+ * Server output only (#430): `island` is the component's name when it's an island, null when it isn't. Outside
13
+ * islands, a level that calls a component or places a slot joins its parts with __cl_join (a string, or a promise
14
+ * when an awaiting component is in it); inside an island, a component call is checked not to be a promise.
15
+ */
16
+ export type ServerCtx = {
17
+ island: string | null;
18
+ };
19
+ export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter, ctx?: ServerCtx): string;
12
20
  /** `render_child({ props }, { slots })` for a component node. */
13
21
  export declare function componentCall(n: Extract<IRNode, {
14
22
  kind: 'component';
15
- }>, rw: Rewriter): string;
23
+ }>, rw: Rewriter, ctx?: ServerCtx): string;
16
24
  /** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
17
25
  export declare function whichExpr(n: Extract<IRNode, {
18
26
  kind: 'if';
@@ -2,38 +2,49 @@ import { FOR_IMPLICIT } from './parse.js';
2
2
  import { renderName } from './shared.js';
3
3
  import { wrapExpr } from './script.js';
4
4
  export const asWritten = { expr: (e) => e, without: () => asWritten };
5
- export function htmlExpr(nodes, rw = asWritten) {
5
+ const mayWait = (nodes) => walk(nodes).some((n) => n.kind === 'component' || n.kind === 'slot' || (n.kind === 'await' && n.block < 0));
6
+ export function htmlExpr(nodes, rw = asWritten, ctx) {
6
7
  const parts = nodes.map((n) => {
7
8
  if (n.kind === 'static')
8
9
  return JSON.stringify(n.html);
9
10
  if (n.kind === 'slot')
10
- return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
11
+ return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw, ctx)})` : '""'})`;
11
12
  if (n.kind === 'connect')
12
13
  return '""';
14
+ if (n.kind === 'attr' && n.name === '...')
15
+ return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
13
16
  if (n.kind === 'attr')
14
17
  return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
15
18
  if (n.kind === 'if') {
16
19
  if (n.block === -1) {
17
20
  const last = n.branches[n.branches.length - 1];
18
- let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw)})` : '""';
21
+ let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw, ctx)})` : '""';
19
22
  const conditional = last.cond === null ? n.branches.slice(0, -1) : n.branches;
20
23
  for (const b of [...conditional].reverse())
21
- expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw)}) : ${expr})`;
24
+ expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw, ctx)}) : ${expr})`;
22
25
  return expr;
23
26
  }
24
- const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw)}`).join(', ');
27
+ const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw, ctx)}`).join(', ');
25
28
  return `__cl_blockHtml(${n.block}, ${whichExpr(n, rw)}, [${branches}])`;
26
29
  }
30
+ if (n.kind === 'await') {
31
+ if (n.block >= 0)
32
+ return `__cl_blockHtml(${n.block}, 0, [() => ${htmlExpr(n.pending, rw, ctx)}])`;
33
+ const branch = (b) => (b ? `(${b.name}) => ${htmlExpr(b.nodes, rw.without([b.name]), ctx)}` : 'null');
34
+ return `__cl_awaitHtml(${wrapExpr(rw.expr(n.expr))}, ${branch(n.then)}, ${branch(n.catch)})`;
35
+ }
27
36
  if (n.kind === 'for') {
28
37
  const list = wrapExpr(rw.expr(n.list));
29
- const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
30
- const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
38
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
39
+ const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
31
40
  if (n.block >= 0)
32
41
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
33
- return `((__cl_l) => __cl_l.length ? __cl_l.map(${row}).join("") : ${n.empty ? `(${htmlExpr(n.empty, rw)})` : '""'})([...(${list} ?? [])])`;
42
+ const rows = ctx && !ctx.island && mayWait(n.nodes) ? `__cl_join(__cl_l.map(${row}))` : `__cl_l.map(${row}).join("")`;
43
+ return `((__cl_l) => __cl_l.length ? ${rows} : ${n.empty ? `(${htmlExpr(n.empty, rw, ctx)})` : '""'})([...(${list} ?? [])])`;
34
44
  }
35
45
  if (n.kind === 'component') {
36
- const call = componentCall(n, rw);
46
+ const plain = componentCall(n, rw, ctx);
47
+ const call = ctx?.island ? `__cl_sync(${plain}, ${JSON.stringify(n.name)}, ${JSON.stringify(ctx.island)})` : plain;
37
48
  return n.region >= 0 ? `__cl_regionHtml(${n.region}, () => ${call})` : call;
38
49
  }
39
50
  if (n.json)
@@ -41,13 +52,15 @@ export function htmlExpr(nodes, rw = asWritten) {
41
52
  const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
42
53
  return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
43
54
  });
55
+ if (ctx && !ctx.island && mayWait(nodes))
56
+ return `__cl_join([${parts.join(', ')}])`;
44
57
  return parts.length ? parts.join(' + ') : '""';
45
58
  }
46
- export function componentCall(n, rw) {
47
- const props = n.props.map((p) => `${p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ');
59
+ export function componentCall(n, rw, ctx) {
60
+ const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${p.name}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
48
61
  const slots = [
49
- ...(n.children.length ? [`"default": ${htmlExpr(n.children, rw)}`] : []),
50
- ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
62
+ ...(n.children.length ? [`"default": ${htmlExpr(n.children, rw, ctx)}`] : []),
63
+ ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw, ctx)}`),
51
64
  ];
52
65
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
53
66
  const opts = [...(n.attach ? [`attach: ${JSON.stringify(n.attach)}`] : []), ...(n.class ? [`class: ${JSON.stringify(n.class)}`] : []), ...(n.paths ? [`paths: { ${n.paths.map((p) => `${JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }`] : [])];
@@ -76,10 +89,11 @@ export function walk(nodes) {
76
89
  return nodes.flatMap((n) => [
77
90
  n,
78
91
  ...(n.kind === 'if' ? n.branches.flatMap((b) => walk(b.nodes))
79
- : n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
80
- : n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
81
- : n.kind === 'slot' ? walk(n.fallback)
82
- : []),
92
+ : n.kind === 'await' ? [...walk(n.pending), ...walk(n.then?.nodes ?? []), ...walk(n.catch?.nodes ?? [])]
93
+ : n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
94
+ : n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
95
+ : n.kind === 'slot' ? walk(n.fallback)
96
+ : []),
83
97
  ]);
84
98
  }
85
99
  const DERIVED = {
@@ -0,0 +1,24 @@
1
+ import type { IconLookup } from '../icons.ts';
2
+ import { ClarusError } from './errors.ts';
3
+ import { type ParsedFile, type TemplateNode } from './parse.ts';
4
+ /**
5
+ * Finds an icon by `set:name` for `<icon>`: `resolveIcon` from clarusjs/icons, bound to the file being compiled.
6
+ * @see https://clarusjs.com/guide/icons
7
+ */
8
+ export type IconResolver = (name: string) => IconLookup;
9
+ type Element = Extract<TemplateNode, {
10
+ type: 'element';
11
+ }>;
12
+ /** `<icon>` as the `<svg>` it renders and the body that goes inside it; throws a located error when it can't. */
13
+ export declare function iconElement(node: Element, file: string, source: string, icon: IconResolver | undefined): {
14
+ svg: Element;
15
+ body: string;
16
+ };
17
+ /**
18
+ * Every `<icon>` error in a file (lower() stops at the first): `clarusjs check` reports them all.
19
+ * @example
20
+ * checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, file)) // [ClarusError, …]
21
+ * @see https://clarusjs.com/guide/icons
22
+ */
23
+ export declare function checkIcons(parsed: ParsedFile, file: string, source: string, icon: IconResolver | undefined): ClarusError[];
24
+ export {};
@@ -0,0 +1,83 @@
1
+ import { ClarusError } from './errors.js';
2
+ import { awaitLists } from './parse.js';
3
+ const LABELS = new Set(['aria-label', 'aria-labelledby']);
4
+ export function iconElement(node, file, source, icon) {
5
+ const fail = (text) => { throw new ClarusError(text, file, source, node.start); };
6
+ const name = node.attrs.find((a) => a.name === 'name');
7
+ if (!name)
8
+ return fail('<icon> needs a name: <icon name="lucide:rocket" />');
9
+ if (name.kind !== 'static' || name.value === true)
10
+ return fail('a bound name: icons are chosen at build time; use @if between static icons');
11
+ if (node.children.some((c) => c.type !== 'text' || c.value.trim()))
12
+ return fail('<icon> takes no content');
13
+ if (!icon)
14
+ return fail('icons are resolved at build time: <icon> needs clarusjs/vite or clarusjs check (the playground has no icon sets)');
15
+ const id = name.value;
16
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id))
17
+ return fail(`<icon> name is set:icon, like lucide:rocket (got '${id}')`);
18
+ let found;
19
+ try {
20
+ found = icon(id);
21
+ }
22
+ catch (e) {
23
+ return fail(e.message);
24
+ }
25
+ if ('missing' in found) {
26
+ if (found.missing === 'set')
27
+ return fail(`no icon set '${found.set}': install it with pnpm add -D @iconify-json/${found.set}`);
28
+ const mean = found.suggestions.length ? ` (did you mean ${found.suggestions.map((s) => `'${s}'`).join(' or ')}?)` : '';
29
+ return fail(`no icon '${id.slice(found.set.length + 1)}' in ${found.set}${mean}`);
30
+ }
31
+ const { data } = found;
32
+ const own = node.attrs.filter((a) => a !== name);
33
+ const has = (n) => own.some((a) => a.name === n);
34
+ const at = node.start;
35
+ const fixed = (n, value) => (has(n) ? [] : [{ kind: 'static', name: n, value, start: at }]);
36
+ const a11y = has('role') || has('aria-hidden') ? [] : own.some((a) => LABELS.has(a.name)) ? fixed('role', 'img') : fixed('aria-hidden', 'true');
37
+ const attrs = [
38
+ ...fixed('xmlns', 'http://www.w3.org/2000/svg'),
39
+ ...fixed('width', `${+(data.width / data.height).toFixed(4)}em`),
40
+ ...fixed('height', '1em'),
41
+ ...fixed('viewBox', `${data.left} ${data.top} ${data.width} ${data.height}`),
42
+ ...a11y,
43
+ ...own,
44
+ ];
45
+ return { svg: { type: 'element', tag: 'svg', attrs, children: [], start: node.start }, body: data.body };
46
+ }
47
+ export function checkIcons(parsed, file, source, icon) {
48
+ const components = new Set(parsed.imports.map((i) => i.name));
49
+ const errors = [];
50
+ const walk = (nodes) => {
51
+ for (const node of nodes) {
52
+ if (node.type === 'element') {
53
+ if (node.tag === 'icon' && !components.has('icon')) {
54
+ try {
55
+ iconElement(node, file, source, icon);
56
+ }
57
+ catch (e) {
58
+ if (!(e instanceof ClarusError))
59
+ throw e;
60
+ errors.push(e);
61
+ }
62
+ continue;
63
+ }
64
+ walk(node.children);
65
+ }
66
+ else if (node.type === 'if')
67
+ for (const b of node.branches)
68
+ walk(b.children);
69
+ else if (node.type === 'for') {
70
+ walk(node.children);
71
+ if (node.empty)
72
+ walk(node.empty);
73
+ }
74
+ else if (node.type === 'fill')
75
+ walk(node.children);
76
+ else if (node.type === 'await')
77
+ for (const kids of awaitLists(node))
78
+ walk(kids);
79
+ }
80
+ };
81
+ walk(parsed.nodes);
82
+ return errors;
83
+ }
@@ -1,6 +1,8 @@
1
1
  import { ClarusError } from './errors.ts';
2
2
  export { ClarusError } from './errors.ts';
3
3
  export { parse } from './parse.ts';
4
+ export { checkIcons, type IconResolver } from './icon.ts';
5
+ import type { IconResolver } from './icon.ts';
4
6
  export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
5
7
  export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
6
8
  /**
@@ -22,6 +24,8 @@ export type CompileOptions = {
22
24
  collapseWhitespace?: boolean;
23
25
  loader?: string;
24
26
  hot?: string;
27
+ /** Finds `<icon name="set:name">` icons: `(name) => resolveIcon(name, file)` from clarusjs/icons. Without it, `<icon>` is an error. */
28
+ icon?: IconResolver;
25
29
  };
26
30
  /**
27
31
  * `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without