clarusjs 0.16.0 → 0.18.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 (64) hide show
  1. package/dist/check/generate.js +97 -8
  2. package/dist/cli/check.d.ts +3 -0
  3. package/dist/cli/check.js +55 -3
  4. package/dist/cli/explain.js +3 -0
  5. package/dist/cli/index.js +21 -3
  6. package/dist/cli/project.d.ts +5 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/emit-client.js +33 -8
  9. package/dist/compiler/events.d.ts +9 -0
  10. package/dist/compiler/events.js +46 -0
  11. package/dist/compiler/html-expr.js +14 -7
  12. package/dist/compiler/index.js +32 -5
  13. package/dist/compiler/ir.d.ts +15 -0
  14. package/dist/compiler/ir.js +87 -11
  15. package/dist/compiler/lint.d.ts +6 -2
  16. package/dist/compiler/lint.js +114 -5
  17. package/dist/compiler/loops.d.ts +13 -0
  18. package/dist/compiler/loops.js +49 -0
  19. package/dist/compiler/parse.d.ts +23 -0
  20. package/dist/compiler/parse.js +149 -1
  21. package/dist/compiler/script.d.ts +2 -0
  22. package/dist/compiler/script.js +78 -1
  23. package/dist/forms/index.js +35 -15
  24. package/dist/forms/types.d.ts +7 -0
  25. package/dist/node/serve.d.ts +26 -0
  26. package/dist/node/serve.js +150 -0
  27. package/dist/runtime/attrs.d.ts +13 -0
  28. package/dist/runtime/attrs.js +13 -0
  29. package/dist/runtime/dom.d.ts +32 -2
  30. package/dist/runtime/dom.js +170 -45
  31. package/dist/runtime/hot.js +3 -2
  32. package/dist/runtime/index.d.ts +2 -2
  33. package/dist/runtime/index.js +2 -2
  34. package/dist/runtime/loader.js +26 -7
  35. package/dist/runtime/motion.d.ts +59 -0
  36. package/dist/runtime/motion.js +339 -0
  37. package/dist/runtime/navigate.d.ts +2 -0
  38. package/dist/runtime/navigate.js +7 -1
  39. package/dist/runtime/navigation.d.ts +44 -0
  40. package/dist/runtime/navigation.js +69 -3
  41. package/dist/runtime/signals.d.ts +2 -0
  42. package/dist/runtime/signals.js +31 -0
  43. package/dist/seo.d.ts +140 -0
  44. package/dist/seo.js +64 -0
  45. package/dist/server/handler.d.ts +1 -0
  46. package/dist/server/handler.js +1 -0
  47. package/dist/server/head.js +5 -0
  48. package/dist/vite/cloudflare.d.ts +3 -0
  49. package/dist/vite/cloudflare.js +55 -0
  50. package/dist/vite/env.d.ts +19 -0
  51. package/dist/vite/env.js +34 -0
  52. package/dist/vite/headers.d.ts +27 -0
  53. package/dist/vite/headers.js +70 -0
  54. package/dist/vite/manifest.d.ts +11 -1
  55. package/dist/vite/manifest.js +10 -1
  56. package/dist/vite/netlify.d.ts +5 -2
  57. package/dist/vite/netlify.js +4 -2
  58. package/dist/vite/node.d.ts +4 -0
  59. package/dist/vite/node.js +9 -2
  60. package/dist/vite/plugin.d.ts +25 -2
  61. package/dist/vite/plugin.js +84 -9
  62. package/dist/vite/vercel.d.ts +3 -0
  63. package/dist/vite/vercel.js +53 -0
  64. package/package.json +14 -1
@@ -4,8 +4,10 @@ import { autoImport } from '../compiler/components.js';
4
4
  import { parseExpressionAt } from 'acorn';
5
5
  import { routeFromFile } from '../server/handler.js';
6
6
  import { ClarusError } from '../compiler/errors.js';
7
+ import { modifierError, splitEvent } from '../compiler/events.js';
8
+ import { outerIndexIn } from '../compiler/loops.js';
7
9
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
8
- import { providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
10
+ import { checkScript, providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
9
11
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
10
12
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
11
13
  function patternNames(params) {
@@ -31,8 +33,26 @@ function patternNames(params) {
31
33
  catch { }
32
34
  return names;
33
35
  }
36
+ function defaultedKeys(params) {
37
+ try {
38
+ const p = parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' }).params[0];
39
+ if (p.type !== 'ObjectPattern')
40
+ return [];
41
+ return p.properties.flatMap((x) => x.type === 'Property' && !x.computed && x.value?.type === 'AssignmentPattern'
42
+ ? [String(x.key.type === 'Identifier' ? x.key.name : x.key.value)] : []);
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
34
48
  export function generateTs(source, file, options = {}) {
35
49
  const parsed = parse(source, file);
50
+ const outer = outerIndexIn(parsed.nodes);
51
+ if (outer)
52
+ throw new ClarusError(outer.message, file, source, outer.start);
53
+ for (const s of [parsed.script, parsed.serverScript])
54
+ if (s)
55
+ checkScript(s.code, file, source, s.start);
36
56
  if (options.components)
37
57
  autoImport(parsed, options.components, file, source);
38
58
  const mappings = [];
@@ -49,6 +69,17 @@ export function generateTs(source, file, options = {}) {
49
69
  emit('declare function shared<T>(store: { get(): T }): T\n');
50
70
  emit('declare function __cl_use(value: unknown): void\n');
51
71
  emit('declare const __cl_bool: boolean\n');
72
+ const transitions = (nodes) => nodes.some((n) => {
73
+ if (n.type === 'if')
74
+ return !!n.transition || n.branches.some((b) => transitions(b.children));
75
+ if (n.type === 'for')
76
+ return !!n.transition || transitions(n.children) || (!!n.empty && transitions(n.empty));
77
+ if (n.type === 'await')
78
+ return transitions(n.pending) || (!!n.then && transitions(n.then.children)) || (!!n.catch && transitions(n.catch.children));
79
+ return 'children' in n && Array.isArray(n.children) && transitions(n.children);
80
+ });
81
+ if (transitions(parsed.nodes))
82
+ emit("declare function __cl_transition(name: string, options?: import('clarusjs/motion').TransitionOptions): void\n");
52
83
  const text = 'string | number | boolean | null | undefined';
53
84
  emit(`export type __cl_Class = ${text} | readonly __cl_Class[] | { [name: string]: unknown }\n`);
54
85
  emit(`export type __cl_Style = ${text} | __cl_Style[] | { [property: string]: ${text} }\n`);
@@ -62,7 +93,7 @@ export function generateTs(source, file, options = {}) {
62
93
  emit(` from ${JSON.stringify(t.from)}\n`);
63
94
  }
64
95
  for (const imp of parsed.imports)
65
- emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E, Attrs as ${alias(imp.name)}_A, DomEvents as ${alias(imp.name)}_D } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
96
+ emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E, Attrs as ${alias(imp.name)}_A, DomEvents as ${alias(imp.name)}_D, Slots as ${alias(imp.name)}_S } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
66
97
  for (const d of parsed.dataImports) {
67
98
  emit('import ');
68
99
  copy(d.clause, d.clauseStart);
@@ -134,6 +165,7 @@ export function generateTs(source, file, options = {}) {
134
165
  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');
135
166
  emit("export type __cl_Bubbling = Exclude<keyof HTMLElementEventMap, 'focus' | 'blur' | 'mouseenter' | 'mouseleave' | 'pointerenter' | 'pointerleave' | 'load' | 'error' | 'scroll' | 'scrollend' | 'toggle' | 'beforetoggle' | 'loadstart' | 'loadeddata' | 'loadedmetadata' | 'play' | 'pause' | 'ended'>\n");
136
167
  emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : any\n');
168
+ emit('export type __cl_SlotOf<S, K extends string> = K extends keyof S ? S[K] : any\n');
137
169
  emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
138
170
  emit('export type __cl_Passed = { class?: unknown; id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
139
171
  const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
@@ -212,6 +244,22 @@ export function generateTs(source, file, options = {}) {
212
244
  emit(value);
213
245
  emit(') });\n');
214
246
  };
247
+ let owner;
248
+ const slotVars = [];
249
+ const transitionCall = (tr) => {
250
+ if (!tr)
251
+ return;
252
+ emit(' __cl_transition(');
253
+ if (tr.name !== null)
254
+ copy(tr.name, tr.nameStart);
255
+ else
256
+ emit("'cl'");
257
+ if (tr.options !== null) {
258
+ emit(', ');
259
+ copy(tr.options, tr.optionsStart);
260
+ }
261
+ emit(')\n');
262
+ };
215
263
  function visit(node) {
216
264
  switch (node.type) {
217
265
  case 'text':
@@ -219,16 +267,26 @@ export function generateTs(source, file, options = {}) {
219
267
  return;
220
268
  case 'expr':
221
269
  return use(node.expr, node.start + 2);
222
- case 'fill':
270
+ case 'fill': {
271
+ const of = owner;
272
+ owner = undefined;
223
273
  if (node.params !== undefined) {
224
- emit(` { const [${node.params}]: any = []; __cl_use([${patternNames(node.params).join(', ')}])\n`);
274
+ const slot = of ? `__cl_SlotOf<${alias(of)}_S, ${JSON.stringify(node.name)}>` : 'any';
275
+ const own = defaultedKeys(node.params).map((k) => `${JSON.stringify(k)}?: any`);
276
+ const data = own.length && of ? `${slot} & Omit<{ ${own.join('; ')} }, keyof ${slot}>` : slot;
277
+ emit(' { const [');
278
+ copy(node.params, node.paramsStart);
279
+ emit(`]: [${data}, ...any[]] = null!; __cl_use([${patternNames(node.params).join(', ')}])\n`);
225
280
  node.children.forEach(visit);
226
281
  emit(' }\n');
227
282
  }
228
283
  else
229
284
  node.children.forEach(visit);
285
+ owner = of;
230
286
  return;
287
+ }
231
288
  case 'if':
289
+ transitionCall(node.transition);
232
290
  node.branches.forEach((b, i) => {
233
291
  if (b.cond === null)
234
292
  emit(' else {\n');
@@ -267,15 +325,18 @@ export function generateTs(source, file, options = {}) {
267
325
  return;
268
326
  }
269
327
  case 'for': {
328
+ transitionCall(node.transition);
270
329
  emit(' for (const ');
271
330
  copy(node.item, node.itemStart);
272
331
  emit(' of ');
273
332
  copy(node.list, node.listStart);
274
333
  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');
334
+ for (const a of node.aliases)
335
+ emit(` const ${a.name} = ${a.of}; __cl_use(${a.name})\n`);
275
336
  if (node.track !== null)
276
337
  use(node.track, node.trackStart);
277
338
  const outer = guards.splice(0);
278
- guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT]))));
339
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT, ...node.aliases.map((a) => a.name)]))));
279
340
  node.children.forEach(visit);
280
341
  guards.splice(0, guards.length, ...outer);
281
342
  emit(' }\n');
@@ -352,9 +413,27 @@ export function generateTs(source, file, options = {}) {
352
413
  copy(a.expr, at(a.expr, attrValueStart(a)));
353
414
  emit(' } __cl_use($info) });\n');
354
415
  }
416
+ const outer = owner;
417
+ owner = node.tag;
355
418
  node.children.forEach(visit);
419
+ owner = outer;
356
420
  return;
357
421
  }
422
+ if (node.tag === 'slot') {
423
+ const name = node.attrs.find((a) => a.kind === 'static' && a.name === 'name');
424
+ const key = name?.kind === 'static' && typeof name.value === 'string' ? name.value : 'default';
425
+ const v = `__cl_slot_${slotVars.length}`;
426
+ slotVars.push([key, v]);
427
+ emit(` var ${v} = { `);
428
+ for (const a of node.attrs) {
429
+ if (a.kind !== 'prop')
430
+ continue;
431
+ emit(`${JSON.stringify(a.name)}: (`);
432
+ copy(a.expr, at(a.expr, attrValueStart(a)));
433
+ emit('), ');
434
+ }
435
+ emit('};\n');
436
+ }
358
437
  for (const a of node.attrs) {
359
438
  if (a.kind === 'model') {
360
439
  use(a.expr, attrValueStart(a));
@@ -364,7 +443,7 @@ export function generateTs(source, file, options = {}) {
364
443
  writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
365
444
  }
366
445
  else if (a.kind === 'prop' && node.tag === 'slot') {
367
- use(a.expr, attrValueStart(a));
446
+ continue;
368
447
  }
369
448
  else if (a.kind === 'prop' && a.name === 'use') {
370
449
  emit(` ;((__cl_u: __cl_Use<__cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => __cl_use(__cl_u))((`);
@@ -387,7 +466,11 @@ export function generateTs(source, file, options = {}) {
387
466
  use(p.expr, p.start + 2);
388
467
  }
389
468
  else if (a.kind === 'event') {
390
- emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => { `);
469
+ const { type, mods } = splitEvent(a.name);
470
+ const wrong = modifierError(type, mods);
471
+ if (wrong)
472
+ throw new ClarusError(wrong, file, source, a.start);
473
+ emit(` ;(($event: __cl_Event<${JSON.stringify(type)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>, $values: Record<string, any>) => { `);
391
474
  guarded();
392
475
  emit('{ ');
393
476
  copy(a.expr, at(a.expr, attrValueStart(a)));
@@ -400,7 +483,12 @@ export function generateTs(source, file, options = {}) {
400
483
  }
401
484
  }
402
485
  parsed.nodes.forEach(visit);
486
+ const byName = new Map();
487
+ for (const [key, v] of slotVars)
488
+ byName.set(key, [...(byName.get(key) ?? []), `typeof ${v}`]);
489
+ emit(` return { __cl_slots: null! as { ${[...byName].map(([k, t]) => `${JSON.stringify(k)}: ${t.join(' | ')}`).join('; ')} } }\n`);
403
490
  emit('}\n');
491
+ emit('export type Slots = Awaited<ReturnType<typeof __cl_check>>[\'__cl_slots\']\n');
404
492
  return { code, mappings, loaderSpan };
405
493
  }
406
494
  export function toSourceOffset(mappings, virtualOffset) {
@@ -503,7 +591,8 @@ export function generateTolerant(source, file, options = {}) {
503
591
  text += closer;
504
592
  continue;
505
593
  }
506
- const from = /@|block|\( after|\(\s*$/.test(message) && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
594
+ const directive = !/^(script:|TypeScript syntax)/.test(message) && /@|block|\( after|\(\s*$/.test(message);
595
+ const from = directive && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
507
596
  const lineStart = text.lastIndexOf('\n', from - 1) + 1;
508
597
  const lineEnd = text.indexOf('\n', from) === -1 ? text.length : text.indexOf('\n', from);
509
598
  const blank = (from) => text.slice(0, from) + text.slice(from, lineEnd).replace(/[^\n]/g, ' ') + text.slice(lineEnd);
@@ -1,5 +1,6 @@
1
1
  import { type LibraryOption } from '../vite/libraries.ts';
2
2
  import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
3
+ import { type ModeTable } from '../server/modes.ts';
3
4
  /** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
4
5
  export type Diagnostic = {
5
6
  file: string;
@@ -42,4 +43,6 @@ export declare function check(options: {
42
43
  auto?: boolean;
43
44
  libraries?: LibraryOption[];
44
45
  };
46
+ envPrefix?: string | string[];
47
+ routes?: ModeTable;
45
48
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync,
4
4
  import { createRequire } from 'node:module';
5
5
  import { basename, dirname, relative, resolve, sep } from 'node:path';
6
6
  import { ClarusError } from '../compiler/errors.js';
7
+ import { compile } from '../compiler/index.js';
7
8
  import { applyFixes, lint } from '../compiler/lint.js';
8
9
  import { checkIcons } from '../compiler/icon.js';
9
10
  import { parse } from '../compiler/parse.js';
@@ -12,6 +13,7 @@ import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from
12
13
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
13
14
  import { projectAliases, resolveAlias } from '../vite/aliases.js';
14
15
  import { routeFromFile } from '../server/handler.js';
16
+ import { modeFor } from '../server/modes.js';
15
17
  const VIRTUAL = '.clarusjs/virtual';
16
18
  const posix = (path) => path.split(sep).join('/');
17
19
  function packageInfo(file) {
@@ -55,6 +57,7 @@ export function check(options) {
55
57
  const virtualRoot = resolve(root, VIRTUAL);
56
58
  rmSync(virtualRoot, { recursive: true, force: true });
57
59
  const diagnostics = [];
60
+ const compilerOnly = [];
58
61
  const generated = new Map();
59
62
  const sources = options.sources ?? [];
60
63
  const aliases = projectAliases(root, options.viteAliases);
@@ -62,6 +65,40 @@ export function check(options) {
62
65
  .filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
63
66
  const views = [];
64
67
  const fixed = [];
68
+ const readRaw = (p) => readFileSync(p, 'utf8');
69
+ const islands = pageFiles.filter((p) => {
70
+ if (!p.endsWith('.tscl'))
71
+ return false;
72
+ try {
73
+ const parsed = parse(readRaw(p), p);
74
+ return !!parsed.script || parsed.inputs.some((i) => i.model);
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ });
80
+ const inIslands = new Set();
81
+ for (const island of islands) {
82
+ const self = realpathSync(island);
83
+ try {
84
+ for (const f of reachableComponents(root, [island], readRaw, ['.tscl'], aliases, names))
85
+ if (f !== self)
86
+ inIslands.add(f);
87
+ }
88
+ catch { }
89
+ }
90
+ const pagesDir = resolve(root, 'src/pages') + sep;
91
+ for (const page of pageFiles) {
92
+ if (!page.endsWith('.tscl') || !page.startsWith(pagesDir))
93
+ continue;
94
+ if (modeFor(routeFromFile(`/${posix(relative(root, page))}`), options.routes ?? {}) !== 'client')
95
+ continue;
96
+ try {
97
+ for (const f of reachableComponents(root, [page], readRaw, ['.tscl'], aliases, names))
98
+ inIslands.add(f);
99
+ }
100
+ catch { }
101
+ }
65
102
  for (const path of pageFiles) {
66
103
  const file = posix(relative(root, path));
67
104
  const original = readFileSync(path, 'utf8');
@@ -70,7 +107,7 @@ export function check(options) {
70
107
  if (options.fix && path.endsWith('.tscl')) {
71
108
  let next = original;
72
109
  try {
73
- next = applyFixes(original, lint(original, file, options.lint, options.lintRules));
110
+ next = applyFixes(original, lint(original, file, options.lint, options.lintRules, { envPrefix: options.envPrefix }));
74
111
  }
75
112
  catch { }
76
113
  if (next !== original) {
@@ -95,7 +132,7 @@ export function check(options) {
95
132
  views.push({ file, source });
96
133
  if (!src) {
97
134
  try {
98
- for (const m of lint(source, file, options.lint, options.lintRules))
135
+ for (const m of lint(source, file, options.lint, options.lintRules, { envPrefix: options.envPrefix }))
99
136
  diagnostics.push({ file, line: m.line, column: m.column, severity: m.severity, code: m.rule, message: m.message });
100
137
  }
101
138
  catch { }
@@ -106,6 +143,7 @@ export function check(options) {
106
143
  const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
107
144
  diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
108
145
  };
146
+ let generatedOk = true;
109
147
  try {
110
148
  const loader = loaderOf(path);
111
149
  const { code, mappings, loaderSpan } = generateTs(source, file, { ...(loader ? { loader } : {}), components: names });
@@ -118,7 +156,19 @@ export function check(options) {
118
156
  if (!(err instanceof ClarusError))
119
157
  throw err;
120
158
  located(err);
159
+ generatedOk = false;
121
160
  }
161
+ if (generatedOk)
162
+ try {
163
+ compile(source, { file, target: 'client', components: names, icon: (name) => resolveIcon(name, path), renderImports: inIslands.has(realpathSync(path)) });
164
+ }
165
+ catch (err) {
166
+ if (!(err instanceof ClarusError))
167
+ throw err;
168
+ const before = diagnostics.length;
169
+ located(err);
170
+ compilerOnly.push(...diagnostics.splice(before));
171
+ }
122
172
  try {
123
173
  for (const err of checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, path)))
124
174
  located(err);
@@ -194,7 +244,7 @@ export function check(options) {
194
244
  rootDirs: ['..', './virtual'],
195
245
  paths,
196
246
  },
197
- include: ['../src', './virtual', './views.d.ts', './routes.d.ts'],
247
+ include: ['../src', './virtual', './views.d.ts', './routes.d.ts', './env.d.ts'],
198
248
  };
199
249
  const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
200
250
  mkdirSync(dirname(configPath), { recursive: true });
@@ -225,6 +275,8 @@ export function check(options) {
225
275
  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];
226
276
  diagnostics.push({ file: g.file, ...at, severity: 'error', code: m[4], message });
227
277
  }
278
+ const errorLines = new Set(diagnostics.filter((d) => d.severity === 'error').map((d) => `${d.file}:${d.line}`));
279
+ diagnostics.push(...compilerOnly.filter((d) => !errorLines.has(`${d.file}:${d.line}`)));
228
280
  diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
229
281
  return {
230
282
  diagnostics,
@@ -9,12 +9,14 @@ const WHEN = {
9
9
  const kb = (bytes) => (bytes ? `${(bytes / 1024).toFixed(1)} KB` : '0 KB');
10
10
  const row = (label, lines) => lines.map((l, i) => ` ${(i ? '' : label).padEnd(12)}${l}`);
11
11
  function describe(path, r) {
12
+ const parts = [...(r.layouts?.length ? row('Layouts', r.layouts) : []), ...(r.guards?.length ? row('Guards', r.guards) : [])];
12
13
  if (r.mode === 'server') {
13
14
  return [
14
15
  path,
15
16
  ...row('Rendered', ['on every request, by dist/server/index.mjs']),
16
17
  ...row('Data', [r.loader === 'request' ? `load() runs on every request${r.cookies ? ', and reads cookies' : ''}` : 'no loader']),
17
18
  ...row('Islands', ['decided per request']),
19
+ ...parts,
18
20
  ].join('\n');
19
21
  }
20
22
  const islands = r.islands.map((i) => `${i.component}${i.count > 1 ? ` ×${i.count}` : ''} (${kb(i.gzip)}, ${WHEN[i.attach]})`);
@@ -25,6 +27,7 @@ function describe(path, r) {
25
27
  ...row('Islands', islands.length ? islands : ['none']),
26
28
  ...row('JavaScript', [r.js.files.length ? `${kb(r.js.initialGzip)} on page load, ${kb(r.js.gzip)} in all (gzip, ${r.js.files.length} files)` : 'none']),
27
29
  ...row('CSS', [r.css.length ? r.css.join(', ') : 'none']),
30
+ ...parts,
28
31
  ].join('\n');
29
32
  }
30
33
  function table(routes) {
package/dist/cli/index.js CHANGED
@@ -3,7 +3,9 @@ import { Command } from 'commander';
3
3
  import { check } from './check.js';
4
4
  import { loadProject } from './project.js';
5
5
  import { explain } from './explain.js';
6
- import { serve } from './mapper.js';
6
+ import { serve as mapper } from './mapper.js';
7
+ import { serve } from '../node/serve.js';
8
+ import { writeEnvTypes } from '../vite/env.js';
7
9
  const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
8
10
  program
9
11
  .command('check')
@@ -13,7 +15,10 @@ program
13
15
  .option('--strict', 'fail on lint warnings too')
14
16
  .option('--fix', 'apply lint fixes to the .tscl files (wrapping a component\'s several roots in <fragment>, …) before checking')
15
17
  .action(async (dir, options) => {
16
- const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict, fix: options.fix });
18
+ const project = await loadProject(dir);
19
+ if (project.env)
20
+ writeEnvTypes(dir, project.env);
21
+ const result = check({ root: dir, ...project, strict: options.strict, fix: options.fix });
17
22
  for (const file of result.fixed ?? [])
18
23
  (options.json ? console.error : console.log)(`fixed ${file}`);
19
24
  if (options.json)
@@ -45,5 +50,18 @@ program
45
50
  program
46
51
  .command('mapper')
47
52
  .description('the TypeScript 7.1 content mapper for .tscl files (TypeScript starts it; see https://clarusjs.com/guide/editor)')
48
- .action(() => serve());
53
+ .action(() => mapper());
54
+ program
55
+ .command('serve')
56
+ .description('serve a built site (vite build first) on Node: its files, server routes and _headers; for any Node host or a container')
57
+ .argument('[dir]', 'project folder', '.')
58
+ .option('--port <port>', 'port (default: $PORT, else 3000)')
59
+ .option('--host <host>', 'interface (default: $HOST, else 0.0.0.0)')
60
+ .action(async (dir, options) => {
61
+ const server = await serve({ root: dir, port: options.port === undefined ? undefined : Number(options.port), host: options.host });
62
+ const address = server.address();
63
+ console.log(`clarusjs: serving ${dir} at http://${typeof address === 'object' && address ? `${address.address === '0.0.0.0' ? 'localhost' : address.address}:${address.port}` : address}/`);
64
+ for (const signal of ['SIGTERM', 'SIGINT'])
65
+ process.once(signal, () => server.close(() => process.exit(0)));
66
+ });
49
67
  program.parse();
@@ -1,4 +1,6 @@
1
1
  import type { LibraryOption } from '../vite/libraries.ts';
2
+ import type { EnvOption } from '../vite/env.ts';
3
+ import type { ModeTable } from '../server/modes.ts';
2
4
  import type { CheckSource } from './check.ts';
3
5
  import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
4
6
  type Project = {
@@ -11,6 +13,9 @@ type Project = {
11
13
  auto?: boolean;
12
14
  libraries?: LibraryOption[];
13
15
  };
16
+ env?: EnvOption;
17
+ envPrefix?: string | string[];
18
+ routes?: ModeTable;
14
19
  };
15
20
  export declare function loadProject(root: string): Promise<Project>;
16
21
  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 ?? [], components: plugin?.api?.components };
21
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [], components: plugin?.api?.components, env: plugin?.api?.env, envPrefix: loaded.config.envPrefix, routes: plugin?.api?.routes };
22
22
  }
@@ -1,3 +1,4 @@
1
+ import { guardCode } from './events.js';
1
2
  import { FOR_IMPLICIT } from './parse.js';
2
3
  import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
4
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
@@ -19,13 +20,15 @@ export function emitClient(ir, hot) {
19
20
  hasHoles && 'holes as __cl_holes',
20
21
  hasHoles && 'text as __cl_text',
21
22
  ir.events.length > 0 && 'on as __cl_on',
23
+ ir.events.some((e) => /\$values\b/.test(e.handler)) && 'values as __cl_values',
22
24
  all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
23
25
  all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
24
- hasBlocks && 'block as __cl_block',
26
+ all.some((n) => ((n.kind === 'if' && !n.transition) || n.kind === 'await') && n.block >= 0) && 'block as __cl_block',
25
27
  all.some((n) => n.kind === 'await' && n.block >= 0) && 'awaited as __cl_awaited',
26
- hasFors && 'forBlock as __cl_for',
28
+ all.some((n) => n.kind === 'for' && !n.transition && n.block >= 0) && 'forBlock as __cl_for',
27
29
  all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
28
30
  hasRegions && 'region as __cl_region',
31
+ all.some((n) => n.kind === 'component' && (n.children.length > 0 || n.fills.some((f) => !f.params))) && 'untrack as __cl_untrack',
29
32
  all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
30
33
  all.some((n) => n.kind === 'component' && !!n.listens?.length) && 'listen as __cl_listen',
31
34
  all.some((n) => n.kind === 'use') && 'use as __cl_useOn',
@@ -44,6 +47,12 @@ export function emitClient(ir, hot) {
44
47
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
45
48
  ].filter(Boolean);
46
49
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
50
+ const motion = [
51
+ all.some((n) => n.kind === 'if' && n.transition && n.block >= 0) && 'transitionBlock as __cl_tb',
52
+ all.some((n) => n.kind === 'for' && n.transition && n.block >= 0) && 'transitionFor as __cl_tf',
53
+ ].filter(Boolean);
54
+ if (motion.length)
55
+ out += `import { ${motion.join(', ')} } from 'clarusjs/motion'\n`;
47
56
  if (hot)
48
57
  out += `import { swap as __cl_swap } from ${JSON.stringify(hot)}\n`;
49
58
  const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
@@ -113,9 +122,13 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
113
122
  lines.push(`__cl_useOn(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
114
123
  }
115
124
  for (const e of ir.events.filter((ev) => ev.scope === scope)) {
116
- const body = rewriteClient(e.handler, signals).trim();
125
+ let body = rewriteClient(e.handler, signals).trim();
126
+ if (/\$values\b/.test(e.handler) && !/\b(?:const|let|var)\s+\$values\b/.test(e.handler))
127
+ body = `const $values = __cl_values(__cl_el, $event); ${body}`;
128
+ const guard = guardCode(e.mods ?? []);
117
129
  const end = body.includes('//') ? '\n ' : ' ';
118
- lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
130
+ const fn = `(${/__cl_el\b/.test(guard + body) ? '$event, __cl_el' : '$event'}) => { ${guard}${body}${end}}`;
131
+ lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ${e.mods?.some((m) => m.toLowerCase() === 'once') ? `((__cl_done) => ${fn})(false)` : fn})`);
119
132
  }
120
133
  const fn = (args, inner) => inner.length ? `(${args}) => {\n${inner.map((l) => ` ${l}`).join('\n')}\n }` : `(${args}) => {}`;
121
134
  for (const n of nodes) {
@@ -133,7 +146,12 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
133
146
  }
134
147
  if (n.kind === 'if' && n.block >= 0) {
135
148
  const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
136
- lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
149
+ if (n.transition) {
150
+ const arg = (x, none) => (x === null ? none : wrapExpr(rw.expr(x)));
151
+ lines.push(`__cl_tb(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ], ${arg(n.transition.name, '"cl"')}, ${arg(n.transition.options, 'undefined')})`);
152
+ }
153
+ else
154
+ lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
137
155
  }
138
156
  if (n.kind === 'await' && n.block >= 0) {
139
157
  const a = `__cl_a${n.block}`;
@@ -153,15 +171,22 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
153
171
  const names = rowNames(n, ir.events);
154
172
  const derivedNames = names.filter((x) => x !== '$count');
155
173
  const loop = [n.item, '$index', ...(names.length ? ['$count'] : [])];
156
- const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived'])]);
157
- const plain = rw.without([n.item, ...FOR_IMPLICIT]);
174
+ const aliasKind = (of) => (of === '$index' || of === '$count' ? 'state' : 'derived');
175
+ const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived']), ...n.aliases.map((a) => [a.name, aliasKind(a.of)])]);
176
+ const plain = rw.without([n.item, ...FOR_IMPLICIT, ...n.aliases.map((a) => a.name)]);
158
177
  const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
159
178
  const wire = [...rowDerived(n, ir.events), ...wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1)];
160
179
  const row = `{\n html: (${rowParams(n)}) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${loop.join(', ')}`, wire)},\n }`;
161
180
  const empty = n.empty
162
181
  ? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
163
182
  : 'null';
164
- lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${n.item}, $index) => ${key}, ${row}, ${empty})`);
183
+ const keyParams = [n.item, '$index', ...n.aliases.filter((a) => a.of === '$index').map((a) => `${a.name} = $index`)].join(', ');
184
+ if (n.transition) {
185
+ const arg = (x, none) => (x === null ? none : wrapExpr(rw.expr(x)));
186
+ lines.push(`__cl_tf(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${keyParams}) => ${key}, ${row}, ${empty}, ${arg(n.transition.name, '"cl"')}, ${arg(n.transition.options, 'undefined')})`);
187
+ }
188
+ else
189
+ lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${keyParams}) => ${key}, ${row}, ${empty})`);
165
190
  }
166
191
  }
167
192
  return lines;
@@ -0,0 +1,9 @@
1
+ /** (name.mods): the event type, and its modifiers in the order written. */
2
+ export declare function splitEvent(name: string): {
3
+ type: string;
4
+ mods: string[];
5
+ };
6
+ /** Why a modifier list is wrong for this event, or null. */
7
+ export declare function modifierError(type: string, mods: string[]): string | null;
8
+ /** The guard: keys and .self first (a miss does nothing), then .once (`__cl_done`), .prevent, .stop. */
9
+ export declare function guardCode(mods: string[]): string;
@@ -0,0 +1,46 @@
1
+ const KEYS = {
2
+ enter: 'Enter', esc: 'Escape', escape: 'Escape', space: ' ', tab: 'Tab',
3
+ up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',
4
+ delete: 'Delete', backspace: 'Backspace', home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown',
5
+ };
6
+ const SYSTEM = ['ctrl', 'shift', 'alt', 'meta'];
7
+ const KEY_EVENTS = new Set(['keydown', 'keyup', 'keypress']);
8
+ const ORDER = ['prevent', 'stop', 'self', 'once'];
9
+ export function splitEvent(name) {
10
+ const [type, ...mods] = name.split('.');
11
+ return { type: type, mods };
12
+ }
13
+ export function modifierError(type, mods) {
14
+ for (const m of mods) {
15
+ const key = m.toLowerCase();
16
+ if (ORDER.includes(key))
17
+ continue;
18
+ if (KEYS[key] || SYSTEM.includes(key) || /^[a-z0-9]$/.test(key)) {
19
+ if (!KEY_EVENTS.has(type))
20
+ return `.${m} is a key: for (keydown) and (keyup)`;
21
+ continue;
22
+ }
23
+ return `unknown modifier .${m}: use ${ORDER.join(', ')}, a key (enter, esc, space, tab, up, down, left, right, a letter…) or ctrl, shift, alt, meta`;
24
+ }
25
+ return null;
26
+ }
27
+ export function guardCode(mods) {
28
+ const keys = mods.map((m) => m.toLowerCase());
29
+ const tests = [];
30
+ const named = keys.filter((k) => KEYS[k] || /^[a-z0-9]$/.test(k));
31
+ if (named.length)
32
+ tests.push(`(${named.map((k) => (KEYS[k] ? `$event.key === ${JSON.stringify(KEYS[k])}` : `$event.key?.toLowerCase() === ${JSON.stringify(k)}`)).join(' || ')})`);
33
+ for (const s of SYSTEM)
34
+ if (keys.includes(s))
35
+ tests.push(`$event.${s}Key`);
36
+ if (keys.includes('self'))
37
+ tests.push('$event.target === __cl_el');
38
+ let code = tests.length ? `if (!(${tests.join(' && ')})) return; ` : '';
39
+ if (keys.includes('once'))
40
+ code += 'if (__cl_done) return; __cl_done = true; ';
41
+ if (keys.includes('prevent'))
42
+ code += '$event.preventDefault(); ';
43
+ if (keys.includes('stop'))
44
+ code += '$event.stopPropagation(); ';
45
+ return code;
46
+ }