clarusjs 0.9.0 → 0.11.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 (61) hide show
  1. package/dist/check/generate.js +15 -8
  2. package/dist/cli/check.d.ts +7 -0
  3. package/dist/cli/check.js +14 -6
  4. package/dist/cli/explain.js +1 -1
  5. package/dist/cli/index.js +6 -3
  6. package/dist/cli/project.d.ts +7 -2
  7. package/dist/cli/project.js +4 -3
  8. package/dist/compiler/emit-client.d.ts +2 -1
  9. package/dist/compiler/emit-client.js +19 -7
  10. package/dist/compiler/emit-server.d.ts +1 -1
  11. package/dist/compiler/emit-server.js +4 -1
  12. package/dist/compiler/errors.d.ts +14 -1
  13. package/dist/compiler/html-expr.d.ts +21 -0
  14. package/dist/compiler/html-expr.js +24 -1
  15. package/dist/compiler/index.d.ts +23 -2
  16. package/dist/compiler/index.js +5 -3
  17. package/dist/compiler/ir.d.ts +6 -1
  18. package/dist/compiler/ir.js +104 -4
  19. package/dist/compiler/lint.d.ts +82 -0
  20. package/dist/compiler/lint.js +177 -0
  21. package/dist/compiler/parse.d.ts +34 -0
  22. package/dist/compiler/parse.js +11 -0
  23. package/dist/compiler/script.js +27 -0
  24. package/dist/fetch/index.d.ts +149 -0
  25. package/dist/fetch/index.js +312 -0
  26. package/dist/forms/index.d.ts +21 -2
  27. package/dist/forms/types.d.ts +20 -3
  28. package/dist/runtime/attrs.js +10 -2
  29. package/dist/runtime/dom.d.ts +15 -7
  30. package/dist/runtime/dom.js +33 -13
  31. package/dist/runtime/env.d.ts +8 -1
  32. package/dist/runtime/env.js +8 -1
  33. package/dist/runtime/hot.d.ts +2 -0
  34. package/dist/runtime/hot.js +51 -0
  35. package/dist/runtime/html.d.ts +9 -7
  36. package/dist/runtime/html.js +12 -7
  37. package/dist/runtime/navigate.d.ts +5 -0
  38. package/dist/runtime/navigation.d.ts +85 -13
  39. package/dist/runtime/navigation.js +77 -11
  40. package/dist/runtime/serialize.d.ts +1 -1
  41. package/dist/runtime/serialize.js +1 -1
  42. package/dist/runtime/server.d.ts +18 -1
  43. package/dist/runtime/server.js +42 -4
  44. package/dist/runtime/signals.d.ts +97 -4
  45. package/dist/runtime/signals.js +88 -4
  46. package/dist/server/handler.d.ts +115 -5
  47. package/dist/server/handler.js +233 -10
  48. package/dist/server/head.d.ts +4 -1
  49. package/dist/server/manifest.d.ts +14 -1
  50. package/dist/server/views.d.ts +64 -6
  51. package/dist/server/views.js +46 -0
  52. package/dist/vite/aliases.js +3 -3
  53. package/dist/vite/build.d.ts +2 -1
  54. package/dist/vite/build.js +1 -1
  55. package/dist/vite/manifest.d.ts +15 -0
  56. package/dist/vite/manifest.js +2 -2
  57. package/dist/vite/node.js +4 -1
  58. package/dist/vite/plugin.d.ts +47 -3
  59. package/dist/vite/plugin.js +197 -106
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +5 -1
@@ -1,6 +1,6 @@
1
1
  import { routeFromFile } from '../server/handler.js';
2
2
  import { ClarusError } from '../compiler/errors.js';
3
- import { parse } from '../compiler/parse.js';
3
+ import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
4
4
  import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
5
5
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
6
6
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
@@ -19,6 +19,7 @@ export function generateTs(source, file, options = {}) {
19
19
  emit('declare function derived<T>(fn: () => T): T\n');
20
20
  emit('declare function shared<T>(store: { get(): T }): T\n');
21
21
  emit('declare function __cl_use(value: unknown): void\n');
22
+ emit('declare const __cl_bool: boolean\n');
22
23
  const text = 'string | number | boolean | null | undefined';
23
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
25
  emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
@@ -118,13 +119,16 @@ export function generateTs(source, file, options = {}) {
118
119
  if (guards.length)
119
120
  emit(`\n // @ts-ignore\n if (${guards.join(' && ')})\n `);
120
121
  };
121
- const writable = (a) => {
122
+ const writable = (a, value) => {
122
123
  emit(' ;(() => { ');
123
124
  guarded();
124
- emit('(');
125
- copy(a.expr, at(a.expr, attrValueStart(a)));
126
- emit(') = (');
125
+ emit(value === undefined ? '(' : '');
127
126
  copy(a.expr, at(a.expr, attrValueStart(a)));
127
+ emit(value === undefined ? ') = (' : ' = (');
128
+ if (value === undefined)
129
+ copy(a.expr, at(a.expr, attrValueStart(a)));
130
+ else
131
+ emit(value);
128
132
  emit(') });\n');
129
133
  };
130
134
  function visit(node) {
@@ -158,11 +162,11 @@ export function generateTs(source, file, options = {}) {
158
162
  copy(node.item, node.itemStart);
159
163
  emit(' of ');
160
164
  copy(node.list, node.listStart);
161
- emit(') {\n const $index: number = 0; __cl_use($index)\n');
165
+ emit(') {\n const $index: number = 0, $count: number = 0, $first = __cl_bool, $last = __cl_bool, $even = __cl_bool, $odd = __cl_bool; __cl_use([$index, $count, $first, $last, $even, $odd])\n');
162
166
  if (node.track !== null)
163
167
  use(node.track, node.trackStart);
164
168
  const outer = guards.splice(0);
165
- guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, '$index']))));
169
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT]))));
166
170
  node.children.forEach(visit);
167
171
  guards.splice(0, guards.length, ...outer);
168
172
  emit(' }\n');
@@ -205,7 +209,10 @@ export function generateTs(source, file, options = {}) {
205
209
  for (const a of node.attrs) {
206
210
  if (a.kind === 'model') {
207
211
  use(a.expr, attrValueStart(a));
208
- writable(a);
212
+ const type = node.attrs.find((x) => x.kind === 'static' && x.name === 'type');
213
+ const own = node.attrs.find((x) => x.kind === 'static' && x.name === 'value');
214
+ const radio = node.tag === 'input' && a.name === 'value' && type?.kind === 'static' && String(type.value).toLowerCase() === 'radio' && own?.kind === 'static';
215
+ writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
209
216
  }
210
217
  else if (a.kind === 'prop' && a.name === 'engine') {
211
218
  emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
@@ -1,7 +1,10 @@
1
+ import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
2
+ /** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
1
3
  export type Diagnostic = {
2
4
  file: string;
3
5
  line: number;
4
6
  column: number;
7
+ severity: 'error' | 'warning';
5
8
  code: string;
6
9
  message: string;
7
10
  };
@@ -22,9 +25,13 @@ export type CheckSource = {
22
25
  addDependency(file: string): void;
23
26
  }): string;
24
27
  };
28
+ /** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too. */
25
29
  export declare function check(options: {
26
30
  root: string;
27
31
  typescript?: string;
28
32
  sources?: CheckSource[];
29
33
  viteAliases?: unknown;
34
+ lint?: LintConfig;
35
+ lintRules?: LintRuleDef[];
36
+ strict?: boolean;
30
37
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync,
3
3
  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
+ import { lint } from '../compiler/lint.js';
6
7
  import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
7
8
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
8
9
  import { projectAliases, resolveAlias } from '../vite/aliases.js';
@@ -65,10 +66,17 @@ export function check(options) {
65
66
  source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
66
67
  }
67
68
  catch (err) {
68
- diagnostics.push({ file, line: 1, column: 1, code: 'clarus', message: err.message });
69
+ diagnostics.push({ file, line: 1, column: 1, severity: 'error', code: 'clarus', message: err.message });
69
70
  continue;
70
71
  }
71
72
  views.push({ file, source });
73
+ if (!src) {
74
+ try {
75
+ for (const m of lint(source, file, options.lint, options.lintRules))
76
+ diagnostics.push({ file, line: m.line, column: m.column, severity: m.severity, code: m.rule, message: m.message });
77
+ }
78
+ catch { }
79
+ }
72
80
  try {
73
81
  const loader = loaderOf(path);
74
82
  const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
@@ -83,7 +91,7 @@ export function check(options) {
83
91
  const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
84
92
  const lines = source.split('\n');
85
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;
86
- diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), code: 'clarus', message });
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 });
87
95
  }
88
96
  }
89
97
  const appRoot = realpathSync(root);
@@ -168,7 +176,7 @@ export function check(options) {
168
176
  if (g?.fromPackage || (!g && (!resolve(path).startsWith(resolve(root) + sep) || path.includes(`${sep}node_modules${sep}`))))
169
177
  continue;
170
178
  if (!g) {
171
- diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
179
+ diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), severity: 'error', code: m[4], message: m[5] });
172
180
  continue;
173
181
  }
174
182
  const lines = g.code.split('\n');
@@ -179,13 +187,13 @@ export function check(options) {
179
187
  const at = source === null ? { line: 1, column: 1 } : position(g.original ?? g.source, source);
180
188
  const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
181
189
  const message = fromLoader ? `load() returns a value that doesn't fit this page's inputs: ${m[5]}` : source === null ? `${m[5]} (in generated code)` : m[5];
182
- diagnostics.push({ file: g.file, ...at, code: m[4], message });
190
+ diagnostics.push({ file: g.file, ...at, severity: 'error', code: m[4], message });
183
191
  }
184
192
  diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
185
193
  return {
186
194
  diagnostics,
187
- exitCode: diagnostics.length ? 1 : 0,
188
- text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} error ${d.code}: ${d.message}`).join('\n'),
195
+ exitCode: diagnostics.some((d) => d.severity === 'error' || options.strict) ? 1 : 0,
196
+ text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} ${d.severity} ${d.code}: ${d.message}`).join('\n'),
189
197
  json: JSON.stringify(diagnostics, null, 2),
190
198
  };
191
199
  }
@@ -13,7 +13,7 @@ function describe(path, r) {
13
13
  return [
14
14
  path,
15
15
  ...row('Rendered', ['on every request, by dist/server/index.mjs']),
16
- ...row('Data', [r.loader === 'request' ? 'load() runs on every request' : 'no loader']),
16
+ ...row('Data', [r.loader === 'request' ? `load() runs on every request${r.cookies ? ', and reads cookies' : ''}` : 'no loader']),
17
17
  ...row('Islands', ['decided per request']),
18
18
  ].join('\n');
19
19
  }
package/dist/cli/index.js CHANGED
@@ -7,16 +7,19 @@ import { serve } from './mapper.js';
7
7
  const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
8
8
  program
9
9
  .command('check')
10
- .description('type-check every .tscl file under src/ and every page (Markdown pages too), reporting errors where they are written')
10
+ .description('type-check and lint every .tscl file under src/ and every page (Markdown pages too), reporting each finding where it is written')
11
11
  .argument('[dir]', 'project folder', '.')
12
12
  .option('--json', 'print diagnostics as JSON')
13
+ .option('--strict', 'fail on lint warnings too')
13
14
  .action(async (dir, options) => {
14
- const result = check({ root: dir, ...(await loadProject(dir)) });
15
+ const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict });
15
16
  if (options.json)
16
17
  console.log(result.json);
17
18
  else if (result.diagnostics.length) {
19
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
20
+ const errors = result.diagnostics.filter((d) => d.severity === 'error').length;
18
21
  console.log(result.text);
19
- console.log(`\n${result.diagnostics.length} error${result.diagnostics.length === 1 ? '' : 's'}`);
22
+ console.log(`\n${[errors && count(errors, 'error'), result.diagnostics.length - errors && count(result.diagnostics.length - errors, 'warning')].filter(Boolean).join(', ')}`);
20
23
  }
21
24
  else
22
25
  console.log('No errors.');
@@ -1,5 +1,10 @@
1
1
  import type { CheckSource } from './check.ts';
2
- export declare function loadProject(root: string): Promise<{
2
+ import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
3
+ type Project = {
3
4
  sources: CheckSource[];
4
5
  viteAliases: unknown;
5
- }>;
6
+ lint: LintConfig | undefined;
7
+ lintRules: LintRuleDef[];
8
+ };
9
+ export declare function loadProject(root: string): Promise<Project>;
10
+ export {};
@@ -5,17 +5,18 @@ async function flatten(plugins) {
5
5
  return (await Promise.all(value.map(flatten))).flat();
6
6
  return value && typeof value === 'object' ? [value] : [];
7
7
  }
8
+ const none = { sources: [], viteAliases: undefined, lint: undefined, lintRules: [] };
8
9
  export async function loadProject(root) {
9
10
  let vite;
10
11
  try {
11
12
  vite = await import('vite');
12
13
  }
13
14
  catch {
14
- return { sources: [], viteAliases: undefined };
15
+ return none;
15
16
  }
16
17
  const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, resolve(root), 'silent');
17
18
  if (!loaded)
18
- return { sources: [], viteAliases: undefined };
19
+ return none;
19
20
  const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
20
- return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias };
21
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [] };
21
22
  }
@@ -1,2 +1,3 @@
1
1
  import type { ComponentIR } from './ir.ts';
2
- export declare function emitClient(ir: ComponentIR): string;
2
+ /** `hot`: in dev, the module that swaps a changed island in place (#53); its updates are accepted. */
3
+ export declare function emitClient(ir: ComponentIR, hot?: string): string;
@@ -1,7 +1,8 @@
1
- import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr } from './html-expr.js';
1
+ import { FOR_IMPLICIT } from './parse.js';
2
+ import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
2
3
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
3
4
  import { indentScript, inputsLine, renderName } from './shared.js';
4
- export function emitClient(ir) {
5
+ export function emitClient(ir, hot) {
5
6
  if (!ir.stateful)
6
7
  return 'export {}\n';
7
8
  const kinds = new Set(ir.signals.values());
@@ -21,6 +22,7 @@ export function emitClient(ir) {
21
22
  all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
22
23
  hasBlocks && 'block as __cl_block',
23
24
  hasFors && 'forBlock as __cl_for',
25
+ all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
24
26
  hasRegions && 'region as __cl_region',
25
27
  all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
26
28
  kinds.has('model') && 'modelInput as __cl_modelInput',
@@ -32,6 +34,8 @@ export function emitClient(ir) {
32
34
  hasRegions && 'regionHtml as __cl_regionHtml',
33
35
  ].filter(Boolean);
34
36
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
37
+ if (hot)
38
+ out += `import { swap as __cl_swap } from ${JSON.stringify(hot)}\n`;
35
39
  const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
36
40
  for (const imp of ir.imports) {
37
41
  if (usedComponents.has(imp.name))
@@ -58,9 +62,14 @@ export function emitClient(ir) {
58
62
  const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
59
63
  if (lines.length)
60
64
  out += '\n' + lines.map((l) => ` ${l}\n`).join('');
65
+ if (hot)
66
+ out += ` __cl_root.__cl_hot = () => ({ ${[...ir.signals].filter(([, kind]) => kind === 'state').map(([name]) => `${name}: ${name}.get()`).join(', ')} })\n`;
61
67
  if (inputs.length)
62
68
  out += ` return (__cl_p) => __cl_batch(() => {\n${inputs.map((i) => ` ${i.name}.${i.model ? 'own' : 'set'}(${value(i, '__cl_p')})\n`).join('')} })\n`;
63
- return out + '}\n';
69
+ out += '}\n';
70
+ if (hot)
71
+ out += `\nif (import.meta.hot) { import.meta.hot.accept(); if (import.meta.hot.data.cl) __cl_swap(import.meta.url); import.meta.hot.data.cl = 1 }\n`;
72
+ return out;
64
73
  }
65
74
  function rewriter(signals) {
66
75
  return {
@@ -101,11 +110,14 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
101
110
  }
102
111
  if (n.kind === 'for' && n.block >= 0) {
103
112
  const rowCtx = `__cl_c${depth + 1}`;
104
- const loop = [n.item, '$index'];
105
- const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state'])]);
106
- const plain = rw.without(loop);
113
+ const names = rowNames(n, ir.events);
114
+ const derivedNames = names.filter((x) => x !== '$count');
115
+ const loop = [n.item, '$index', ...(names.length ? ['$count'] : [])];
116
+ const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived'])]);
117
+ const plain = rw.without([n.item, ...FOR_IMPLICIT]);
107
118
  const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
108
- const row = `{\n html: (${n.item}, $index) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${n.item}, $index`, wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1))},\n }`;
119
+ const wire = [...rowDerived(n, ir.events), ...wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1)];
120
+ const row = `{\n html: (${rowParams(n)}) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${loop.join(', ')}`, wire)},\n }`;
109
121
  const empty = n.empty
110
122
  ? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
111
123
  : 'null';
@@ -1,2 +1,2 @@
1
1
  import type { ComponentIR } from './ir.ts';
2
- export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean): string;
2
+ export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean, loader?: string): string;
@@ -1,7 +1,7 @@
1
1
  import { htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
3
  import { indentScript, inputsLine, renderName } from './shared.js';
4
- export function emitServer(ir, clientUrl, renderImports = false) {
4
+ export function emitServer(ir, clientUrl, renderImports = false, loader) {
5
5
  const all = walk(ir.nodes);
6
6
  const runtime = [
7
7
  'escape as __cl_escape',
@@ -11,6 +11,7 @@ export function emitServer(ir, clientUrl, renderImports = false) {
11
11
  all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
12
12
  all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
13
13
  all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
14
+ loader && 'loaded as __cl_loaded',
14
15
  ].filter(Boolean).join(', ');
15
16
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
16
17
  for (const imp of ir.imports)
@@ -28,6 +29,8 @@ export function emitServer(ir, clientUrl, renderImports = false) {
28
29
  out += unknownSlotCheck(ir);
29
30
  out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
30
31
  }
32
+ if (loader)
33
+ out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
31
34
  out += inputsLine(ir);
32
35
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
33
36
  if (ir.script)
@@ -1,4 +1,17 @@
1
- /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
1
+ /**
2
+ * A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based), with the
3
+ * parts as `file`, `line` and `column`. `compile()` and `parse()` throw it; `compile()`'s warnings are ones too.
4
+ * @example
5
+ * ```ts
6
+ * try {
7
+ * compile(source, { file, target: 'server' })
8
+ * } catch (err) {
9
+ * if (err instanceof ClarusError) report(err.file, err.line, err.column, err.message)
10
+ * else throw err
11
+ * }
12
+ * ```
13
+ * @see https://clarusjs.com/reference/compiler#claruserror
14
+ */
2
15
  export declare class ClarusError extends Error {
3
16
  file: string;
4
17
  line: number;
@@ -27,3 +27,24 @@ export declare function tagArg(n: Extract<IRNode, {
27
27
  }>): string;
28
28
  /** Every node, including those inside @if branches, @for bodies and component children. */
29
29
  export declare function walk(nodes: IRNode[]): IRNode[];
30
+ /** The @for implicit names a row's template uses, besides `$index`: `$count` and those derived from it. */
31
+ export declare function rowNames(n: Extract<IRNode, {
32
+ kind: 'for';
33
+ }>, events?: {
34
+ handler: string;
35
+ scope?: string;
36
+ }[]): string[];
37
+ /**
38
+ * A row's parameters: the item and `$index`, then (when used) the list, `$count` and the names derived from them as
39
+ * default values, so every caller passes (item, index, list) and a plain Array.map works too.
40
+ */
41
+ export declare function rowParams(n: Extract<IRNode, {
42
+ kind: 'for';
43
+ }>): string;
44
+ /** In a row's wiring: the derived names, from the row's $index and the list's $count signals. */
45
+ export declare function rowDerived(n: Extract<IRNode, {
46
+ kind: 'for';
47
+ }>, events?: {
48
+ handler: string;
49
+ scope?: string;
50
+ }[]): string[];
@@ -1,3 +1,4 @@
1
+ import { FOR_IMPLICIT } from './parse.js';
1
2
  import { renderName } from './shared.js';
2
3
  import { wrapExpr } from './script.js';
3
4
  export const asWritten = { expr: (e) => e, without: () => asWritten };
@@ -25,7 +26,7 @@ export function htmlExpr(nodes, rw = asWritten) {
25
26
  }
26
27
  if (n.kind === 'for') {
27
28
  const list = wrapExpr(rw.expr(n.list));
28
- const row = `(${n.item}, $index) => ${htmlExpr(n.nodes, rw.without([n.item, '$index']))}`;
29
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
29
30
  const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
30
31
  if (n.block >= 0)
31
32
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
@@ -81,3 +82,25 @@ export function walk(nodes) {
81
82
  : []),
82
83
  ]);
83
84
  }
85
+ const DERIVED = {
86
+ $first: '$index === 0',
87
+ $last: '$index === $count - 1',
88
+ $even: '$index % 2 === 0',
89
+ $odd: '$index % 2 === 1',
90
+ };
91
+ export function rowNames(n, events = []) {
92
+ const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
93
+ const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
94
+ const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
95
+ const used = Object.keys(DERIVED).filter(has);
96
+ return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
97
+ }
98
+ export function rowParams(n) {
99
+ const names = rowNames(n);
100
+ if (!names.length)
101
+ return `${n.item}, $index`;
102
+ return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`)].join(', ');
103
+ }
104
+ export function rowDerived(n, events = []) {
105
+ return rowNames(n, events).filter((x) => x !== '$count').map((x) => `const ${x} = __cl_derived(() => ${DERIVED[x].replace(/\$index/g, '$index.get()').replace(/\$count/g, '$count.get()')})`);
106
+ }
@@ -1,22 +1,32 @@
1
1
  import { ClarusError } from './errors.ts';
2
2
  export { ClarusError } from './errors.ts';
3
3
  export { parse } from './parse.ts';
4
+ export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
4
5
  export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
5
6
  /**
6
7
  * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
7
8
  * browser (a client route's page, or a component re-rendered inside an island).
8
9
  */
9
- /** `scope`: the id that scopes this component's styles (default: from the file name). */
10
+ /**
11
+ * `compile()`'s options: the file (for errors and the style scope), the target (`'server'` renders HTML, `'client'`
12
+ * attaches an island), and for the server target the island's client URL.
13
+ * `scope`: the id that scopes this component's styles (default: from the file name).
14
+ * @see https://clarusjs.com/reference/compiler#compile
15
+ */
10
16
  export type CompileOptions = {
11
17
  file: string;
12
18
  target: 'server' | 'client';
13
19
  clientUrl?: string;
14
20
  renderImports?: boolean;
15
21
  scope?: string;
22
+ collapseWhitespace?: boolean;
23
+ loader?: string;
24
+ hot?: string;
16
25
  };
17
26
  /**
18
27
  * `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
19
28
  * <style>. `warnings`: things that compile but likely aren't meant (each a located ClarusError, not thrown).
29
+ * @see https://clarusjs.com/reference/compiler#compile
20
30
  */
21
31
  export type CompileResult = {
22
32
  code: string;
@@ -24,6 +34,17 @@ export type CompileResult = {
24
34
  css: string;
25
35
  warnings: ClarusError[];
26
36
  };
37
+ /**
38
+ * Compile a `.tscl` component: for the server, a module whose `render(props)` returns its HTML; for the client, an
39
+ * island's `attach(root, props)` (or `export {}` when it has no script). Pure: strings in, strings out. Throws a
40
+ * located `ClarusError` for a template it can't compile.
41
+ * @example
42
+ * ```ts
43
+ * import { compile } from 'clarusjs/compiler'
44
+ * const { code, css, stateful, warnings } = compile(source, { file: 'src/components/card.tscl', target: 'server', clientUrl: '/card.js' })
45
+ * ```
46
+ * @see https://clarusjs.com/reference/compiler#compile
47
+ */
27
48
  export declare function compile(source: string, options: CompileOptions): CompileResult;
28
- /** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
49
+ /** 'src/components/card.tscl' → 'card-<short hash of the path>'. @internal */
29
50
  export declare function scopeId(file: string): string;
@@ -5,6 +5,7 @@ import { lower } from './ir.js';
5
5
  import { parse } from './parse.js';
6
6
  export { ClarusError } from './errors.js';
7
7
  export { parse } from './parse.js';
8
+ export { lint, lintRules } from './lint.js';
8
9
  export function compile(source, options) {
9
10
  const parsed = parse(source, options.file);
10
11
  const warnings = [];
@@ -23,12 +24,13 @@ export function compile(source, options) {
23
24
  const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
24
25
  css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
25
26
  }
26
- const ir = lower(parsed, options.file, source);
27
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
28
+ warnings.push(...ir.warnings);
27
29
  if (options.target === 'client')
28
- return { code: emitClient(ir), stateful: ir.stateful, css, warnings };
30
+ return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
29
31
  if (ir.stateful && !options.clientUrl)
30
32
  throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
31
- return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css, warnings };
33
+ return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports, options.loader), stateful: ir.stateful, css, warnings };
32
34
  }
33
35
  export function scopeId(file) {
34
36
  let h = 0x811c9dc5;
@@ -1,3 +1,4 @@
1
+ import { ClarusError } from './errors.ts';
1
2
  import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
2
3
  import { type Signals } from './script.ts';
3
4
  export type IRNode = {
@@ -87,5 +88,9 @@ export type ComponentIR = {
87
88
  stateful: boolean;
88
89
  nodes: IRNode[];
89
90
  events: IREvent[];
91
+ /** Things that compile but likely aren't meant (located, not thrown). */
92
+ warnings: ClarusError[];
90
93
  };
91
- export declare function lower(parsed: ParsedFile, file: string, source: string): ComponentIR;
94
+ export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
95
+ collapseWhitespace?: boolean;
96
+ }): ComponentIR;