clarusjs 0.15.0 → 0.16.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.
- package/dist/check/generate.js +19 -6
- package/dist/cli/check.d.ts +6 -2
- package/dist/cli/check.js +37 -13
- package/dist/cli/index.js +4 -1
- package/dist/cli/mapper.js +6 -1
- package/dist/cli/project.d.ts +2 -0
- package/dist/compiler/components.d.ts +29 -0
- package/dist/compiler/components.js +18 -0
- package/dist/compiler/element-attrs.d.ts +7 -0
- package/dist/compiler/element-attrs.js +32 -0
- package/dist/compiler/emit-client.js +6 -1
- package/dist/compiler/emit-server.js +1 -1
- package/dist/compiler/html-expr.js +1 -1
- package/dist/compiler/index.d.ts +2 -2
- package/dist/compiler/index.js +94 -7
- package/dist/compiler/ir.d.ts +4 -0
- package/dist/compiler/ir.js +3 -0
- package/dist/compiler/lint.d.ts +26 -2
- package/dist/compiler/lint.js +64 -4
- package/dist/compiler/parse.d.ts +17 -0
- package/dist/compiler/parse.js +15 -0
- package/dist/runtime/attrs.d.ts +1 -1
- package/dist/runtime/attrs.js +8 -5
- package/dist/runtime/dom.d.ts +8 -2
- package/dist/runtime/dom.js +36 -5
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loader.js +21 -1
- package/dist/vite/build.d.ts +9 -2
- package/dist/vite/build.js +20 -5
- package/dist/vite/libraries.d.ts +32 -0
- package/dist/vite/libraries.js +77 -0
- package/dist/vite/plugin.d.ts +5 -1
- package/dist/vite/plugin.js +13 -19
- package/package.json +1 -1
package/dist/check/generate.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { fragmentRoot } from '../compiler/parse.js';
|
|
2
|
+
import { ELEMENT_ATTRS, extendedAttrs } from '../compiler/element-attrs.js';
|
|
1
3
|
import { autoImport } from '../compiler/components.js';
|
|
2
4
|
import { parseExpressionAt } from 'acorn';
|
|
3
5
|
import { routeFromFile } from '../server/handler.js';
|
|
@@ -60,7 +62,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
60
62
|
emit(` from ${JSON.stringify(t.from)}\n`);
|
|
61
63
|
}
|
|
62
64
|
for (const imp of parsed.imports)
|
|
63
|
-
emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
|
|
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`);
|
|
64
66
|
for (const d of parsed.dataImports) {
|
|
65
67
|
emit('import ');
|
|
66
68
|
copy(d.clause, d.clauseStart);
|
|
@@ -101,6 +103,11 @@ export function generateTs(source, file, options = {}) {
|
|
|
101
103
|
emit('}\n');
|
|
102
104
|
const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
|
|
103
105
|
emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
|
|
106
|
+
const fragment = fragmentRoot(parsed.nodes);
|
|
107
|
+
const ext = parsed.extends && ELEMENT_ATTRS[parsed.extends.tag] ? extendedAttrs(parsed.extends.tag) : null;
|
|
108
|
+
const own = ext ? ` & Omit<{ ${Object.entries(ext).map(([k, t]) => `${JSON.stringify(k)}?: ${t}`).join('; ')} }, keyof Inputs>` : '';
|
|
109
|
+
emit(`export type Attrs = ${fragment ? '{ __cl_fragment_root_takes_no_attributes?: never }' : `__cl_Passed${own}`}\n`);
|
|
110
|
+
emit(`export type DomEvents = ${fragment ? 'never' : '__cl_Bubbling'}\n`);
|
|
104
111
|
emit('export interface Events {\n');
|
|
105
112
|
for (const e of parsed.events) {
|
|
106
113
|
emit(` ${JSON.stringify(e.name)}: `);
|
|
@@ -125,9 +132,10 @@ export function generateTs(source, file, options = {}) {
|
|
|
125
132
|
emit('\n');
|
|
126
133
|
}
|
|
127
134
|
emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
|
|
128
|
-
emit(
|
|
135
|
+
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
|
+
emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : any\n');
|
|
129
137
|
emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
|
|
130
|
-
emit('export type __cl_Passed = { id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
|
|
138
|
+
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');
|
|
131
139
|
const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
|
|
132
140
|
emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
|
|
133
141
|
for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
|
|
@@ -283,7 +291,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
283
291
|
if (component) {
|
|
284
292
|
emit(' { const ');
|
|
285
293
|
point('__cl_p', node.start, node.tag.length + 1);
|
|
286
|
-
emit(`: __cl_Readonly<${alias(node.tag)} &
|
|
294
|
+
emit(`: __cl_Readonly<${alias(node.tag)} & ${alias(node.tag)}_A> = { `);
|
|
287
295
|
for (const a of node.attrs) {
|
|
288
296
|
if (a.kind !== 'prop' || a.name !== '...')
|
|
289
297
|
continue;
|
|
@@ -292,7 +300,12 @@ export function generateTs(source, file, options = {}) {
|
|
|
292
300
|
emit('), ');
|
|
293
301
|
}
|
|
294
302
|
for (const a of node.attrs) {
|
|
295
|
-
if (a.
|
|
303
|
+
if (a.name === 'class' && (a.kind === 'static' || a.kind === 'interp')) {
|
|
304
|
+
copy(a.name, a.start);
|
|
305
|
+
emit(': undefined, ');
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (a.kind === 'static' && a.name !== 'attach') {
|
|
296
309
|
const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
|
|
297
310
|
if (quoted)
|
|
298
311
|
emit('"');
|
|
@@ -332,7 +345,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
332
345
|
const name = JSON.stringify(a.name);
|
|
333
346
|
emit(' { const ');
|
|
334
347
|
point('__cl_ev', a.start, a.name.length + 2);
|
|
335
|
-
emit(`: keyof ${alias(node.tag)}_E = ${name}; __cl_use(__cl_ev) }\n`);
|
|
348
|
+
emit(`: keyof ${alias(node.tag)}_E | ${alias(node.tag)}_D = ${name}; __cl_use(__cl_ev) }\n`);
|
|
336
349
|
emit(` ;(($event: __cl_Ev<${alias(node.tag)}_E, ${name}>, $info: { reason?: string; event?: Event; cancel(): void }) => { `);
|
|
337
350
|
guarded();
|
|
338
351
|
emit('{ ');
|
package/dist/cli/check.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type LibraryOption } from '../vite/libraries.ts';
|
|
1
2
|
import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
|
|
2
3
|
/** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
|
|
3
4
|
export type Diagnostic = {
|
|
@@ -12,7 +13,8 @@ export type CheckResult = {
|
|
|
12
13
|
diagnostics: Diagnostic[];
|
|
13
14
|
exitCode: 0 | 1;
|
|
14
15
|
text: string;
|
|
15
|
-
json: string;
|
|
16
|
+
json: string; /** With fix: the files it rewrote. */
|
|
17
|
+
fixed?: string[];
|
|
16
18
|
};
|
|
17
19
|
/** A page's .load.ts that exports load(), as an import specifier: what it returns is checked against the inputs. */
|
|
18
20
|
export declare function loaderOf(path: string): string | undefined;
|
|
@@ -25,7 +27,7 @@ export type CheckSource = {
|
|
|
25
27
|
addDependency(file: string): void;
|
|
26
28
|
}): string;
|
|
27
29
|
};
|
|
28
|
-
/** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too. */
|
|
30
|
+
/** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too; `fix`: lint fixes are written to the .tscl files first. */
|
|
29
31
|
export declare function check(options: {
|
|
30
32
|
root: string;
|
|
31
33
|
typescript?: string;
|
|
@@ -34,8 +36,10 @@ export declare function check(options: {
|
|
|
34
36
|
lint?: LintConfig;
|
|
35
37
|
lintRules?: LintRuleDef[];
|
|
36
38
|
strict?: boolean;
|
|
39
|
+
fix?: boolean;
|
|
37
40
|
components?: {
|
|
38
41
|
dirs?: string[];
|
|
39
42
|
auto?: boolean;
|
|
43
|
+
libraries?: LibraryOption[];
|
|
40
44
|
};
|
|
41
45
|
}): CheckResult;
|
package/dist/cli/check.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { componentNames } from '../vite/libraries.js';
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
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 { lint } from '../compiler/lint.js';
|
|
7
|
+
import { applyFixes, lint } from '../compiler/lint.js';
|
|
8
8
|
import { checkIcons } from '../compiler/icon.js';
|
|
9
9
|
import { parse } from '../compiler/parse.js';
|
|
10
10
|
import { resolveIcon } from '../icons.js';
|
|
@@ -51,7 +51,7 @@ function typescriptDir(root, override) {
|
|
|
51
51
|
}
|
|
52
52
|
export function check(options) {
|
|
53
53
|
const root = resolve(options.root);
|
|
54
|
-
const names =
|
|
54
|
+
const names = componentNames(root, options.components);
|
|
55
55
|
const virtualRoot = resolve(root, VIRTUAL);
|
|
56
56
|
rmSync(virtualRoot, { recursive: true, force: true });
|
|
57
57
|
const diagnostics = [];
|
|
@@ -61,11 +61,29 @@ export function check(options) {
|
|
|
61
61
|
const pageFiles = findClarusFiles(resolve(root, 'src'), ['.tscl', ...sources.map((x) => x.extension)])
|
|
62
62
|
.filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
|
|
63
63
|
const views = [];
|
|
64
|
+
const fixed = [];
|
|
64
65
|
for (const path of pageFiles) {
|
|
65
66
|
const file = posix(relative(root, path));
|
|
66
67
|
const original = readFileSync(path, 'utf8');
|
|
67
68
|
const src = sources.find((x) => path.endsWith(x.extension));
|
|
68
69
|
let source = original;
|
|
70
|
+
if (options.fix && path.endsWith('.tscl')) {
|
|
71
|
+
let next = original;
|
|
72
|
+
try {
|
|
73
|
+
next = applyFixes(original, lint(original, file, options.lint, options.lintRules));
|
|
74
|
+
}
|
|
75
|
+
catch { }
|
|
76
|
+
if (next !== original) {
|
|
77
|
+
try {
|
|
78
|
+
writeFileSync(path, next);
|
|
79
|
+
fixed.push(file);
|
|
80
|
+
source = next;
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
diagnostics.push({ file, line: 1, column: 1, severity: 'error', code: 'fix', message: `--fix could not write ${file}: ${err.message}` });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
69
87
|
try {
|
|
70
88
|
if (src)
|
|
71
89
|
source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
|
|
@@ -112,7 +130,7 @@ export function check(options) {
|
|
|
112
130
|
const virtualOf = new Map();
|
|
113
131
|
const converted = new Map(views.map((v) => [realpathSync(resolve(root, v.file)), v.source]));
|
|
114
132
|
const textOf = (p) => converted.get(realpathSync(p)) ?? readFileSync(p, 'utf8');
|
|
115
|
-
const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases);
|
|
133
|
+
const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases, names);
|
|
116
134
|
for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
|
|
117
135
|
const pkg = packageInfo(path);
|
|
118
136
|
const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
|
|
@@ -130,17 +148,22 @@ export function check(options) {
|
|
|
130
148
|
}
|
|
131
149
|
}
|
|
132
150
|
const require = createRequire(resolve(root, 'package.json'));
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
|
|
140
|
-
}
|
|
141
|
-
catch { }
|
|
151
|
+
const mapSpecifier = (spec) => {
|
|
152
|
+
try {
|
|
153
|
+
const file = realpathSync(resolveAlias(spec, aliases) ?? require.resolve(spec));
|
|
154
|
+
const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
|
|
155
|
+
if (target)
|
|
156
|
+
paths[`${spec}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
|
|
142
157
|
}
|
|
158
|
+
catch { }
|
|
159
|
+
};
|
|
160
|
+
for (const path of components) {
|
|
161
|
+
for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm))
|
|
162
|
+
mapSpecifier(m[2]);
|
|
143
163
|
}
|
|
164
|
+
for (const spec of Object.values(names ?? {}).flat())
|
|
165
|
+
if (!spec.startsWith('/') && spec.endsWith('.tscl'))
|
|
166
|
+
mapSpecifier(spec);
|
|
144
167
|
const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
|
|
145
168
|
paths['/*'] = ['../*', './virtual/*'];
|
|
146
169
|
for (const alias of aliases) {
|
|
@@ -208,5 +231,6 @@ export function check(options) {
|
|
|
208
231
|
exitCode: diagnostics.some((d) => d.severity === 'error' || options.strict) ? 1 : 0,
|
|
209
232
|
text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} ${d.severity} ${d.code}: ${d.message}`).join('\n'),
|
|
210
233
|
json: JSON.stringify(diagnostics, null, 2),
|
|
234
|
+
...(options.fix ? { fixed } : {}),
|
|
211
235
|
};
|
|
212
236
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -11,8 +11,11 @@ program
|
|
|
11
11
|
.argument('[dir]', 'project folder', '.')
|
|
12
12
|
.option('--json', 'print diagnostics as JSON')
|
|
13
13
|
.option('--strict', 'fail on lint warnings too')
|
|
14
|
+
.option('--fix', 'apply lint fixes to the .tscl files (wrapping a component\'s several roots in <fragment>, …) before checking')
|
|
14
15
|
.action(async (dir, options) => {
|
|
15
|
-
const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict });
|
|
16
|
+
const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict, fix: options.fix });
|
|
17
|
+
for (const file of result.fixed ?? [])
|
|
18
|
+
(options.json ? console.error : console.log)(`fixed ${file}`);
|
|
16
19
|
if (options.json)
|
|
17
20
|
console.log(result.json);
|
|
18
21
|
else if (result.diagnostics.length) {
|
package/dist/cli/mapper.js
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
3
3
|
import { generateTolerant } from '../check/generate.js';
|
|
4
4
|
import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
5
|
+
import { readComponents } from '../vite/libraries.js';
|
|
5
6
|
import { findClarusFiles } from '../vite/build.js';
|
|
6
7
|
import { loaderOf } from './check.js';
|
|
7
8
|
function namesFor(fileName) {
|
|
@@ -11,11 +12,15 @@ function namesFor(fileName) {
|
|
|
11
12
|
return undefined;
|
|
12
13
|
root = dirname(root);
|
|
13
14
|
}
|
|
15
|
+
const written = readComponents(root);
|
|
14
16
|
const files = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
|
|
15
17
|
const rel = (path) => { const r = relative(dirname(fileName), resolve(root, path.slice(1))).split(sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
|
|
16
18
|
const names = {};
|
|
17
|
-
for (const [name, path] of Object.entries(componentIndex(files, COMPONENT_DIRS).names))
|
|
19
|
+
for (const [name, path] of Object.entries(componentIndex(files, written?.dirs ?? COMPONENT_DIRS).names))
|
|
18
20
|
names[name] = Array.isArray(path) ? path.map(rel) : rel(path);
|
|
21
|
+
for (const [name, path] of Object.entries(written?.names ?? {}))
|
|
22
|
+
if (!(name in names) && ![path].flat().some((p) => p.startsWith('/')))
|
|
23
|
+
names[name] = path;
|
|
19
24
|
return names;
|
|
20
25
|
}
|
|
21
26
|
export function transform(params) {
|
package/dist/cli/project.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { LibraryOption } from '../vite/libraries.ts';
|
|
1
2
|
import type { CheckSource } from './check.ts';
|
|
2
3
|
import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
3
4
|
type Project = {
|
|
@@ -8,6 +9,7 @@ type Project = {
|
|
|
8
9
|
components?: {
|
|
9
10
|
dirs?: string[];
|
|
10
11
|
auto?: boolean;
|
|
12
|
+
libraries?: LibraryOption[];
|
|
11
13
|
};
|
|
12
14
|
};
|
|
13
15
|
export declare function loadProject(root: string): Promise<Project>;
|
|
@@ -25,6 +25,35 @@ export declare function componentIndex(files: string[], dirs: string[]): {
|
|
|
25
25
|
names: ComponentNames;
|
|
26
26
|
skipped: string[];
|
|
27
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* A component library an app uses, resolved: its package `name`, the `prefix` of its tags, and its `.tscl` files
|
|
30
|
+
* (posix, relative to the folder its package.json's `clarusjs.components` names).
|
|
31
|
+
* @since 0.16.0
|
|
32
|
+
* @see https://clarusjs.com/guide/components#components-from-libraries
|
|
33
|
+
*/
|
|
34
|
+
export type Library = {
|
|
35
|
+
name: string;
|
|
36
|
+
prefix: string;
|
|
37
|
+
files: string[];
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Name each library component: its prefix, folders and file joined with hyphens (`ui` + `dialog.tscl` → `ui-dialog`),
|
|
41
|
+
* imported as `<package>/<file>`. Only kebab-case names with a hyphen; a name two libraries share is ambiguous.
|
|
42
|
+
* @example
|
|
43
|
+
* libraryNames([{ name: '@clarusjs/ui-primitives', prefix: 'ui', files: ['dialog.tscl'] }])
|
|
44
|
+
* // { 'ui-dialog': '@clarusjs/ui-primitives/dialog.tscl' }
|
|
45
|
+
* @since 0.16.0
|
|
46
|
+
* @see https://clarusjs.com/guide/components#components-from-libraries
|
|
47
|
+
*/
|
|
48
|
+
export declare function libraryNames(libraries: Library[]): ComponentNames;
|
|
49
|
+
/**
|
|
50
|
+
* The app's own component names with the libraries' added: a name the app's own components have stays theirs.
|
|
51
|
+
* @example
|
|
52
|
+
* withLibraries(componentIndex(files, COMPONENT_DIRS).names, libraryNames(libraries))
|
|
53
|
+
* @since 0.16.0
|
|
54
|
+
* @see https://clarusjs.com/guide/components#components-from-libraries
|
|
55
|
+
*/
|
|
56
|
+
export declare function withLibraries(own: ComponentNames, libraries: ComponentNames): ComponentNames;
|
|
28
57
|
/**
|
|
29
58
|
* Add an import for each component tag the template uses that `names` knows and the file doesn't import itself (only
|
|
30
59
|
* those). A tag that names two components is a located error. Other hyphenated tags stay HTML (web components).
|
|
@@ -29,6 +29,24 @@ export function componentIndex(files, dirs) {
|
|
|
29
29
|
names[name] = paths.length === 1 ? paths[0] : paths;
|
|
30
30
|
return { names, skipped };
|
|
31
31
|
}
|
|
32
|
+
export function libraryNames(libraries) {
|
|
33
|
+
const found = new Map();
|
|
34
|
+
for (const lib of libraries) {
|
|
35
|
+
for (const file of [...lib.files].sort()) {
|
|
36
|
+
if (!file.endsWith('.tscl'))
|
|
37
|
+
continue;
|
|
38
|
+
const segments = [...(lib.prefix ? [lib.prefix] : []), ...file.slice(0, -'.tscl'.length).split('/')];
|
|
39
|
+
const name = segments.join('-');
|
|
40
|
+
if (!segments.every((s) => KEBAB.test(s)) || !name.includes('-'))
|
|
41
|
+
continue;
|
|
42
|
+
found.set(name, [...(found.get(name) ?? []), `${lib.name}/${file}`]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return Object.fromEntries([...found].map(([name, paths]) => [name, paths.length === 1 ? paths[0] : paths]));
|
|
46
|
+
}
|
|
47
|
+
export function withLibraries(own, libraries) {
|
|
48
|
+
return { ...libraries, ...own };
|
|
49
|
+
}
|
|
32
50
|
export function autoImport(parsed, names, file, source) {
|
|
33
51
|
const imported = new Set(parsed.imports.map((i) => i.name));
|
|
34
52
|
const walk = (nodes) => {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Each supported element's own attributes (lowercase names) and their types.
|
|
3
|
+
* @internal The compiler and check read it.
|
|
4
|
+
*/
|
|
5
|
+
export declare const ELEMENT_ATTRS: Record<string, Record<string, string>>;
|
|
6
|
+
/** The attributes `@extends tag` passes through: the element's and the global ones. */
|
|
7
|
+
export declare function extendedAttrs(tag: string): Record<string, string>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const B = 'boolean';
|
|
2
|
+
const S = 'string';
|
|
3
|
+
const N = 'string | number';
|
|
4
|
+
const union = (...values) => values.map((v) => JSON.stringify(v)).join(' | ');
|
|
5
|
+
const GLOBAL = {
|
|
6
|
+
title: S, accesskey: S, autofocus: B, inert: B, popover: `${union('auto', 'manual', 'hint')} | ''`, spellcheck: `${B} | ${union('true', 'false')}`,
|
|
7
|
+
translate: union('yes', 'no'), draggable: union('true', 'false'), contenteditable: `${B} | ${union('true', 'false', 'plaintext-only')}`,
|
|
8
|
+
enterkeyhint: union('enter', 'done', 'go', 'next', 'previous', 'search', 'send'), inputmode: union('none', 'text', 'decimal', 'numeric', 'tel', 'search', 'email', 'url'),
|
|
9
|
+
autocapitalize: union('off', 'none', 'on', 'sentences', 'words', 'characters'),
|
|
10
|
+
};
|
|
11
|
+
const FORM_FIELD = { disabled: B, form: S, name: S };
|
|
12
|
+
const SUBMIT = { formaction: S, formenctype: S, formmethod: union('get', 'post', 'dialog'), formnovalidate: B, formtarget: S };
|
|
13
|
+
export const ELEMENT_ATTRS = {
|
|
14
|
+
button: { ...FORM_FIELD, ...SUBMIT, type: union('submit', 'reset', 'button'), value: N, popovertarget: S, popovertargetaction: union('toggle', 'show', 'hide'), command: S, commandfor: S },
|
|
15
|
+
input: {
|
|
16
|
+
...FORM_FIELD, ...SUBMIT, type: S, value: N, checked: B, placeholder: S, required: B, readonly: B, multiple: B, min: N, max: N, step: N,
|
|
17
|
+
minlength: N, maxlength: N, pattern: S, size: N, accept: S, alt: S, src: S, width: N, height: N, list: S, autocomplete: S, dirname: S, capture: S,
|
|
18
|
+
popovertarget: S, popovertargetaction: union('toggle', 'show', 'hide'),
|
|
19
|
+
},
|
|
20
|
+
textarea: { ...FORM_FIELD, value: S, placeholder: S, required: B, readonly: B, rows: N, cols: N, minlength: N, maxlength: N, wrap: union('soft', 'hard', 'off'), autocomplete: S, dirname: S },
|
|
21
|
+
select: { ...FORM_FIELD, value: S, required: B, multiple: B, size: N, autocomplete: S },
|
|
22
|
+
option: { disabled: B, label: S, selected: B, value: N },
|
|
23
|
+
a: { href: S, target: S, download: `${S} | ${B}`, rel: S, hreflang: S, type: S, referrerpolicy: S, ping: S },
|
|
24
|
+
img: { src: S, alt: S, srcset: S, sizes: S, width: N, height: N, loading: union('eager', 'lazy'), decoding: union('sync', 'async', 'auto'), fetchpriority: union('high', 'low', 'auto'), crossorigin: S, referrerpolicy: S, usemap: S, ismap: B },
|
|
25
|
+
form: { action: S, method: union('get', 'post', 'dialog'), enctype: S, target: S, novalidate: B, autocomplete: union('on', 'off'), name: S, rel: S, 'accept-charset': S },
|
|
26
|
+
label: { for: S },
|
|
27
|
+
details: { open: B, name: S },
|
|
28
|
+
dialog: { open: B, closedby: union('any', 'closerequest', 'none') },
|
|
29
|
+
};
|
|
30
|
+
export function extendedAttrs(tag) {
|
|
31
|
+
return { ...GLOBAL, ...ELEMENT_ATTRS[tag] };
|
|
32
|
+
}
|
|
@@ -30,6 +30,7 @@ export function emitClient(ir, hot) {
|
|
|
30
30
|
all.some((n) => n.kind === 'component' && !!n.listens?.length) && 'listen as __cl_listen',
|
|
31
31
|
all.some((n) => n.kind === 'use') && 'use as __cl_useOn',
|
|
32
32
|
ir.sends && 'emit as __cl_emit',
|
|
33
|
+
ir.sends && 'declare as __cl_declare',
|
|
33
34
|
ir.provides && 'provideOn as __cl_provideOn',
|
|
34
35
|
kinds.has('model') && 'modelInput as __cl_modelInput',
|
|
35
36
|
ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
|
|
@@ -58,6 +59,8 @@ export function emitClient(ir, hot) {
|
|
|
58
59
|
out += `${line}\n`;
|
|
59
60
|
out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
|
|
60
61
|
out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
|
|
62
|
+
if (ir.sends)
|
|
63
|
+
out += ` __cl_declare(__cl_root, ${JSON.stringify(ir.sendNames)})\n`;
|
|
61
64
|
if (ir.sends)
|
|
62
65
|
out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
|
|
63
66
|
out += contextLines(ir, 'undefined');
|
|
@@ -123,7 +126,9 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
123
126
|
lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
|
|
124
127
|
for (const l of n.listens ?? []) {
|
|
125
128
|
const body = rewriteClient(l.handler, signals).trim();
|
|
126
|
-
|
|
129
|
+
const from = ir.imports.find((i) => i.name === n.name)?.from ?? '';
|
|
130
|
+
const bound = (from.split(/[\\/]/).pop() ?? '').replace(/\.tscl$/, '').replace(/[^\w-]/g, '');
|
|
131
|
+
lines.push(`__cl_listen(${ctx}, ${n.region}, ${JSON.stringify(l.name)}, ($event, $info) => { ${body}${body.includes('//') ? '\n ' : ' '}}, ${JSON.stringify(bound)})`);
|
|
127
132
|
}
|
|
128
133
|
}
|
|
129
134
|
if (n.kind === 'if' && n.block >= 0) {
|
|
@@ -42,7 +42,7 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
|
42
42
|
out += inputsLine(ir);
|
|
43
43
|
out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
|
|
44
44
|
if (html.includes('__cl_attrs'))
|
|
45
|
-
out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))})\n`;
|
|
45
|
+
out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))}${ir.extends ? `, ${JSON.stringify(ir.extends)}` : ''})\n`;
|
|
46
46
|
out += contextLines(ir, '__cl_opts?.cx');
|
|
47
47
|
if (ir.script)
|
|
48
48
|
out += indentScript(rewriteServer(ir.script));
|
|
@@ -16,7 +16,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
|
|
|
16
16
|
if (n.kind === 'connect' || n.kind === 'use')
|
|
17
17
|
return '""';
|
|
18
18
|
if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
|
|
19
|
-
return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) =>
|
|
19
|
+
return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
|
|
20
20
|
if (n.kind === 'attr' && n.name === '...')
|
|
21
21
|
return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
|
|
22
22
|
if (n.kind === 'attr')
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -2,10 +2,10 @@ import { ClarusError } from './errors.ts';
|
|
|
2
2
|
import { type ComponentNames } from './components.ts';
|
|
3
3
|
export { ClarusError } from './errors.ts';
|
|
4
4
|
export { parse } from './parse.ts';
|
|
5
|
-
export { componentIndex, COMPONENT_DIRS, type ComponentNames } from './components.ts';
|
|
5
|
+
export { componentIndex, COMPONENT_DIRS, libraryNames, withLibraries, type ComponentNames, type Library } from './components.ts';
|
|
6
6
|
export { checkIcons, type IconResolver } from './icon.ts';
|
|
7
7
|
import type { IconResolver } from './icon.ts';
|
|
8
|
-
export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
|
|
8
|
+
export { applyFixes, lint, lintRules, type LintFix, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
|
|
9
9
|
export type { ParsedFile, InputDecl, EventDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
|
|
10
10
|
/**
|
|
11
11
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
package/dist/compiler/index.js
CHANGED
|
@@ -3,22 +3,26 @@ import { ClarusError } from './errors.js';
|
|
|
3
3
|
import { emitServer } from './emit-server.js';
|
|
4
4
|
import { lower, SPREAD_REFUSED } from './ir.js';
|
|
5
5
|
import { autoImport } from './components.js';
|
|
6
|
-
import {
|
|
6
|
+
import { ELEMENT_ATTRS } from './element-attrs.js';
|
|
7
|
+
import { awaitLists, fragmentRoot, parse, rootNodes } from './parse.js';
|
|
7
8
|
export { ClarusError } from './errors.js';
|
|
8
9
|
export { parse } from './parse.js';
|
|
9
|
-
export { componentIndex, COMPONENT_DIRS } from './components.js';
|
|
10
|
+
export { componentIndex, COMPONENT_DIRS, libraryNames, withLibraries } from './components.js';
|
|
10
11
|
import { foldClass } from './class-style.js';
|
|
11
12
|
export { checkIcons } from './icon.js';
|
|
12
|
-
export { lint, lintRules } from './lint.js';
|
|
13
|
+
export { applyFixes, lint, lintRules } from './lint.js';
|
|
13
14
|
export function compile(source, options) {
|
|
14
15
|
const parsed = parse(source, options.file);
|
|
16
|
+
checkExtends(parsed, options.file, source);
|
|
17
|
+
const fragmentRoot = unwrapFragments(parsed, options.file, source);
|
|
15
18
|
if (options.components)
|
|
16
19
|
autoImport(parsed, options.components, options.file, source);
|
|
17
20
|
if (options.layouts?.length && parsed.layout !== 'none')
|
|
18
21
|
wrapInLayouts(parsed, options.layouts, options.file, source);
|
|
19
22
|
const warnings = [];
|
|
20
23
|
const id = options.scope ?? scopeId(options.file);
|
|
21
|
-
|
|
24
|
+
if (!fragmentRoot)
|
|
25
|
+
fallThrough(parsed);
|
|
22
26
|
foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
|
|
23
27
|
markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
|
|
24
28
|
let css = '';
|
|
@@ -84,10 +88,93 @@ function markSlotContent(nodes, cls, components) {
|
|
|
84
88
|
}
|
|
85
89
|
}
|
|
86
90
|
const ID_LISTS = ['aria-describedby', 'aria-labelledby', 'aria-controls', 'aria-owns'];
|
|
91
|
+
function checkExtends(parsed, file, source) {
|
|
92
|
+
const ext = parsed.extends;
|
|
93
|
+
if (!ext)
|
|
94
|
+
return;
|
|
95
|
+
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
96
|
+
if (!ELEMENT_ATTRS[ext.tag])
|
|
97
|
+
fail(`@extends ${ext.tag}: clarusjs knows the attributes of ${Object.keys(ELEMENT_ATTRS).join(', ')}`, ext.start);
|
|
98
|
+
const top = rootNodes;
|
|
99
|
+
const nodes = top(parsed.nodes);
|
|
100
|
+
const is = (list) => list.length === 1 && list[0].type === 'element' && list[0].tag === ext.tag;
|
|
101
|
+
const spread = (el) => el.type === 'element' && el.attrs.some((a) => a.kind === 'prop' && a.name === '...');
|
|
102
|
+
for (const r of [nodes, ...(nodes[0]?.type === 'if' ? nodes[0].branches.map((b) => top(b.children)) : [])])
|
|
103
|
+
if (is(r) && spread(r[0]))
|
|
104
|
+
fail(`@extends ${ext.tag}: its root has its own [...] spread, which takes the place of the attributes passed to it; pass what it spreads as inputs instead`, r[0].start);
|
|
105
|
+
if (is(nodes))
|
|
106
|
+
return;
|
|
107
|
+
const first = nodes[0];
|
|
108
|
+
const wrong = `@extends ${ext.tag}: the root must be a <${ext.tag}>, where the attributes land`;
|
|
109
|
+
if (nodes.length !== 1 || first.type !== 'if')
|
|
110
|
+
return fail(wrong, (nodes[0] ?? { start: ext.start }).start);
|
|
111
|
+
if (parsed.script || parsed.inputs.some((i) => i.model))
|
|
112
|
+
fail(`@extends ${ext.tag}: an island's root must be one <${ext.tag}> (it re-renders an @if in the browser, without the passed attributes)`, first.start);
|
|
113
|
+
if (first.branches.at(-1).cond !== null || !first.branches.every((b) => is(top(b.children))))
|
|
114
|
+
fail(wrong, first.start);
|
|
115
|
+
}
|
|
116
|
+
function unwrapFragments(parsed, file, source) {
|
|
117
|
+
const reserved = parsed.imports.find((i) => i.name === 'fragment');
|
|
118
|
+
if (reserved)
|
|
119
|
+
throw new ClarusError('fragment is reserved: <fragment> groups elements without rendering one; import the component under another name', file, source, reserved.start);
|
|
120
|
+
const isNode = (x) => !!x && typeof x === 'object' && 'type' in x;
|
|
121
|
+
const holders = (n) => {
|
|
122
|
+
const out = [];
|
|
123
|
+
for (const v of Object.values(n)) {
|
|
124
|
+
const items = Array.isArray(v) ? v : [v];
|
|
125
|
+
for (const x of items)
|
|
126
|
+
if (x && typeof x === 'object' && !isNode(x) && Array.isArray(x.children))
|
|
127
|
+
out.push(x);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
};
|
|
131
|
+
const flat = (nodes) => nodes.flatMap((n) => {
|
|
132
|
+
if ('children' in n)
|
|
133
|
+
n.children = flat(n.children);
|
|
134
|
+
const r = n;
|
|
135
|
+
for (const key of ['pending', 'empty'])
|
|
136
|
+
if (Array.isArray(r[key]))
|
|
137
|
+
r[key] = flat(r[key]);
|
|
138
|
+
for (const h of holders(n))
|
|
139
|
+
h.children = flat(h.children);
|
|
140
|
+
if (n.type !== 'element' || n.tag !== 'fragment')
|
|
141
|
+
return [n];
|
|
142
|
+
if (n.attrs.length)
|
|
143
|
+
throw new ClarusError('<fragment> renders no element: attributes and events can\'t land on it', file, source, n.start);
|
|
144
|
+
return n.children;
|
|
145
|
+
});
|
|
146
|
+
const root = fragmentRoot(parsed.nodes);
|
|
147
|
+
parsed.nodes = parsed.nodes.flatMap((n) => {
|
|
148
|
+
if (n.type !== 'element' || n.tag !== 'fragment' || n.attrs.length)
|
|
149
|
+
return [n];
|
|
150
|
+
const kept = n.children.filter((c) => !(c.type === 'text' && !c.value.trim()));
|
|
151
|
+
const head = kept[0];
|
|
152
|
+
if (head?.type === 'text')
|
|
153
|
+
kept[0] = { ...head, value: head.value.replace(/^[ \t]*\r?\n/, '') };
|
|
154
|
+
return kept;
|
|
155
|
+
});
|
|
156
|
+
parsed.nodes = flat(parsed.nodes);
|
|
157
|
+
return root;
|
|
158
|
+
}
|
|
87
159
|
function fallThrough(parsed) {
|
|
88
|
-
const
|
|
89
|
-
const
|
|
90
|
-
if (meaningful.length !== 1
|
|
160
|
+
const meaningfulOf = (nodes) => nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
|
|
161
|
+
const meaningful = meaningfulOf(parsed.nodes);
|
|
162
|
+
if (meaningful.length !== 1)
|
|
163
|
+
return;
|
|
164
|
+
const top = meaningful[0];
|
|
165
|
+
if (top.type === 'if') {
|
|
166
|
+
const roots = top.branches.map((b) => meaningfulOf(b.children));
|
|
167
|
+
if (parsed.script || parsed.inputs.some((i) => i.model) || top.branches.at(-1).cond !== null || roots.some((r) => r.length !== 1 || r[0].type !== 'element'))
|
|
168
|
+
return;
|
|
169
|
+
for (const [r] of roots)
|
|
170
|
+
fallOnto(parsed, r);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (top.type === 'element')
|
|
174
|
+
fallOnto(parsed, top);
|
|
175
|
+
}
|
|
176
|
+
function fallOnto(parsed, root) {
|
|
177
|
+
if (SPREAD_REFUSED.has(root.tag.toLowerCase()))
|
|
91
178
|
return;
|
|
92
179
|
if (root.attrs.some((a) => a.kind === 'prop' && a.name === '...'))
|
|
93
180
|
return;
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -109,6 +109,8 @@ export type ComponentIR = {
|
|
|
109
109
|
file: string;
|
|
110
110
|
name: string;
|
|
111
111
|
inputs: InputDecl[];
|
|
112
|
+
/** `@extends tag`: the attribute names passed through to the root besides the usual ones. */
|
|
113
|
+
extends?: string[];
|
|
112
114
|
imports: ImportDecl[];
|
|
113
115
|
script?: string;
|
|
114
116
|
scriptImports: string[];
|
|
@@ -125,6 +127,8 @@ export type ComponentIR = {
|
|
|
125
127
|
events: IREvent[];
|
|
126
128
|
/** The component sends events to its parent (@event, #442): its script gets emit(). */
|
|
127
129
|
sends: boolean;
|
|
130
|
+
/** Their names: the parent's (name) listens for these as component events, not DOM events. */
|
|
131
|
+
sendNames: string[];
|
|
128
132
|
/** @context declarations (#465): values read from the components around this one. */
|
|
129
133
|
contexts: InputDecl[];
|
|
130
134
|
/** The script calls provide() (#465): this component adds to the context its children render with. */
|
package/dist/compiler/ir.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { extendedAttrs } from './element-attrs.js';
|
|
1
2
|
import { parseExpressionAt } from 'acorn';
|
|
2
3
|
import { iconElement } from './icon.js';
|
|
3
4
|
import { ClarusError } from './errors.js';
|
|
@@ -518,6 +519,7 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
518
519
|
file,
|
|
519
520
|
name: file.split('/').pop().replace(/\.tscl$/, ''),
|
|
520
521
|
inputs: parsed.inputs,
|
|
522
|
+
...(parsed.extends ? { extends: Object.keys(extendedAttrs(parsed.extends.tag)) } : {}),
|
|
521
523
|
imports: parsed.imports,
|
|
522
524
|
script: parsed.script ? split.body : undefined,
|
|
523
525
|
scriptImports: split.imports.map((imp) => imp.text),
|
|
@@ -528,6 +530,7 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
528
530
|
nodes,
|
|
529
531
|
events,
|
|
530
532
|
sends: parsed.events.length > 0,
|
|
533
|
+
sendNames: parsed.events.map((e) => e.name),
|
|
531
534
|
contexts: parsed.contexts,
|
|
532
535
|
provides,
|
|
533
536
|
warnings,
|