clarusjs 0.8.1 → 0.10.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.d.ts +20 -4
  2. package/dist/check/generate.js +157 -21
  3. package/dist/cli/check.d.ts +13 -0
  4. package/dist/cli/check.js +65 -18
  5. package/dist/cli/index.js +9 -3
  6. package/dist/cli/mapper.d.ts +25 -0
  7. package/dist/cli/mapper.js +65 -0
  8. package/dist/cli/project.d.ts +5 -0
  9. package/dist/cli/project.js +21 -0
  10. package/dist/compiler/emit-client.js +33 -9
  11. package/dist/compiler/emit-server.js +3 -2
  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 +29 -3
  15. package/dist/compiler/index.d.ts +28 -3
  16. package/dist/compiler/index.js +36 -24
  17. package/dist/compiler/ir.d.ts +19 -1
  18. package/dist/compiler/ir.js +261 -11
  19. package/dist/compiler/parse.d.ts +52 -1
  20. package/dist/compiler/parse.js +145 -6
  21. package/dist/compiler/script.d.ts +22 -1
  22. package/dist/compiler/script.js +108 -5
  23. package/dist/fetch/index.d.ts +149 -0
  24. package/dist/fetch/index.js +312 -0
  25. package/dist/forms/index.d.ts +26 -0
  26. package/dist/forms/index.js +374 -0
  27. package/dist/forms/types.d.ts +111 -0
  28. package/dist/forms/types.js +1 -0
  29. package/dist/runtime/attrs.js +10 -2
  30. package/dist/runtime/dom.d.ts +26 -11
  31. package/dist/runtime/dom.js +102 -14
  32. package/dist/runtime/env.d.ts +14 -0
  33. package/dist/runtime/env.js +14 -0
  34. package/dist/runtime/html.d.ts +9 -7
  35. package/dist/runtime/html.js +12 -7
  36. package/dist/runtime/index.d.ts +3 -2
  37. package/dist/runtime/index.js +3 -2
  38. package/dist/runtime/loader.d.ts +1 -1
  39. package/dist/runtime/loader.js +36 -5
  40. package/dist/runtime/navigate.d.ts +5 -0
  41. package/dist/runtime/navigation.d.ts +85 -13
  42. package/dist/runtime/navigation.js +77 -11
  43. package/dist/runtime/router.js +10 -1
  44. package/dist/runtime/serialize.d.ts +1 -1
  45. package/dist/runtime/serialize.js +1 -1
  46. package/dist/runtime/server.d.ts +9 -2
  47. package/dist/runtime/server.js +23 -5
  48. package/dist/runtime/signals.d.ts +98 -3
  49. package/dist/runtime/signals.js +112 -6
  50. package/dist/server/handler.d.ts +14 -1
  51. package/dist/server/handler.js +2 -2
  52. package/dist/server/head.d.ts +4 -1
  53. package/dist/server/manifest.d.ts +14 -1
  54. package/dist/server/views.d.ts +64 -6
  55. package/dist/server/views.js +46 -0
  56. package/dist/vite/build.d.ts +1 -1
  57. package/dist/vite/manifest.d.ts +12 -0
  58. package/dist/vite/plugin.d.ts +30 -2
  59. package/dist/vite/plugin.js +17 -2
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +19 -1
@@ -1,14 +1,17 @@
1
1
  /**
2
- * [virtual offset, length, source offset, exact]. Exact spans are verbatim copies (offsets map one to one); other
3
- * spans stand for a whole template construct and map to its start.
2
+ * [virtual offset, length, source offset, exact, source length]. Exact spans are verbatim copies (offsets map one to
3
+ * one); other spans stand for a whole template construct (a component's tag, a binding's name): the source length
4
+ * says how much of the template that is.
4
5
  */
5
- export type Mapping = [number, number, number, boolean];
6
+ export type Mapping = [number, number, number, boolean, number?];
6
7
  /**
7
8
  * `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
8
- * the page's inputs. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
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.
9
11
  */
10
12
  export declare function generateTs(source: string, file: string, options?: {
11
13
  loader?: string;
14
+ componentSuffix?: string;
12
15
  }): {
13
16
  code: string;
14
17
  mappings: Mapping[];
@@ -31,3 +34,16 @@ export declare function viewsDeclaration(views: {
31
34
  * and other page sources count, though check only type-checks .tscl pages (#142).
32
35
  */
33
36
  export declare function routesDeclaration(files: string[]): string;
37
+ /**
38
+ * generateTs for a template that may not parse, as an editor has it while someone types: each error is collected and
39
+ * the text repaired (what's open at the end is closed; any other error blanks its line, from the error on, then whole)
40
+ * until it parses, so TypeScript still covers the rest. Repairs only append or replace with spaces, so every offset
41
+ * in `source` stays where it was. `result` is null if it still doesn't parse after a few repairs.
42
+ */
43
+ export declare function generateTolerant(source: string, file: string, options?: Parameters<typeof generateTs>[2]): {
44
+ result: ReturnType<typeof generateTs> | null;
45
+ errors: {
46
+ message: string;
47
+ offset: number;
48
+ }[];
49
+ };
@@ -1,29 +1,37 @@
1
1
  import { routeFromFile } from '../server/handler.js';
2
- import { parse } from '../compiler/parse.js';
3
- import { splitImports } from '../compiler/script.js';
2
+ import { ClarusError } from '../compiler/errors.js';
3
+ import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
4
+ import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
5
+ const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
6
+ const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
4
7
  export function generateTs(source, file, options = {}) {
5
8
  const parsed = parse(source, file);
6
9
  const mappings = [];
7
10
  let code = '';
8
11
  const emit = (text) => { code += text; };
9
12
  const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
10
- const point = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, false]); code += text; };
13
+ const point = (text, sourceStart, sourceLength = 1) => { mappings.push([code.length, text.length, sourceStart, false, sourceLength]); code += text; };
11
14
  const at = (text, from) => source.indexOf(text, from);
12
15
  const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
13
16
  const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
14
17
  emit('// Generated by clarusjs for type checking. It never runs.\n');
15
- emit('declare function state<T>(value: T): T\n');
18
+ emit('declare function state<T>(value: T): T extends never[] ? any[] : T\n');
16
19
  emit('declare function derived<T>(fn: () => T): T\n');
17
20
  emit('declare function shared<T>(store: { get(): T }): T\n');
18
21
  emit('declare function __cl_use(value: unknown): void\n');
19
- emit('type __cl_Event<K extends string> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : Event) & { target: any; currentTarget: any }\n');
22
+ emit('declare const __cl_bool: boolean\n');
23
+ const text = 'string | number | boolean | null | undefined';
24
+ emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
25
+ emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
26
+ emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
27
+ emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
20
28
  for (const t of parsed.typeImports) {
21
29
  emit('import type ');
22
30
  copy(t.clause, t.clauseStart);
23
31
  emit(` from ${JSON.stringify(t.from)}\n`);
24
32
  }
25
33
  for (const imp of parsed.imports)
26
- emit(`import type { Inputs as ${alias(imp.name)} } from ${JSON.stringify(`${imp.from}.ts`)}\n`);
34
+ emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
27
35
  for (const d of parsed.dataImports) {
28
36
  emit('import ');
29
37
  copy(d.clause, d.clauseStart);
@@ -38,7 +46,14 @@ export function generateTs(source, file, options = {}) {
38
46
  emit('\n');
39
47
  }
40
48
  }
49
+ for (const t of parsed.types) {
50
+ emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
51
+ copy(t.type, t.typeStart);
52
+ emit('\n');
53
+ }
41
54
  emit('\nexport interface Inputs {\n');
55
+ if (!parsed.inputs.length)
56
+ emit(' __cl_none?: never\n');
42
57
  for (const input of parsed.inputs) {
43
58
  emit(' ');
44
59
  copy(input.name, input.nameStart);
@@ -47,18 +62,24 @@ export function generateTs(source, file, options = {}) {
47
62
  emit('\n');
48
63
  }
49
64
  emit('}\n');
65
+ const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
66
+ emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
50
67
  let loaderSpan;
51
68
  if (options.loader) {
52
69
  emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
53
70
  const start = code.length;
54
71
  point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
55
72
  loaderSpan = [start, code.length];
73
+ emit('; __cl_use(__cl_from_load)');
56
74
  emit('\n');
57
75
  }
58
- emit('\nexport default function __cl_check(__cl_props: Inputs) {\n');
59
- if (parsed.inputs.length) {
60
- emit(' const { ');
61
- parsed.inputs.forEach((input, i) => {
76
+ emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
77
+ emit('\nexport default function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n');
78
+ for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
79
+ if (!list.length)
80
+ continue;
81
+ emit(` ${keyword} { `);
82
+ list.forEach((input, i) => {
62
83
  if (i)
63
84
  emit(', ');
64
85
  copy(input.name, input.nameStart);
@@ -68,9 +89,23 @@ export function generateTs(source, file, options = {}) {
68
89
  }
69
90
  });
70
91
  emit(' } = __cl_props\n');
92
+ emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
71
93
  }
72
94
  if (parsed.script && script) {
73
- copy(script.body, parsed.script.start);
95
+ const body = script.body;
96
+ const cuts = [
97
+ ...script.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
98
+ ...untypedParams(parsed.script.code).map((e) => ({ ...e, end: e.at })),
99
+ ].sort((a, b) => a.at - b.at);
100
+ let pos = 0;
101
+ for (const cut of cuts) {
102
+ if (cut.at > pos)
103
+ copy(body.slice(pos, cut.at), parsed.script.start + pos);
104
+ emit(cut.text);
105
+ pos = Math.max(pos, cut.end);
106
+ }
107
+ if (body.length > pos)
108
+ copy(body.slice(pos), parsed.script.start + pos);
74
109
  emit('\n;\n');
75
110
  }
76
111
  const use = (expr, start) => {
@@ -78,7 +113,24 @@ export function generateTs(source, file, options = {}) {
78
113
  copy(expr, at(expr, start));
79
114
  emit('));\n');
80
115
  };
81
- const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : 4);
116
+ const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : a.kind === 'model' ? 6 : 4);
117
+ const guards = [];
118
+ const guarded = () => {
119
+ if (guards.length)
120
+ emit(`\n // @ts-ignore\n if (${guards.join(' && ')})\n `);
121
+ };
122
+ const writable = (a, value) => {
123
+ emit(' ;(() => { ');
124
+ guarded();
125
+ emit(value === undefined ? '(' : '');
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);
132
+ emit(') });\n');
133
+ };
82
134
  function visit(node) {
83
135
  switch (node.type) {
84
136
  case 'text':
@@ -98,7 +150,10 @@ export function generateTs(source, file, options = {}) {
98
150
  copy(b.cond, at(b.cond, b.condStart));
99
151
  emit(')) {\n');
100
152
  }
153
+ const earlier = node.branches.slice(0, i).map((x) => `!(${x.cond})`);
154
+ guards.push([...earlier, ...(b.cond === null ? [] : [`(${b.cond})`])].join(' && ') || 'true');
101
155
  b.children.forEach(visit);
156
+ guards.pop();
102
157
  emit(' }\n');
103
158
  });
104
159
  return;
@@ -107,10 +162,13 @@ export function generateTs(source, file, options = {}) {
107
162
  copy(node.item, node.itemStart);
108
163
  emit(' of ');
109
164
  copy(node.list, node.listStart);
110
- emit(') {\n const $index: number = 0\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');
111
166
  if (node.track !== null)
112
167
  use(node.track, node.trackStart);
168
+ const outer = guards.splice(0);
169
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT]))));
113
170
  node.children.forEach(visit);
171
+ guards.splice(0, guards.length, ...outer);
114
172
  emit(' }\n');
115
173
  if (node.empty) {
116
174
  emit(' {\n');
@@ -123,32 +181,60 @@ export function generateTs(source, file, options = {}) {
123
181
  const component = components.get(node.tag);
124
182
  if (component) {
125
183
  emit(' { const ');
126
- point('__cl_p', node.start);
127
- emit(`: ${alias(node.tag)} = { `);
184
+ point('__cl_p', node.start, node.tag.length + 1);
185
+ emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
128
186
  for (const a of node.attrs) {
129
- if (a.kind !== 'prop')
187
+ if (a.kind !== 'prop' && a.kind !== 'model')
130
188
  continue;
131
- copy(a.name, a.start + 1);
189
+ copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
132
190
  emit(': (');
133
191
  copy(a.expr, at(a.expr, attrValueStart(a)));
134
192
  emit('), ');
135
193
  }
136
194
  emit('}; __cl_use(__cl_p) }\n');
195
+ for (const a of node.attrs) {
196
+ if (a.kind !== 'model')
197
+ continue;
198
+ emit(' { const ');
199
+ point('__cl_m', a.start, a.name.length + 4);
200
+ emit(`: ${alias(node.tag)}_M = ${JSON.stringify(a.name)}; __cl_use(__cl_m) }\n`);
201
+ emit(' ;(() => { ');
202
+ guarded();
203
+ copy(a.expr, at(a.expr, attrValueStart(a)));
204
+ emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
205
+ }
137
206
  node.children.forEach(visit);
138
207
  return;
139
208
  }
140
209
  for (const a of node.attrs) {
141
- if (a.kind === 'prop')
210
+ if (a.kind === 'model') {
142
211
  use(a.expr, attrValueStart(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);
216
+ }
217
+ else if (a.kind === 'prop' && a.name === 'engine') {
218
+ emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
219
+ copy(a.expr, at(a.expr, attrValueStart(a)));
220
+ emit('));\n');
221
+ }
222
+ else if (a.kind === 'prop') {
223
+ emit(` __cl_attr<${JSON.stringify(node.tag.toLowerCase())}, ${JSON.stringify(ENUMERATED.has(a.name.toLowerCase()) ? '' : PROPERTY[a.name.toLowerCase()] ?? a.name.toLowerCase())}>((`);
224
+ copy(a.expr, at(a.expr, attrValueStart(a)));
225
+ emit('));\n');
226
+ }
143
227
  else if (a.kind === 'interp') {
144
228
  for (const p of a.parts)
145
229
  if (typeof p !== 'string')
146
230
  use(p.expr, p.start + 2);
147
231
  }
148
232
  else if (a.kind === 'event') {
149
- emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}>) => { `);
233
+ emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => { `);
234
+ guarded();
235
+ emit('{ ');
150
236
  copy(a.expr, at(a.expr, attrValueStart(a)));
151
- emit(' });\n');
237
+ emit(' } });\n');
152
238
  }
153
239
  }
154
240
  node.children.forEach(visit);
@@ -203,12 +289,16 @@ export function viewsDeclaration(views) {
203
289
  body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
204
290
  }
205
291
  }
292
+ for (const t of parsed.types)
293
+ body.push(t.kind === 'interface' ? ` interface ${t.name}${t.params ?? ''} ${t.type}` : ` type ${t.name}${t.params ?? ''} = ${t.type}`);
206
294
  body.push(` interface Inputs {`);
295
+ if (!parsed.inputs.length)
296
+ body.push(' __cl_none?: never');
207
297
  for (const input of parsed.inputs)
208
298
  body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
209
299
  body.push(' }');
210
300
  lines.push(`declare namespace ${ns} {`, ...body, '}');
211
- entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.tscl$/, ''))}: ${ns}.Inputs`);
301
+ entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.[^./]+$/, ''))}: ${ns}.Inputs`);
212
302
  });
213
303
  lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
214
304
  return lines.join('\n');
@@ -222,3 +312,49 @@ export function routesDeclaration(files) {
222
312
  });
223
313
  return ['// Generated by clarusjs check: every page route → its params, for href() from clarusjs/navigation.', "declare module 'clarusjs/navigation' {", ' interface Routes {', ...entries, ' }', '}', 'export {}', ''].join('\n');
224
314
  }
315
+ function located(err, source) {
316
+ const lines = source.split('\n');
317
+ const offset = Math.min(source.length, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1);
318
+ return { text: err.message.slice(`${err.file}:${err.line}:${err.column} `.length), offset };
319
+ }
320
+ const CLOSERS = [
321
+ [/^unclosed \{\{--/, () => ' --}}'],
322
+ [/^unclosed <!--/, () => ' -->'],
323
+ [/^unclosed \{\{$/, () => ' }}'],
324
+ [/^unclosed <\/([\w:-]+)>$/, () => '>'],
325
+ [/^unclosed <(script|style)\b/, (m) => `</${m[1]}>`],
326
+ [/^unclosed <([\w:-]+)(?: verbatim)?>$/, (m) => `</${m[1]}>`],
327
+ [/^unclosed @?[\w-]+ block$/, () => '\n}'],
328
+ ];
329
+ export function generateTolerant(source, file, options = {}) {
330
+ const errors = [];
331
+ let text = source;
332
+ for (let tries = 0; tries < 20; tries++) {
333
+ try {
334
+ const result = generateTs(text, file, options);
335
+ result.mappings = result.mappings.filter(([, , s]) => s < source.length).map((m) => (m[2] + m[1] > source.length && m[3] ? [m[0], m[1], m[2], false, source.length - m[2]] : m));
336
+ return { result, errors };
337
+ }
338
+ catch (err) {
339
+ if (!(err instanceof ClarusError))
340
+ throw err;
341
+ const { text: message, offset } = located(err, text);
342
+ if (!errors.some((e) => e.message === message && e.offset === offset))
343
+ errors.push({ message, offset: Math.min(offset, source.length) });
344
+ const closer = CLOSERS.map(([re, close]) => { const m = re.exec(message); return m && close(m); }).find((c) => c);
345
+ if (closer && text.slice(offset).indexOf('\n', 1) === -1 || closer && /^unclosed (<[\w:-]+|@?[\w-]+ block)/.test(message)) {
346
+ text += closer;
347
+ continue;
348
+ }
349
+ const from = /@|block|\( after|\(\s*$/.test(message) && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
350
+ const lineStart = text.lastIndexOf('\n', from - 1) + 1;
351
+ const lineEnd = text.indexOf('\n', from) === -1 ? text.length : text.indexOf('\n', from);
352
+ const blank = (from) => text.slice(0, from) + text.slice(from, lineEnd).replace(/[^\n]/g, ' ') + text.slice(lineEnd);
353
+ const next = blank(from) !== text ? blank(from) : blank(lineStart);
354
+ if (next === text)
355
+ break;
356
+ text = next;
357
+ }
358
+ }
359
+ return { result: null, errors };
360
+ }
@@ -11,7 +11,20 @@ export type CheckResult = {
11
11
  text: string;
12
12
  json: string;
13
13
  };
14
+ /** A page's .load.ts that exports load(), as an import specifier: what it returns is checked against the inputs. */
15
+ export declare function loaderOf(path: string): string | undefined;
16
+ /** A page source, as the Vite plugin's `sources` option takes it (Markdown from @clarusjs/content, …). */
17
+ export type CheckSource = {
18
+ extension: string;
19
+ toTscl(code: string, file: string, context: {
20
+ route: string;
21
+ root: string;
22
+ addDependency(file: string): void;
23
+ }): string;
24
+ };
14
25
  export declare function check(options: {
15
26
  root: string;
16
27
  typescript?: string;
28
+ sources?: CheckSource[];
29
+ viteAliases?: unknown;
17
30
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -5,7 +5,8 @@ import { basename, dirname, relative, resolve, sep } from 'node:path';
5
5
  import { ClarusError } from '../compiler/errors.js';
6
6
  import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
7
7
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
8
- import { projectAliases } from '../vite/aliases.js';
8
+ import { projectAliases, resolveAlias } from '../vite/aliases.js';
9
+ import { routeFromFile } from '../server/handler.js';
9
10
  const VIRTUAL = '.clarusjs/virtual';
10
11
  const posix = (path) => path.split(sep).join('/');
11
12
  function packageInfo(file) {
@@ -20,6 +21,24 @@ function position(text, offset) {
20
21
  const before = text.slice(0, offset);
21
22
  return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
22
23
  }
24
+ function inSource(original, converted, offset) {
25
+ const tag = [converted.lastIndexOf('<', offset), converted.indexOf('>', offset) + 1];
26
+ const line = [converted.lastIndexOf('\n', offset - 1) + 1, converted.indexOf('\n', offset) === -1 ? converted.length : converted.indexOf('\n', offset)];
27
+ for (const [a, b] of [tag, line]) {
28
+ if (a < 0 || b <= offset || b - a < 3)
29
+ continue;
30
+ const snippet = converted.slice(a, b);
31
+ const at = original.indexOf(snippet);
32
+ if (at !== -1 && original.indexOf(snippet, at + 1) === -1)
33
+ return at + (offset - a);
34
+ }
35
+ return null;
36
+ }
37
+ export function loaderOf(path) {
38
+ const loaderPath = path.replace(/\.[^./]+$/, '.load.ts');
39
+ const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
40
+ return hasLoad ? `./${basename(loaderPath)}` : undefined;
41
+ }
23
42
  function typescriptDir(root, override) {
24
43
  if (override)
25
44
  return override;
@@ -31,29 +50,48 @@ export function check(options) {
31
50
  rmSync(virtualRoot, { recursive: true, force: true });
32
51
  const diagnostics = [];
33
52
  const generated = new Map();
34
- for (const path of findClarusFiles(resolve(root, 'src'))) {
53
+ const sources = options.sources ?? [];
54
+ const aliases = projectAliases(root, options.viteAliases);
55
+ const pageFiles = findClarusFiles(resolve(root, 'src'), ['.tscl', ...sources.map((x) => x.extension)])
56
+ .filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
57
+ const views = [];
58
+ for (const path of pageFiles) {
35
59
  const file = posix(relative(root, path));
36
- const source = readFileSync(path, 'utf8');
60
+ const original = readFileSync(path, 'utf8');
61
+ const src = sources.find((x) => path.endsWith(x.extension));
62
+ let source = original;
63
+ try {
64
+ if (src)
65
+ source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
66
+ }
67
+ catch (err) {
68
+ diagnostics.push({ file, line: 1, column: 1, code: 'clarus', message: err.message });
69
+ continue;
70
+ }
71
+ views.push({ file, source });
37
72
  try {
38
- const loaderPath = path.replace(/\.tscl$/, '.load.ts');
39
- const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
40
- const { code, mappings, loaderSpan } = generateTs(source, file, hasLoad ? { loader: `./${basename(loaderPath)}` } : {});
73
+ const loader = loaderOf(path);
74
+ const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
41
75
  const vpath = resolve(virtualRoot, `${file}.ts`);
42
76
  mkdirSync(dirname(vpath), { recursive: true });
43
77
  writeFileSync(vpath, code);
44
- generated.set(vpath, { file, source, code, mappings, loaderSpan });
78
+ generated.set(vpath, { file, source, code, mappings, loaderSpan, ...(src ? { original } : {}) });
45
79
  }
46
80
  catch (err) {
47
81
  if (!(err instanceof ClarusError))
48
82
  throw err;
49
83
  const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
50
- diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
84
+ const lines = source.split('\n');
85
+ 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 });
51
87
  }
52
88
  }
53
89
  const appRoot = realpathSync(root);
54
90
  const paths = {};
55
91
  const virtualOf = new Map();
56
- const components = reachableComponents(root, findClarusFiles(resolve(root, 'src')), (p) => readFileSync(p, 'utf8'), ['.tscl'], projectAliases(root));
92
+ const converted = new Map(views.map((v) => [realpathSync(resolve(root, v.file)), v.source]));
93
+ const textOf = (p) => converted.get(realpathSync(p)) ?? readFileSync(p, 'utf8');
94
+ const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases);
57
95
  for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
58
96
  const pkg = packageInfo(path);
59
97
  const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
@@ -72,9 +110,10 @@ export function check(options) {
72
110
  }
73
111
  const require = createRequire(resolve(root, 'package.json'));
74
112
  for (const path of components) {
75
- for (const m of readFileSync(path, 'utf8').matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
113
+ for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
76
114
  try {
77
- const target = virtualOf.get(realpathSync(require.resolve(m[2])));
115
+ const file = realpathSync(resolveAlias(m[2], aliases) ?? require.resolve(m[2]));
116
+ const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
78
117
  if (target)
79
118
  paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
80
119
  }
@@ -82,14 +121,20 @@ export function check(options) {
82
121
  }
83
122
  }
84
123
  const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
85
- for (const alias of projectAliases(root)) {
86
- const tail = alias.exact ? '' : '*';
124
+ paths['/*'] = ['../*', './virtual/*'];
125
+ for (const alias of aliases) {
87
126
  const mirror = resolve(virtualRoot, relative(root, alias.replacement));
88
- paths[alias.find + tail] = [fromCheck(alias.replacement) + (alias.exact ? '' : '/') + tail, fromCheck(mirror) + (alias.exact ? '' : '/') + tail].map((p) => p.replace(/\/\/\*$/, '/*'));
127
+ const targets = (tail) => [fromCheck(alias.replacement) + tail, fromCheck(mirror) + tail].map((p) => p.replace(/\/\/\*$/, '/*'));
128
+ if (alias.find.endsWith('/'))
129
+ paths[`${alias.find}*`] = targets('/*');
130
+ else {
131
+ paths[alias.find] = targets('');
132
+ if (!alias.exact)
133
+ paths[`${alias.find}/*`] = targets('/*');
134
+ }
89
135
  }
90
136
  mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
91
- const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
92
- writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
137
+ writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(views));
93
138
  const walk = (dir) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(resolve(dir, e.name)) : [resolve(dir, e.name)])) : []);
94
139
  writeFileSync(resolve(root, '.clarusjs/routes.d.ts'), routesDeclaration(walk(resolve(root, 'src/pages')).map((path) => posix(relative(root, path)))));
95
140
  const own = ['tsconfig.json', 'jsconfig.json'].find((name) => existsSync(resolve(root, name)));
@@ -128,8 +173,10 @@ export function check(options) {
128
173
  }
129
174
  const lines = g.code.split('\n');
130
175
  const offset = lines.slice(0, Number(m[2]) - 1).reduce((n, l) => n + l.length + 1, 0) + Number(m[3]) - 1;
131
- const source = toSourceOffset(g.mappings, offset);
132
- const at = source === null ? { line: 1, column: 1 } : position(g.source, source);
176
+ let source = toSourceOffset(g.mappings, offset);
177
+ if (source !== null && g.original !== undefined)
178
+ source = inSource(g.original, g.source, source);
179
+ const at = source === null ? { line: 1, column: 1 } : position(g.original ?? g.source, source);
133
180
  const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
134
181
  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];
135
182
  diagnostics.push({ file: g.file, ...at, code: m[4], message });
package/dist/cli/index.js CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
3
  import { check } from './check.js';
4
+ import { loadProject } from './project.js';
4
5
  import { explain } from './explain.js';
6
+ import { serve } from './mapper.js';
5
7
  const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
6
8
  program
7
9
  .command('check')
8
- .description('type-check every .tscl file under src/ and report errors at file.tscl:line:col')
10
+ .description('type-check every .tscl file under src/ and every page (Markdown pages too), reporting errors where they are written')
9
11
  .argument('[dir]', 'project folder', '.')
10
12
  .option('--json', 'print diagnostics as JSON')
11
- .action((dir, options) => {
12
- const result = check({ root: dir });
13
+ .action(async (dir, options) => {
14
+ const result = check({ root: dir, ...(await loadProject(dir)) });
13
15
  if (options.json)
14
16
  console.log(result.json);
15
17
  else if (result.diagnostics.length) {
@@ -34,4 +36,8 @@ program
34
36
  console.log(options.json ? result.json : result.text);
35
37
  process.exitCode = result.exitCode;
36
38
  });
39
+ program
40
+ .command('mapper')
41
+ .description('the TypeScript 7.1 content mapper for .tscl files (TypeScript starts it; see https://clarusjs.com/guide/editor)')
42
+ .action(() => serve());
37
43
  program.parse();
@@ -0,0 +1,25 @@
1
+ /**
2
+ * [virtual start, virtual length, original start, original length, kind, features?]: kind 0 = verbatim, 1 = atom (a
3
+ * whole span). Features (a bitmask of language-service operations; all when absent) are none for atoms: they are
4
+ * generated stand-ins (`__cl_p` for a component's props), so only their errors belong in the template, not hover,
5
+ * completion or rename. Diagnostics can't be switched off per span.
6
+ */
7
+ type Span = [number, number, number, number, 0 | 1] | [number, number, number, number, 1, number];
8
+ type Diagnostic = {
9
+ messageText: string;
10
+ start: number;
11
+ length: number;
12
+ code: number;
13
+ };
14
+ export declare function transform(params: {
15
+ fileName: string;
16
+ content: string;
17
+ }): {
18
+ text: string;
19
+ extension: '.ts';
20
+ mappings: Span[];
21
+ diagnostics: Diagnostic[];
22
+ };
23
+ /** Serve the protocol on stdin/stdout until stdin ends. */
24
+ export declare function serve(): void;
25
+ export {};
@@ -0,0 +1,65 @@
1
+ import { generateTolerant } from '../check/generate.js';
2
+ import { loaderOf } from './check.js';
3
+ export function transform(params) {
4
+ const { fileName, content } = params;
5
+ const loader = loaderOf(fileName);
6
+ const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', ...(loader ? { loader } : {}) });
7
+ 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
+ if (!result)
9
+ return { text: 'export {}\n', extension: '.ts', mappings: [], diagnostics };
10
+ const { code, mappings } = result;
11
+ const spans = mappings.map(([v, length, s, exact, sourceLength]) => {
12
+ if (exact && code.slice(v, v + length) === content.slice(s, s + length))
13
+ return [v, length, s, length, 0];
14
+ if (exact)
15
+ return [v, length, s, Math.min(length, content.length - s), 1];
16
+ return [v, length, s, Math.min(sourceLength ?? 1, content.length - s), 1, 0];
17
+ });
18
+ return { text: code, extension: '.ts', mappings: spans, diagnostics };
19
+ }
20
+ function handle(request) {
21
+ if (request.id === undefined)
22
+ return;
23
+ switch (request.method) {
24
+ case 'initialize': return { id: request.id, result: { positionEncoding: 'utf-16', diagnosticSource: 'clarus' } };
25
+ case 'openProject': return { id: request.id, result: {} };
26
+ case 'closeProject': return { id: request.id, result: null };
27
+ case 'transform': return { id: request.id, result: transform(request.params) };
28
+ default: return { id: request.id, error: { code: -32601, message: `Unknown method: ${request.method}` } };
29
+ }
30
+ }
31
+ export function serve() {
32
+ const send = (message) => {
33
+ const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...message }));
34
+ process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`);
35
+ process.stdout.write(body);
36
+ };
37
+ let pending = Buffer.alloc(0);
38
+ process.stdin.on('data', (chunk) => {
39
+ pending = Buffer.concat([pending, chunk]);
40
+ for (;;) {
41
+ const headerEnd = pending.indexOf('\r\n\r\n');
42
+ if (headerEnd === -1)
43
+ return;
44
+ const match = /Content-Length:\s*(\d+)/i.exec(pending.subarray(0, headerEnd).toString());
45
+ if (!match)
46
+ throw new Error('clarusjs mapper: a message without Content-Length');
47
+ const start = headerEnd + 4;
48
+ const end = start + Number(match[1]);
49
+ if (pending.length < end)
50
+ return;
51
+ const request = JSON.parse(pending.subarray(start, end).toString());
52
+ pending = pending.subarray(end);
53
+ let response;
54
+ try {
55
+ response = handle(request);
56
+ }
57
+ catch (err) {
58
+ response = { id: request.id, error: { code: -32603, message: err.message } };
59
+ }
60
+ if (response)
61
+ send(response);
62
+ }
63
+ });
64
+ process.stdin.on('end', () => process.exit(0));
65
+ }
@@ -0,0 +1,5 @@
1
+ import type { CheckSource } from './check.ts';
2
+ export declare function loadProject(root: string): Promise<{
3
+ sources: CheckSource[];
4
+ viteAliases: unknown;
5
+ }>;