clarusjs 0.14.0 → 0.15.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/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +106 -5
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.js +2 -2
  9. package/dist/compiler/components.d.ts +32 -0
  10. package/dist/compiler/components.js +63 -0
  11. package/dist/compiler/emit-client.js +18 -3
  12. package/dist/compiler/emit-server.js +11 -8
  13. package/dist/compiler/html-expr.d.ts +2 -1
  14. package/dist/compiler/html-expr.js +15 -9
  15. package/dist/compiler/index.d.ts +13 -1
  16. package/dist/compiler/index.js +54 -1
  17. package/dist/compiler/ir.d.ts +20 -0
  18. package/dist/compiler/ir.js +78 -11
  19. package/dist/compiler/parse.d.ts +20 -0
  20. package/dist/compiler/parse.js +27 -10
  21. package/dist/compiler/script.d.ts +11 -0
  22. package/dist/compiler/script.js +41 -0
  23. package/dist/compiler/shared.d.ts +6 -0
  24. package/dist/compiler/shared.js +14 -0
  25. package/dist/forms/index.js +15 -3
  26. package/dist/runtime/attrs.d.ts +6 -0
  27. package/dist/runtime/attrs.js +16 -0
  28. package/dist/runtime/dom.d.ts +33 -1
  29. package/dist/runtime/dom.js +128 -23
  30. package/dist/runtime/html.d.ts +6 -0
  31. package/dist/runtime/html.js +12 -0
  32. package/dist/runtime/index.d.ts +1 -1
  33. package/dist/runtime/index.js +1 -1
  34. package/dist/runtime/loader.js +32 -6
  35. package/dist/runtime/router.d.ts +6 -1
  36. package/dist/runtime/router.js +1 -1
  37. package/dist/runtime/server.d.ts +8 -2
  38. package/dist/runtime/server.js +14 -7
  39. package/dist/server/handler.d.ts +28 -1
  40. package/dist/server/handler.js +44 -1
  41. package/dist/server/modes.d.ts +2 -0
  42. package/dist/server/modes.js +5 -1
  43. package/dist/vite/plugin.d.ts +19 -0
  44. package/dist/vite/plugin.js +46 -12
  45. package/package.json +1 -1
@@ -1,17 +1,14 @@
1
+ import { type ComponentNames } from '../compiler/components.ts';
1
2
  /**
2
3
  * [virtual offset, length, source offset, exact, source length]. Exact spans are verbatim copies (offsets map one to
3
4
  * one); other spans stand for a whole template construct (a component's tag, a binding's name): the source length
4
5
  * says how much of the template that is.
5
6
  */
6
7
  export type Mapping = [number, number, number, boolean, number?];
7
- /**
8
- * `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
9
- * the page's inputs. `componentSuffix`: added to component imports ('.ts' for `clarusjs check`'s generated files; ''
10
- * for the content mapper, where TypeScript resolves the .tscl file itself). `loaderSpan` is where that check sits in the generated code, so its errors can say so.
11
- */
12
8
  export declare function generateTs(source: string, file: string, options?: {
13
9
  loader?: string;
14
10
  componentSuffix?: string;
11
+ components?: ComponentNames;
15
12
  }): {
16
13
  code: string;
17
14
  mappings: Mapping[];
@@ -1,11 +1,38 @@
1
+ import { autoImport } from '../compiler/components.js';
2
+ import { parseExpressionAt } from 'acorn';
1
3
  import { routeFromFile } from '../server/handler.js';
2
4
  import { ClarusError } from '../compiler/errors.js';
3
5
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
4
- import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
6
+ import { providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
5
7
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
6
8
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
9
+ function patternNames(params) {
10
+ const names = [];
11
+ const walk = (p) => {
12
+ if (!p)
13
+ return;
14
+ if (p.type === 'Identifier')
15
+ names.push(p.name);
16
+ else if (p.type === 'ObjectPattern')
17
+ for (const prop of p.properties)
18
+ walk(prop.type === 'RestElement' ? prop.argument : prop.value);
19
+ else if (p.type === 'ArrayPattern')
20
+ p.elements.forEach(walk);
21
+ else if (p.type === 'AssignmentPattern')
22
+ walk(p.left);
23
+ else if (p.type === 'RestElement')
24
+ walk(p.argument);
25
+ };
26
+ try {
27
+ walk(parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' }).params[0]);
28
+ }
29
+ catch { }
30
+ return names;
31
+ }
7
32
  export function generateTs(source, file, options = {}) {
8
33
  const parsed = parse(source, file);
34
+ if (options.components)
35
+ autoImport(parsed, options.components, file, source);
9
36
  const mappings = [];
10
37
  let code = '';
11
38
  const emit = (text) => { code += text; };
@@ -33,7 +60,7 @@ export function generateTs(source, file, options = {}) {
33
60
  emit(` from ${JSON.stringify(t.from)}\n`);
34
61
  }
35
62
  for (const imp of parsed.imports)
36
- emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
63
+ emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
37
64
  for (const d of parsed.dataImports) {
38
65
  emit('import ');
39
66
  copy(d.clause, d.clauseStart);
@@ -42,6 +69,7 @@ export function generateTs(source, file, options = {}) {
42
69
  if (options.loader)
43
70
  emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
44
71
  const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
72
+ const provides = !!parsed.script && !!script && providesIn(script, file, source, parsed.script.start);
45
73
  if (parsed.script && script) {
46
74
  for (const imp of script.imports) {
47
75
  copy(imp.text, parsed.script.start + imp.start);
@@ -73,6 +101,20 @@ export function generateTs(source, file, options = {}) {
73
101
  emit('}\n');
74
102
  const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
75
103
  emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
104
+ emit('export interface Events {\n');
105
+ for (const e of parsed.events) {
106
+ emit(` ${JSON.stringify(e.name)}: `);
107
+ if (e.type === 'void')
108
+ emit('void');
109
+ else
110
+ copy(e.type, e.typeStart);
111
+ emit('\n');
112
+ }
113
+ emit('}\n');
114
+ if (provides)
115
+ emit('declare function provide(key: string, value: unknown): void\n');
116
+ if (parsed.events.length)
117
+ emit('declare const emit: <K extends keyof Events>(name: K, ...args: Events[K] extends void ? [value?: undefined, info?: { reason?: string; event?: Event }] : [value: Events[K], info?: { reason?: string; event?: Event }]) => boolean\n');
76
118
  let loaderSpan;
77
119
  if (options.loader) {
78
120
  emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
@@ -83,6 +125,9 @@ export function generateTs(source, file, options = {}) {
83
125
  emit('\n');
84
126
  }
85
127
  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');
128
+ emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : any\n');
129
+ emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
130
+ emit('export type __cl_Passed = { id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
86
131
  const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
87
132
  emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
88
133
  for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
@@ -101,6 +146,20 @@ export function generateTs(source, file, options = {}) {
101
146
  emit(' } = __cl_props\n');
102
147
  emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
103
148
  }
149
+ for (const c of parsed.contexts) {
150
+ emit(' const ');
151
+ copy(c.name, c.nameStart);
152
+ emit(': ');
153
+ copy(c.type, c.typeStart);
154
+ emit(' = ');
155
+ if (c.default !== undefined && c.defaultStart !== undefined)
156
+ copy(c.default, c.defaultStart);
157
+ else
158
+ emit('null!');
159
+ emit('\n');
160
+ }
161
+ if (parsed.contexts.length)
162
+ emit(` __cl_use([${parsed.contexts.map((c) => c.name).join(', ')}])\n`);
104
163
  const copyScript = (from, split) => {
105
164
  const body = split.body;
106
165
  const cuts = [
@@ -153,7 +212,13 @@ export function generateTs(source, file, options = {}) {
153
212
  case 'expr':
154
213
  return use(node.expr, node.start + 2);
155
214
  case 'fill':
156
- node.children.forEach(visit);
215
+ if (node.params !== undefined) {
216
+ emit(` { const [${node.params}]: any = []; __cl_use([${patternNames(node.params).join(', ')}])\n`);
217
+ node.children.forEach(visit);
218
+ emit(' }\n');
219
+ }
220
+ else
221
+ node.children.forEach(visit);
157
222
  return;
158
223
  case 'if':
159
224
  node.branches.forEach((b, i) => {
@@ -218,7 +283,7 @@ export function generateTs(source, file, options = {}) {
218
283
  if (component) {
219
284
  emit(' { const ');
220
285
  point('__cl_p', node.start, node.tag.length + 1);
221
- emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
286
+ emit(`: __cl_Readonly<${alias(node.tag)} & __cl_Passed> = { `);
222
287
  for (const a of node.attrs) {
223
288
  if (a.kind !== 'prop' || a.name !== '...')
224
289
  continue;
@@ -227,9 +292,24 @@ export function generateTs(source, file, options = {}) {
227
292
  emit('), ');
228
293
  }
229
294
  for (const a of node.attrs) {
295
+ if (a.kind === 'static' && a.name !== 'class' && a.name !== 'attach') {
296
+ const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
297
+ if (quoted)
298
+ emit('"');
299
+ copy(a.name, a.start);
300
+ if (quoted)
301
+ emit('"');
302
+ emit(`: ${a.value === true ? 'true' : JSON.stringify(a.value)}, `);
303
+ continue;
304
+ }
230
305
  if ((a.kind !== 'prop' && a.kind !== 'model') || a.name === '...')
231
306
  continue;
307
+ const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
308
+ if (quoted)
309
+ emit('"');
232
310
  copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
311
+ if (quoted)
312
+ emit('"');
233
313
  emit(': (');
234
314
  copy(a.expr, at(a.expr, attrValueStart(a)));
235
315
  emit('), ');
@@ -246,6 +326,19 @@ export function generateTs(source, file, options = {}) {
246
326
  copy(a.expr, at(a.expr, attrValueStart(a)));
247
327
  emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
248
328
  }
329
+ for (const a of node.attrs) {
330
+ if (a.kind !== 'event')
331
+ continue;
332
+ const name = JSON.stringify(a.name);
333
+ emit(' { const ');
334
+ point('__cl_ev', a.start, a.name.length + 2);
335
+ emit(`: keyof ${alias(node.tag)}_E = ${name}; __cl_use(__cl_ev) }\n`);
336
+ emit(` ;(($event: __cl_Ev<${alias(node.tag)}_E, ${name}>, $info: { reason?: string; event?: Event; cancel(): void }) => { `);
337
+ guarded();
338
+ emit('{ ');
339
+ copy(a.expr, at(a.expr, attrValueStart(a)));
340
+ emit(' } __cl_use($info) });\n');
341
+ }
249
342
  node.children.forEach(visit);
250
343
  return;
251
344
  }
@@ -257,6 +350,14 @@ export function generateTs(source, file, options = {}) {
257
350
  const radio = node.tag === 'input' && a.name === 'value' && type?.kind === 'static' && String(type.value).toLowerCase() === 'radio' && own?.kind === 'static';
258
351
  writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
259
352
  }
353
+ else if (a.kind === 'prop' && node.tag === 'slot') {
354
+ use(a.expr, attrValueStart(a));
355
+ }
356
+ else if (a.kind === 'prop' && a.name === 'use') {
357
+ emit(` ;((__cl_u: __cl_Use<__cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => __cl_use(__cl_u))((`);
358
+ copy(a.expr, at(a.expr, attrValueStart(a)));
359
+ emit('));\n');
360
+ }
260
361
  else if (a.kind === 'prop' && a.name === 'engine') {
261
362
  emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
262
363
  copy(a.expr, at(a.expr, attrValueStart(a)));
@@ -347,7 +448,7 @@ export function viewsDeclaration(views) {
347
448
  return lines.join('\n');
348
449
  }
349
450
  export function routesDeclaration(files) {
350
- const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
451
+ const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)[_+][^/]*$/.test(f));
351
452
  const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
352
453
  const entries = routes.map((route) => {
353
454
  const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
@@ -34,4 +34,8 @@ export declare function check(options: {
34
34
  lint?: LintConfig;
35
35
  lintRules?: LintRuleDef[];
36
36
  strict?: boolean;
37
+ components?: {
38
+ dirs?: string[];
39
+ auto?: boolean;
40
+ };
37
41
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
1
2
  import { spawnSync } from 'node:child_process';
2
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { createRequire } from 'node:module';
@@ -50,6 +51,7 @@ function typescriptDir(root, override) {
50
51
  }
51
52
  export function check(options) {
52
53
  const root = resolve(options.root);
54
+ const names = options.components?.auto === false ? undefined : componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), options.components?.dirs ?? COMPONENT_DIRS).names;
53
55
  const virtualRoot = resolve(root, VIRTUAL);
54
56
  rmSync(virtualRoot, { recursive: true, force: true });
55
57
  const diagnostics = [];
@@ -88,7 +90,7 @@ export function check(options) {
88
90
  };
89
91
  try {
90
92
  const loader = loaderOf(path);
91
- const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
93
+ const { code, mappings, loaderSpan } = generateTs(source, file, { ...(loader ? { loader } : {}), components: names });
92
94
  const vpath = resolve(virtualRoot, `${file}.ts`);
93
95
  mkdirSync(dirname(vpath), { recursive: true });
94
96
  writeFileSync(vpath, code);
@@ -1,9 +1,27 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
1
3
  import { generateTolerant } from '../check/generate.js';
4
+ import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
5
+ import { findClarusFiles } from '../vite/build.js';
2
6
  import { loaderOf } from './check.js';
7
+ function namesFor(fileName) {
8
+ let root = dirname(fileName);
9
+ while (!existsSync(resolve(root, 'package.json'))) {
10
+ if (dirname(root) === root)
11
+ return undefined;
12
+ root = dirname(root);
13
+ }
14
+ const files = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
15
+ const rel = (path) => { const r = relative(dirname(fileName), resolve(root, path.slice(1))).split(sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
16
+ const names = {};
17
+ for (const [name, path] of Object.entries(componentIndex(files, COMPONENT_DIRS).names))
18
+ names[name] = Array.isArray(path) ? path.map(rel) : rel(path);
19
+ return names;
20
+ }
3
21
  export function transform(params) {
4
22
  const { fileName, content } = params;
5
23
  const loader = loaderOf(fileName);
6
- const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', ...(loader ? { loader } : {}) });
24
+ const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', components: namesFor(fileName), ...(loader ? { loader } : {}) });
7
25
  const diagnostics = errors.slice(0, 1).map((e) => ({ messageText: e.message, start: e.offset, length: Math.min(1, content.length - e.offset), code: 1 }));
8
26
  if (!result)
9
27
  return { text: 'export {}\n', extension: '.ts', mappings: [], diagnostics };
@@ -5,6 +5,10 @@ type Project = {
5
5
  viteAliases: unknown;
6
6
  lint: LintConfig | undefined;
7
7
  lintRules: LintRuleDef[];
8
+ components?: {
9
+ dirs?: string[];
10
+ auto?: boolean;
11
+ };
8
12
  };
9
13
  export declare function loadProject(root: string): Promise<Project>;
10
14
  export {};
@@ -18,5 +18,5 @@ export async function loadProject(root) {
18
18
  if (!loaded)
19
19
  return none;
20
20
  const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
21
- return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [] };
21
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [], components: plugin?.api?.components };
22
22
  }
@@ -11,7 +11,7 @@ function part(a) {
11
11
  function foldStyle(node) {
12
12
  const props = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('style.'));
13
13
  const sources = node.attrs.filter((a) => isSource(a, 'style'));
14
- const spread = spreadOf(node);
14
+ const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
15
15
  if (!spread && !props.length && !(sources.length > 1 && sources.some((a) => a.kind === 'prop')))
16
16
  return;
17
17
  const exprs = [...(spread ? [`((${spread}) || {}).style`] : []), ...sources.map(part), ...props.map((p) => `{ ${JSON.stringify(p.name.slice(6))}: (${p.expr}) }`)];
@@ -27,7 +27,7 @@ export function foldClass(nodes, components) {
27
27
  const toggles = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('class.'));
28
28
  const sources = node.attrs.filter((a) => isSource(a, 'class'));
29
29
  const mixed = sources.length > 1 && sources.some((a) => a.kind === 'prop');
30
- const spread = spreadOf(node);
30
+ const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
31
31
  if (toggles.length || mixed || spread) {
32
32
  const exprs = [...(spread ? [`((${spread}) || {}).class`] : []), ...sources.map(part), ...toggles.map((t) => `{ ${JSON.stringify(t.name.slice(6))}: (${t.expr}) }`)];
33
33
  const start = (sources[0] ?? toggles[0] ?? node.attrs.find((a) => a.name === '...')).start;
@@ -0,0 +1,32 @@
1
+ import { type ParsedFile } from './parse.ts';
2
+ /**
3
+ * Tag name → the component's root path ('/src/components/forms/text-field.tscl'), or every candidate when ambiguous.
4
+ * @see https://clarusjs.com/guide/components#automatic-imports
5
+ */
6
+ export type ComponentNames = Record<string, string | string[]>;
7
+ /**
8
+ * Where automatic components live, by default (root-relative).
9
+ * @example
10
+ * componentIndex(files, COMPONENT_DIRS)
11
+ * @see https://clarusjs.com/guide/components#automatic-imports
12
+ */
13
+ export declare const COMPONENT_DIRS: string[];
14
+ /**
15
+ * Name every `.tscl` file under `dirs` (root-relative, posix): its full name is its folders and file joined with
16
+ * hyphens (`forms/text-field.tscl` → `forms-text-field`), its short name the file alone (`text-field`) when no other
17
+ * component has that name; a full name wins over a short one. Only names with a hyphen count, like custom elements,
18
+ * so a component never takes an HTML element's name. `skipped`: files that aren't kebab-case (never named).
19
+ * @example
20
+ * componentIndex(['src/components/forms/text-field.tscl'], ['src/components']).names
21
+ * // { 'forms-text-field': '/src/components/forms/text-field.tscl', 'text-field': '/src/components/forms/text-field.tscl' }
22
+ * @see https://clarusjs.com/guide/components#automatic-imports
23
+ */
24
+ export declare function componentIndex(files: string[], dirs: string[]): {
25
+ names: ComponentNames;
26
+ skipped: string[];
27
+ };
28
+ /**
29
+ * Add an import for each component tag the template uses that `names` knows and the file doesn't import itself (only
30
+ * those). A tag that names two components is a located error. Other hyphenated tags stay HTML (web components).
31
+ */
32
+ export declare function autoImport(parsed: ParsedFile, names: ComponentNames, file: string, source: string): void;
@@ -0,0 +1,63 @@
1
+ import { ClarusError } from './errors.js';
2
+ import { awaitLists } from './parse.js';
3
+ export const COMPONENT_DIRS = ['src/components', 'src/layouts'];
4
+ const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
5
+ export function componentIndex(files, dirs) {
6
+ const full = new Map();
7
+ const short = new Map();
8
+ const skipped = [];
9
+ const add = (map, name, path) => map.set(name, [...(map.get(name) ?? []), path]);
10
+ for (const file of [...files].sort()) {
11
+ const dir = dirs.find((d) => file.startsWith(`${d.replace(/\/+$/, '')}/`));
12
+ if (!dir || !file.endsWith('.tscl'))
13
+ continue;
14
+ const segments = file.slice(dir.replace(/\/+$/, '').length + 1, -'.tscl'.length).split('/');
15
+ if (!segments.every((s) => KEBAB.test(s))) {
16
+ skipped.push(file);
17
+ continue;
18
+ }
19
+ add(full, segments.join('-'), `/${file}`);
20
+ if (segments.length > 1)
21
+ add(short, segments.at(-1), `/${file}`);
22
+ }
23
+ const names = {};
24
+ for (const [name, paths] of short)
25
+ if (name.includes('-') && !full.has(name))
26
+ names[name] = paths.length === 1 ? paths[0] : paths;
27
+ for (const [name, paths] of full)
28
+ if (name.includes('-'))
29
+ names[name] = paths.length === 1 ? paths[0] : paths;
30
+ return { names, skipped };
31
+ }
32
+ export function autoImport(parsed, names, file, source) {
33
+ const imported = new Set(parsed.imports.map((i) => i.name));
34
+ const walk = (nodes) => {
35
+ for (const node of nodes) {
36
+ if (node.type === 'element') {
37
+ const found = node.tag.includes('-') && !imported.has(node.tag) ? names[node.tag] : undefined;
38
+ if (Array.isArray(found)) {
39
+ throw new ClarusError(`<${node.tag}> could be ${found.join(' or ')}: use its full name, or @import the one you mean`, file, source, node.start);
40
+ }
41
+ if (found) {
42
+ parsed.imports.push({ name: node.tag, from: found, start: 0 });
43
+ imported.add(node.tag);
44
+ }
45
+ walk(node.children);
46
+ }
47
+ else if (node.type === 'if')
48
+ for (const b of node.branches)
49
+ walk(b.children);
50
+ else if (node.type === 'for') {
51
+ walk(node.children);
52
+ if (node.empty)
53
+ walk(node.empty);
54
+ }
55
+ else if (node.type === 'fill')
56
+ walk(node.children);
57
+ else if (node.type === 'await')
58
+ for (const kids of awaitLists(node))
59
+ walk(kids);
60
+ }
61
+ };
62
+ walk(parsed.nodes);
63
+ }
@@ -1,7 +1,7 @@
1
1
  import { FOR_IMPLICIT } from './parse.js';
2
2
  import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
3
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
4
- import { indentScript, inputsLine, renderName } from './shared.js';
4
+ import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
5
5
  export function emitClient(ir, hot) {
6
6
  if (!ir.stateful)
7
7
  return 'export {}\n';
@@ -27,11 +27,15 @@ export function emitClient(ir, hot) {
27
27
  all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
28
28
  hasRegions && 'region as __cl_region',
29
29
  all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
30
+ all.some((n) => n.kind === 'component' && !!n.listens?.length) && 'listen as __cl_listen',
31
+ all.some((n) => n.kind === 'use') && 'use as __cl_useOn',
32
+ ir.sends && 'emit as __cl_emit',
33
+ ir.provides && 'provideOn as __cl_provideOn',
30
34
  kinds.has('model') && 'modelInput as __cl_modelInput',
31
35
  ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
32
36
  rendersHtml && 'escape as __cl_escape',
33
37
  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',
38
+ rendersHtml && all.some((n) => n.kind === 'attr' && n.name === '...' && !('expr' in n.value && n.value.expr === '__cl_attrs')) && 'spreadHtml as __cl_spreadHtml',
35
39
  rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
36
40
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
37
41
  hasRegions && 'regionHtml as __cl_regionHtml',
@@ -54,6 +58,11 @@ export function emitClient(ir, hot) {
54
58
  out += `${line}\n`;
55
59
  out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
56
60
  out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
61
+ if (ir.sends)
62
+ out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
63
+ out += contextLines(ir, 'undefined');
64
+ if (ir.provides)
65
+ out += ` __cl_provideOn(__cl_root, __cl_cx)\n`;
57
66
  const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
58
67
  const value = (i, from) => i.default === undefined ? `${from}.${i.name}` : `${from}.${i.name} === undefined ? (${rewriteClientExpr(i.default, ir.signals)}) : ${from}.${i.name}`;
59
68
  for (const i of inputs) {
@@ -97,6 +106,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
97
106
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
98
107
  if (a.kind === 'connect')
99
108
  lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
109
+ if (a.kind === 'use')
110
+ lines.push(`__cl_useOn(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
100
111
  }
101
112
  for (const e of ir.events.filter((ev) => ev.scope === scope)) {
102
113
  const body = rewriteClient(e.handler, signals).trim();
@@ -107,9 +118,13 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
107
118
  for (const n of nodes) {
108
119
  if (n.kind === 'component' && n.region >= 0) {
109
120
  const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
110
- lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
121
+ lines.push(`__cl_region(${ctx}, ${n.region}, (__cl_cx) => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))}, __cl_cx)`);
111
122
  for (const m of n.models ?? [])
112
123
  lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
124
+ for (const l of n.listens ?? []) {
125
+ const body = rewriteClient(l.handler, signals).trim();
126
+ lines.push(`__cl_listen(${ctx}, ${n.region}, ${JSON.stringify(l.name)}, ($event, $info) => { ${body}${body.includes('//') ? '\n ' : ' '}})`);
127
+ }
113
128
  }
114
129
  if (n.kind === 'if' && n.block >= 0) {
115
130
  const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
@@ -1,24 +1,27 @@
1
1
  import { asWritten, htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
- import { indentScript, inputsLine, renderName } from './shared.js';
3
+ import { contextLines, 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
+ const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null, top: true });
7
7
  const runtime = [
8
8
  'escape as __cl_escape',
9
9
  all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
10
10
  ir.stateful && 'island as __cl_island',
11
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',
12
+ html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
+ html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
13
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
14
15
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
15
16
  all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
16
17
  all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
17
18
  all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
18
19
  all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
20
+ all.some((n) => n.kind === 'slot') && 'slot as __cl_slot',
19
21
  loader && 'loaded as __cl_loaded',
20
22
  html.includes('__cl_join(') && 'join as __cl_join',
21
23
  html.includes('__cl_sync(') && 'sync as __cl_sync',
24
+ html.includes('__cl_attrs') && 'passed as __cl_passed',
22
25
  ].filter(Boolean).join(', ');
23
26
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
24
27
  for (const imp of ir.imports)
@@ -31,16 +34,16 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
31
34
  out += `${line}\n`;
32
35
  const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
33
36
  out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
34
- if (ir.stateful)
35
- out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
36
- else {
37
- out += unknownSlotCheck(ir);
37
+ out += unknownSlotCheck(ir);
38
+ if (!ir.stateful)
38
39
  out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
39
- }
40
40
  if (loader)
41
41
  out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
42
42
  out += inputsLine(ir);
43
43
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
44
+ if (html.includes('__cl_attrs'))
45
+ out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))})\n`;
46
+ out += contextLines(ir, '__cl_opts?.cx');
44
47
  if (ir.script)
45
48
  out += indentScript(rewriteServer(ir.script));
46
49
  if (ir.server)
@@ -15,8 +15,9 @@ export declare const asWritten: Rewriter;
15
15
  */
16
16
  export type ServerCtx = {
17
17
  island: string | null;
18
+ top?: boolean;
18
19
  };
19
- export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter, ctx?: ServerCtx): string;
20
+ export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter, top?: ServerCtx): string;
20
21
  /** `render_child({ props }, { slots })` for a component node. */
21
22
  export declare function componentCall(n: Extract<IRNode, {
22
23
  kind: 'component';
@@ -3,14 +3,20 @@ import { renderName } from './shared.js';
3
3
  import { wrapExpr } from './script.js';
4
4
  export const asWritten = { expr: (e) => e, without: () => asWritten };
5
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
+ export function htmlExpr(nodes, rw = asWritten, top) {
7
+ const ctx = top?.top ? { island: top.island } : top;
7
8
  const parts = nodes.map((n) => {
8
9
  if (n.kind === 'static')
9
10
  return JSON.stringify(n.html);
10
- if (n.kind === 'slot')
11
- return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw, ctx)})` : '""'})`;
12
- if (n.kind === 'connect')
11
+ if (n.kind === 'slot') {
12
+ const data = n.props.length ? `{ ${n.props.map((p) => `${p.name === '__proto__' ? '["__proto__"]' : p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }` : 'undefined';
13
+ const placed = `__cl_slot(__cl_slots?.[${JSON.stringify(n.name)}], ${data}, () => ${n.fallback.length ? htmlExpr(n.fallback, rw, ctx) : '""'}, __cl_cx)`;
14
+ return ctx?.island ? `__cl_join(["<!--[s-->", ${placed}, "<!--]s-->"])` : placed;
15
+ }
16
+ if (n.kind === 'connect' || n.kind === 'use')
13
17
  return '""';
18
+ if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
19
+ return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => /^(id|role|tabindex|hidden|lang|dir|(data|aria)-.+)$/.test(x)))})`;
14
20
  if (n.kind === 'attr' && n.name === '...')
15
21
  return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
16
22
  if (n.kind === 'attr')
@@ -52,18 +58,18 @@ export function htmlExpr(nodes, rw = asWritten, ctx) {
52
58
  const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
53
59
  return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
54
60
  });
55
- if (ctx && !ctx.island && mayWait(nodes))
61
+ if (ctx && (!ctx.island || (top?.top && nodes.some((n) => n.kind === 'slot'))) && mayWait(nodes))
56
62
  return `__cl_join([${parts.join(', ')}])`;
57
63
  return parts.length ? parts.join(' + ') : '""';
58
64
  }
59
65
  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(', ');
66
+ const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${/^[A-Za-z_$][\w$]*$/.test(p.name) ? p.name : JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
61
67
  const slots = [
62
- ...(n.children.length ? [`"default": ${htmlExpr(n.children, rw, ctx)}`] : []),
63
- ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw, ctx)}`),
68
+ ...(n.children.length ? [`"default": (_, __cl_cx) => ${htmlExpr(n.children, rw, ctx)}`] : []),
69
+ ...n.fills.map((f) => `${JSON.stringify(f.name)}: (${f.params ?? '_'}, __cl_cx) => ${htmlExpr(f.nodes, rw, ctx)}`),
64
70
  ];
65
71
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
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(', ')} }`] : [])];
72
+ const opts = ['cx: __cl_cx', ...(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(', ')} }`] : [])];
67
73
  if (opts.length)
68
74
  return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { ${opts.join(', ')} })`;
69
75
  return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
@@ -1,10 +1,12 @@
1
1
  import { ClarusError } from './errors.ts';
2
+ import { type ComponentNames } from './components.ts';
2
3
  export { ClarusError } from './errors.ts';
3
4
  export { parse } from './parse.ts';
5
+ export { componentIndex, COMPONENT_DIRS, type ComponentNames } from './components.ts';
4
6
  export { checkIcons, type IconResolver } from './icon.ts';
5
7
  import type { IconResolver } from './icon.ts';
6
8
  export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
7
- export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
9
+ export type { ParsedFile, InputDecl, EventDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
8
10
  /**
9
11
  * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
10
12
  * browser (a client route's page, or a component re-rendered inside an island).
@@ -16,6 +18,16 @@ export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './pa
16
18
  * @see https://clarusjs.com/reference/compiler#compile
17
19
  */
18
20
  export type CompileOptions = {
21
+ /**
22
+ * The page's layouts (#456), outermost first, as import specifiers: its folder and config layouts, which the plugin
23
+ * finds. The page's template is wrapped in them (each gets the route's `path` and `params`); `@layout none` skips them.
24
+ */
25
+ layouts?: string[];
26
+ /**
27
+ * Automatic imports (#458): tag names → component paths, from `componentIndex()`. A tag the template uses that's
28
+ * here and not imported by the file is imported; other hyphenated tags stay HTML.
29
+ */
30
+ components?: ComponentNames;
19
31
  file: string;
20
32
  target: 'server' | 'client';
21
33
  clientUrl?: string;