clarusjs 0.8.1 → 0.9.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.
@@ -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,36 @@
1
1
  import { routeFromFile } from '../server/handler.js';
2
+ import { ClarusError } from '../compiler/errors.js';
2
3
  import { parse } from '../compiler/parse.js';
3
- import { splitImports } from '../compiler/script.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
+ const text = 'string | number | boolean | null | undefined';
23
+ emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
24
+ emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
25
+ emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
26
+ emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
20
27
  for (const t of parsed.typeImports) {
21
28
  emit('import type ');
22
29
  copy(t.clause, t.clauseStart);
23
30
  emit(` from ${JSON.stringify(t.from)}\n`);
24
31
  }
25
32
  for (const imp of parsed.imports)
26
- emit(`import type { Inputs as ${alias(imp.name)} } from ${JSON.stringify(`${imp.from}.ts`)}\n`);
33
+ emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
27
34
  for (const d of parsed.dataImports) {
28
35
  emit('import ');
29
36
  copy(d.clause, d.clauseStart);
@@ -38,7 +45,14 @@ export function generateTs(source, file, options = {}) {
38
45
  emit('\n');
39
46
  }
40
47
  }
48
+ for (const t of parsed.types) {
49
+ emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
50
+ copy(t.type, t.typeStart);
51
+ emit('\n');
52
+ }
41
53
  emit('\nexport interface Inputs {\n');
54
+ if (!parsed.inputs.length)
55
+ emit(' __cl_none?: never\n');
42
56
  for (const input of parsed.inputs) {
43
57
  emit(' ');
44
58
  copy(input.name, input.nameStart);
@@ -47,18 +61,24 @@ export function generateTs(source, file, options = {}) {
47
61
  emit('\n');
48
62
  }
49
63
  emit('}\n');
64
+ const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
65
+ emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
50
66
  let loaderSpan;
51
67
  if (options.loader) {
52
68
  emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
53
69
  const start = code.length;
54
70
  point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
55
71
  loaderSpan = [start, code.length];
72
+ emit('; __cl_use(__cl_from_load)');
56
73
  emit('\n');
57
74
  }
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) => {
75
+ 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');
76
+ emit('\nexport default function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n');
77
+ for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
78
+ if (!list.length)
79
+ continue;
80
+ emit(` ${keyword} { `);
81
+ list.forEach((input, i) => {
62
82
  if (i)
63
83
  emit(', ');
64
84
  copy(input.name, input.nameStart);
@@ -68,9 +88,23 @@ export function generateTs(source, file, options = {}) {
68
88
  }
69
89
  });
70
90
  emit(' } = __cl_props\n');
91
+ emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
71
92
  }
72
93
  if (parsed.script && script) {
73
- copy(script.body, parsed.script.start);
94
+ const body = script.body;
95
+ const cuts = [
96
+ ...script.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
97
+ ...untypedParams(parsed.script.code).map((e) => ({ ...e, end: e.at })),
98
+ ].sort((a, b) => a.at - b.at);
99
+ let pos = 0;
100
+ for (const cut of cuts) {
101
+ if (cut.at > pos)
102
+ copy(body.slice(pos, cut.at), parsed.script.start + pos);
103
+ emit(cut.text);
104
+ pos = Math.max(pos, cut.end);
105
+ }
106
+ if (body.length > pos)
107
+ copy(body.slice(pos), parsed.script.start + pos);
74
108
  emit('\n;\n');
75
109
  }
76
110
  const use = (expr, start) => {
@@ -78,7 +112,21 @@ export function generateTs(source, file, options = {}) {
78
112
  copy(expr, at(expr, start));
79
113
  emit('));\n');
80
114
  };
81
- const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : 4);
115
+ const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : a.kind === 'model' ? 6 : 4);
116
+ const guards = [];
117
+ const guarded = () => {
118
+ if (guards.length)
119
+ emit(`\n // @ts-ignore\n if (${guards.join(' && ')})\n `);
120
+ };
121
+ const writable = (a) => {
122
+ emit(' ;(() => { ');
123
+ guarded();
124
+ emit('(');
125
+ copy(a.expr, at(a.expr, attrValueStart(a)));
126
+ emit(') = (');
127
+ copy(a.expr, at(a.expr, attrValueStart(a)));
128
+ emit(') });\n');
129
+ };
82
130
  function visit(node) {
83
131
  switch (node.type) {
84
132
  case 'text':
@@ -98,7 +146,10 @@ export function generateTs(source, file, options = {}) {
98
146
  copy(b.cond, at(b.cond, b.condStart));
99
147
  emit(')) {\n');
100
148
  }
149
+ const earlier = node.branches.slice(0, i).map((x) => `!(${x.cond})`);
150
+ guards.push([...earlier, ...(b.cond === null ? [] : [`(${b.cond})`])].join(' && ') || 'true');
101
151
  b.children.forEach(visit);
152
+ guards.pop();
102
153
  emit(' }\n');
103
154
  });
104
155
  return;
@@ -107,10 +158,13 @@ export function generateTs(source, file, options = {}) {
107
158
  copy(node.item, node.itemStart);
108
159
  emit(' of ');
109
160
  copy(node.list, node.listStart);
110
- emit(') {\n const $index: number = 0\n');
161
+ emit(') {\n const $index: number = 0; __cl_use($index)\n');
111
162
  if (node.track !== null)
112
163
  use(node.track, node.trackStart);
164
+ const outer = guards.splice(0);
165
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, '$index']))));
113
166
  node.children.forEach(visit);
167
+ guards.splice(0, guards.length, ...outer);
114
168
  emit(' }\n');
115
169
  if (node.empty) {
116
170
  emit(' {\n');
@@ -123,32 +177,57 @@ export function generateTs(source, file, options = {}) {
123
177
  const component = components.get(node.tag);
124
178
  if (component) {
125
179
  emit(' { const ');
126
- point('__cl_p', node.start);
127
- emit(`: ${alias(node.tag)} = { `);
180
+ point('__cl_p', node.start, node.tag.length + 1);
181
+ emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
128
182
  for (const a of node.attrs) {
129
- if (a.kind !== 'prop')
183
+ if (a.kind !== 'prop' && a.kind !== 'model')
130
184
  continue;
131
- copy(a.name, a.start + 1);
185
+ copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
132
186
  emit(': (');
133
187
  copy(a.expr, at(a.expr, attrValueStart(a)));
134
188
  emit('), ');
135
189
  }
136
190
  emit('}; __cl_use(__cl_p) }\n');
191
+ for (const a of node.attrs) {
192
+ if (a.kind !== 'model')
193
+ continue;
194
+ emit(' { const ');
195
+ point('__cl_m', a.start, a.name.length + 4);
196
+ emit(`: ${alias(node.tag)}_M = ${JSON.stringify(a.name)}; __cl_use(__cl_m) }\n`);
197
+ emit(' ;(() => { ');
198
+ guarded();
199
+ copy(a.expr, at(a.expr, attrValueStart(a)));
200
+ emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
201
+ }
137
202
  node.children.forEach(visit);
138
203
  return;
139
204
  }
140
205
  for (const a of node.attrs) {
141
- if (a.kind === 'prop')
206
+ if (a.kind === 'model') {
142
207
  use(a.expr, attrValueStart(a));
208
+ writable(a);
209
+ }
210
+ else if (a.kind === 'prop' && a.name === 'engine') {
211
+ emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
212
+ copy(a.expr, at(a.expr, attrValueStart(a)));
213
+ emit('));\n');
214
+ }
215
+ else if (a.kind === 'prop') {
216
+ emit(` __cl_attr<${JSON.stringify(node.tag.toLowerCase())}, ${JSON.stringify(ENUMERATED.has(a.name.toLowerCase()) ? '' : PROPERTY[a.name.toLowerCase()] ?? a.name.toLowerCase())}>((`);
217
+ copy(a.expr, at(a.expr, attrValueStart(a)));
218
+ emit('));\n');
219
+ }
143
220
  else if (a.kind === 'interp') {
144
221
  for (const p of a.parts)
145
222
  if (typeof p !== 'string')
146
223
  use(p.expr, p.start + 2);
147
224
  }
148
225
  else if (a.kind === 'event') {
149
- emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}>) => { `);
226
+ emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => { `);
227
+ guarded();
228
+ emit('{ ');
150
229
  copy(a.expr, at(a.expr, attrValueStart(a)));
151
- emit(' });\n');
230
+ emit(' } });\n');
152
231
  }
153
232
  }
154
233
  node.children.forEach(visit);
@@ -203,12 +282,16 @@ export function viewsDeclaration(views) {
203
282
  body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
204
283
  }
205
284
  }
285
+ for (const t of parsed.types)
286
+ body.push(t.kind === 'interface' ? ` interface ${t.name}${t.params ?? ''} ${t.type}` : ` type ${t.name}${t.params ?? ''} = ${t.type}`);
206
287
  body.push(` interface Inputs {`);
288
+ if (!parsed.inputs.length)
289
+ body.push(' __cl_none?: never');
207
290
  for (const input of parsed.inputs)
208
291
  body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
209
292
  body.push(' }');
210
293
  lines.push(`declare namespace ${ns} {`, ...body, '}');
211
- entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.tscl$/, ''))}: ${ns}.Inputs`);
294
+ entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.[^./]+$/, ''))}: ${ns}.Inputs`);
212
295
  });
213
296
  lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
214
297
  return lines.join('\n');
@@ -222,3 +305,49 @@ export function routesDeclaration(files) {
222
305
  });
223
306
  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
307
  }
308
+ function located(err, source) {
309
+ const lines = source.split('\n');
310
+ const offset = Math.min(source.length, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1);
311
+ return { text: err.message.slice(`${err.file}:${err.line}:${err.column} `.length), offset };
312
+ }
313
+ const CLOSERS = [
314
+ [/^unclosed \{\{--/, () => ' --}}'],
315
+ [/^unclosed <!--/, () => ' -->'],
316
+ [/^unclosed \{\{$/, () => ' }}'],
317
+ [/^unclosed <\/([\w:-]+)>$/, () => '>'],
318
+ [/^unclosed <(script|style)\b/, (m) => `</${m[1]}>`],
319
+ [/^unclosed <([\w:-]+)(?: verbatim)?>$/, (m) => `</${m[1]}>`],
320
+ [/^unclosed @?[\w-]+ block$/, () => '\n}'],
321
+ ];
322
+ export function generateTolerant(source, file, options = {}) {
323
+ const errors = [];
324
+ let text = source;
325
+ for (let tries = 0; tries < 20; tries++) {
326
+ try {
327
+ const result = generateTs(text, file, options);
328
+ 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));
329
+ return { result, errors };
330
+ }
331
+ catch (err) {
332
+ if (!(err instanceof ClarusError))
333
+ throw err;
334
+ const { text: message, offset } = located(err, text);
335
+ if (!errors.some((e) => e.message === message && e.offset === offset))
336
+ errors.push({ message, offset: Math.min(offset, source.length) });
337
+ const closer = CLOSERS.map(([re, close]) => { const m = re.exec(message); return m && close(m); }).find((c) => c);
338
+ if (closer && text.slice(offset).indexOf('\n', 1) === -1 || closer && /^unclosed (<[\w:-]+|@?[\w-]+ block)/.test(message)) {
339
+ text += closer;
340
+ continue;
341
+ }
342
+ const from = /@|block|\( after|\(\s*$/.test(message) && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
343
+ const lineStart = text.lastIndexOf('\n', from - 1) + 1;
344
+ const lineEnd = text.indexOf('\n', from) === -1 ? text.length : text.indexOf('\n', from);
345
+ const blank = (from) => text.slice(0, from) + text.slice(from, lineEnd).replace(/[^\n]/g, ' ') + text.slice(lineEnd);
346
+ const next = blank(from) !== text ? blank(from) : blank(lineStart);
347
+ if (next === text)
348
+ break;
349
+ text = next;
350
+ }
351
+ }
352
+ return { result: null, errors };
353
+ }
@@ -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
+ }>;
@@ -0,0 +1,21 @@
1
+ import { resolve } from 'node:path';
2
+ async function flatten(plugins) {
3
+ const value = await plugins;
4
+ if (Array.isArray(value))
5
+ return (await Promise.all(value.map(flatten))).flat();
6
+ return value && typeof value === 'object' ? [value] : [];
7
+ }
8
+ export async function loadProject(root) {
9
+ let vite;
10
+ try {
11
+ vite = await import('vite');
12
+ }
13
+ catch {
14
+ return { sources: [], viteAliases: undefined };
15
+ }
16
+ const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, resolve(root), 'silent');
17
+ if (!loaded)
18
+ return { sources: [], viteAliases: undefined };
19
+ const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
20
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias };
21
+ }