@clarusjs/eslint-plugin 0.0.0 → 0.1.1

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/README.md CHANGED
@@ -1,3 +1,21 @@
1
1
  # @clarusjs/eslint-plugin
2
2
 
3
- Placeholder. The first release is published from [clarusjs](https://github.com/forinda/clarusjs).
3
+ Lint [clarusjs](https://github.com/forinda/clarusjs) `.tscl` components with ESLint: your rules on each `<script>`, at the line and column you wrote (and `--fix` edits the `.tscl` file), plus the template rules of `clarusjs check` as `clarusjs/template`.
4
+
5
+ ```sh
6
+ pnpm add -D eslint @clarusjs/eslint-plugin
7
+ ```
8
+
9
+ ```js
10
+ // eslint.config.js
11
+ import clarusjs from '@clarusjs/eslint-plugin'
12
+
13
+ export default [
14
+ ...clarusjs.configs.recommended,
15
+ { files: ['**/*.tscl'], rules: { 'prefer-const': 'error', 'no-unused-vars': 'error' } },
16
+ ]
17
+ ```
18
+
19
+ A component's inputs, imported data and `state`/`derived`/`shared` are known to `no-undef`; names the template uses count as used; `let x = state(…)` written by the template isn't pushed to `const`. Another parser (typescript-eslint's) goes in `parserOptions.parser`; with `typeAware: true`, type-aware rules work too, with types from the component's inputs, imported data and signals. typescript-eslint needs TypeScript 6 for now: `pnpm add -D typescript@npm:@typescript/typescript6 @typescript/native@npm:typescript@^7`. See the [Lint guide](https://clarusjs.com/guide/lint#with-eslint).
20
+
21
+ MIT licensed.
@@ -0,0 +1,37 @@
1
+ import type { ESLint, Linter, Scope } from 'eslint';
2
+ type Parser = {
3
+ parse?(code: string, options?: object): unknown;
4
+ parseForESLint?(code: string, options?: object): {
5
+ ast: unknown;
6
+ scopeManager?: unknown;
7
+ visitorKeys?: unknown;
8
+ services?: unknown;
9
+ };
10
+ };
11
+ type ScopeManager = Scope.ScopeManager & {
12
+ addGlobals?(names: string[]): void;
13
+ };
14
+ export declare const parser: {
15
+ meta: {
16
+ name: string;
17
+ };
18
+ parseForESLint(code: string, options?: {
19
+ filePath?: string;
20
+ parser?: Parser;
21
+ ecmaVersion?: Linter.EcmaVersion;
22
+ sourceType?: string;
23
+ } & Record<string, unknown>): {
24
+ ast: unknown;
25
+ visitorKeys?: unknown;
26
+ services?: unknown;
27
+ scopeManager: ScopeManager;
28
+ };
29
+ };
30
+ /** The plugin: its parser, the .tscl processor, its rules, and `configs.recommended`. */
31
+ declare const plugin: ESLint.Plugin & {
32
+ parser: typeof parser;
33
+ configs: {
34
+ recommended: Linter.Config[];
35
+ };
36
+ };
37
+ export default plugin;
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ // @clarusjs/eslint-plugin (#305): ESLint for .tscl components.
2
+ // - parser: the file with everything outside <script> blanked to spaces (newlines kept), so every offset is where it
3
+ // was: errors land on the .tscl line and column, and fixes apply to the file. Parsed by ESLint's own espree, or by
4
+ // `parserOptions.parser` (typescript-eslint, …). The file's inputs, imported data and state()/derived()/shared() are
5
+ // its globals.
6
+ // - clarusjs/uses-vars: script names the template reads count as used (no-unused-vars).
7
+ // - clarusjs/template: the template rules of `clarusjs check` (#304), with a project's own from settings.
8
+ // - parserOptions.typeAware (#339): typescript-eslint's type-aware rules on the script, types from a program built by
9
+ // type-aware.ts (TypeScript 6 until typescript-eslint runs on 7).
10
+ import { createRequire } from 'node:module';
11
+ import { lint, parse, ClarusError } from 'clarusjs/compiler';
12
+ import { declarations, fromTypescriptEslint, loadTypeScript, typeProgram } from './type-aware.js';
13
+ // ESLint's own parser and scope analyzer: dependencies of the project's eslint (a peer), loaded from there.
14
+ const fromEslint = createRequire(createRequire(import.meta.url).resolve('eslint'));
15
+ const espree = fromEslint('espree');
16
+ const eslintScope = fromEslint('eslint-scope');
17
+ const RUNTIME = ['state', 'derived', 'shared']; // what a script uses without importing (see the compiler's script.ts)
18
+ /** Every expression a template reads, as text. */
19
+ function* expressions(nodes) {
20
+ for (const n of nodes) {
21
+ if (n.type === 'expr')
22
+ yield n.expr;
23
+ else if (n.type === 'element') {
24
+ for (const a of n.attrs) {
25
+ if (a.kind === 'interp')
26
+ for (const p of a.parts) {
27
+ if (typeof p !== 'string')
28
+ yield p.expr;
29
+ }
30
+ else if (a.kind !== 'static')
31
+ yield a.expr;
32
+ }
33
+ yield* expressions(n.children);
34
+ }
35
+ else if (n.type === 'if')
36
+ for (const b of n.branches) {
37
+ if (b.cond)
38
+ yield b.cond;
39
+ yield* expressions(b.children);
40
+ }
41
+ else if (n.type === 'for') {
42
+ yield n.list;
43
+ if (n.track)
44
+ yield n.track;
45
+ yield* expressions(n.children);
46
+ if (n.empty)
47
+ yield* expressions(n.empty);
48
+ }
49
+ else if (n.type === 'fill')
50
+ yield* expressions(n.children);
51
+ else if (n.type === 'await') {
52
+ yield n.expr;
53
+ for (const kids of [n.pending, ...(n.then ? [n.then.children] : []), ...(n.catch ? [n.catch.children] : [])])
54
+ yield* expressions(kids);
55
+ }
56
+ }
57
+ }
58
+ /** The text ESLint parses: the script where it is, everything else spaces (line breaks kept). */
59
+ function blank(text, script) {
60
+ const spaces = (s) => s.replace(/[^\r\n]/g, ' ');
61
+ if (!script)
62
+ return spaces(text);
63
+ const end = script.start + script.code.length;
64
+ return spaces(text.slice(0, script.start)) + script.code + spaces(text.slice(end));
65
+ }
66
+ /** A template syntax error as ESLint reports a parsing error: at its line and column. */
67
+ function parsingError(err) {
68
+ const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
69
+ return Object.assign(new SyntaxError(message), { lineNumber: err.line, column: err.column, index: 0 });
70
+ }
71
+ export const parser = {
72
+ meta: { name: '@clarusjs/eslint-plugin/parser' },
73
+ parseForESLint(code, options = {}) {
74
+ let parsed;
75
+ try {
76
+ parsed = parse(code, options.filePath ?? 'file.tscl');
77
+ }
78
+ catch (err) {
79
+ throw err instanceof ClarusError ? parsingError(err) : err;
80
+ }
81
+ const text = blank(code, parsed.script);
82
+ const { parser: delegate, typeAware, typescript, ...rest } = options;
83
+ const parserOptions = { ecmaVersion: 'latest', sourceType: 'module', ...rest, range: true, loc: true, tokens: true, comment: true };
84
+ if (typeAware)
85
+ return typeAwareParse(code, text, parsed, options.filePath ?? 'file.tscl', delegate, parserOptions, typescript);
86
+ const result = delegate?.parseForESLint ? delegate.parseForESLint(text, parserOptions) : { ast: (delegate ?? espree).parse(text, parserOptions) };
87
+ const scopeManager = result.scopeManager ?? eslintScope.analyze(result.ast, { ecmaVersion: 2022, sourceType: 'module', ...(result.visitorKeys ? { childVisitorKeys: result.visitorKeys } : {}) });
88
+ // ponytail: addGlobals is eslint-scope's (ESLint 9.x late and 10); older ones skip it, so no-undef may report them.
89
+ scopeManager.addGlobals?.(globalsOf(parsed));
90
+ return { ...result, scopeManager };
91
+ },
92
+ };
93
+ /** The file's own globals: inputs, imported data, and the runtime's signal functions. */
94
+ const globalsOf = (parsed) => [...RUNTIME, ...parsed.inputs.map((i) => i.name), ...parsed.dataImports.flatMap((d) => importNames(d.clause))];
95
+ /**
96
+ * typescript-eslint's parse of the script followed by declarations for what it uses without importing, with the types
97
+ * of a program that has them; the declarations are then cut from the tree, so ESLint sees the file as it is.
98
+ */
99
+ function typeAwareParse(code, text, parsed, file, delegate, parserOptions, typescript) {
100
+ if (!delegate?.parseForESLint)
101
+ throw new Error("clarusjs: typeAware needs typescript-eslint's parser as parserOptions.parser (import tseslint from 'typescript-eslint', then parserOptions: { parser: tseslint.parser, typeAware: true })");
102
+ const ts = loadTypeScript(file, typescript);
103
+ const virtualFile = `${file}.ts`; // never written: the program reads it from memory
104
+ const full = text + declarations(parsed);
105
+ const program = typeProgram(ts, file, virtualFile, full);
106
+ const { project: _p, projectService: _s, ...options } = parserOptions;
107
+ const result = delegate.parseForESLint(full, { ...options, filePath: virtualFile, programs: [program] });
108
+ const ast = result.ast;
109
+ const inFile = (n) => n.range[1] <= code.length;
110
+ ast.body = ast.body.filter(inFile);
111
+ if (ast.tokens)
112
+ ast.tokens = ast.tokens.filter(inFile);
113
+ if (ast.comments)
114
+ ast.comments = ast.comments.filter(inFile);
115
+ const lines = code.split('\n');
116
+ ast.range = [ast.range[0], code.length];
117
+ ast.loc = { ...ast.loc, end: { line: lines.length, column: lines.at(-1).length } };
118
+ // The scopes of the file as ESLint sees it (without the declarations), and its globals as without typeAware.
119
+ const { analyze } = fromTypescriptEslint(file)('@typescript-eslint/scope-manager');
120
+ const scopeManager = analyze(ast, { sourceType: 'module', lib: ['esnext', 'dom'] });
121
+ scopeManager.addGlobals?.(globalsOf(parsed));
122
+ return { ...result, ast, scopeManager };
123
+ }
124
+ /** Local names an import clause binds: `{ a, b as c }` → a, c. */
125
+ function importNames(clause) {
126
+ if (!clause.startsWith('{'))
127
+ return [clause];
128
+ return clause.slice(1, -1).split(',').map((p) => p.trim()).filter((p) => p && !p.startsWith('type ')).map((p) => p.split(/\s+as\s+/).pop().trim());
129
+ }
130
+ const usesVars = {
131
+ meta: { type: 'problem', docs: { description: 'Script names the template reads count as used (for no-unused-vars)' }, schema: [] },
132
+ create(context) {
133
+ const { sourceCode } = context;
134
+ return {
135
+ Program(node) {
136
+ let nodes;
137
+ try {
138
+ nodes = parse(sourceCode.text, context.filename).nodes;
139
+ }
140
+ catch {
141
+ return;
142
+ }
143
+ const corpus = [...expressions(nodes)].join('\n');
144
+ const scope = sourceCode.getScope(node);
145
+ // The module scope's names (a script is a module), and the global scope's for scripts parsed as scripts.
146
+ for (const variable of [...scope.variables, ...(scope.childScopes[0]?.variables ?? [])]) {
147
+ if (new RegExp(`(?<![\\w$.])${variable.name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus))
148
+ sourceCode.markVariableAsUsed(variable.name, node);
149
+ }
150
+ },
151
+ };
152
+ },
153
+ };
154
+ const template = {
155
+ meta: {
156
+ type: 'problem',
157
+ docs: { description: 'The template rules of clarusjs check: unused inputs and imports, images without alt, labels and buttons without names' },
158
+ schema: [{ type: 'object', additionalProperties: { enum: ['off', 'warn', 'error'] } }],
159
+ },
160
+ create(context) {
161
+ const levels = (context.options[0] ?? {});
162
+ const own = (context.settings.clarusjs?.lintRules) ?? [];
163
+ return {
164
+ 'Program:exit'() {
165
+ let found;
166
+ try {
167
+ found = lint(context.sourceCode.text, context.filename, levels, own);
168
+ }
169
+ catch {
170
+ return;
171
+ } // the parser reports it
172
+ // One ESLint rule for them all: its severity is the configured one, and the finding's rule is in the message.
173
+ for (const m of found)
174
+ context.report({ loc: { line: m.line, column: m.column - 1 }, message: `${m.message} (${m.rule})` });
175
+ },
176
+ };
177
+ },
178
+ };
179
+ // `let x = state(…)` (or shared(store)) is a signal the template assigns (`(click)="x++"`, `[(value)]="x.name"`), where
180
+ // ESLint can't see: prefer-const's report on its declaration is dropped. The file itself is linted as it is.
181
+ const texts = new Map();
182
+ const processor = {
183
+ meta: { name: '@clarusjs/eslint-plugin/tscl' },
184
+ supportsAutofix: true,
185
+ preprocess(text, filename) {
186
+ texts.set(filename, text);
187
+ return [text];
188
+ },
189
+ postprocess(messages, filename) {
190
+ const lines = (texts.get(filename) ?? '').split('\n');
191
+ texts.delete(filename);
192
+ return messages.flat().filter((m) => m.ruleId !== 'prefer-const' || !/^[\w$]+\s*=\s*(state|shared)\s*\(/.test(lines[m.line - 1]?.slice(m.column - 1) ?? ''));
193
+ },
194
+ };
195
+ /** The plugin: its parser, the .tscl processor, its rules, and `configs.recommended`. */
196
+ const plugin = {
197
+ meta: { name: '@clarusjs/eslint-plugin' },
198
+ parser,
199
+ processors: { tscl: processor },
200
+ rules: { 'uses-vars': usesVars, template },
201
+ configs: { recommended: [] },
202
+ };
203
+ /** For .tscl files: the parser, script names the template reads marked as used, and the template rules as warnings. */
204
+ plugin.configs.recommended = [
205
+ {
206
+ name: 'clarusjs/recommended',
207
+ files: ['**/*.tscl'],
208
+ plugins: { clarusjs: plugin },
209
+ languageOptions: { parser },
210
+ processor,
211
+ rules: { 'clarusjs/uses-vars': 'error', 'clarusjs/template': 'warn' },
212
+ },
213
+ ];
214
+ export default plugin;
@@ -0,0 +1,17 @@
1
+ import type { ParsedFile } from 'clarusjs/compiler';
2
+ import type * as TS from 'typescript';
3
+ type TypeScript = typeof TS;
4
+ /** What the script uses without importing it, as TypeScript, appended after the file's own text. */
5
+ export declare function declarations(parsed: ParsedFile): string;
6
+ /** require() from where the project's typescript-eslint parser is (its TypeScript, its scope manager). */
7
+ export declare function fromTypescriptEslint(file: string): NodeJS.Require;
8
+ /**
9
+ * The TypeScript typescript-eslint runs on: the one its typescript-estree resolves from the project (or `override`).
10
+ * Throws when it isn't TypeScript 6 or older, saying what to install.
11
+ */
12
+ export declare function loadTypeScript(file: string, override?: Partial<TypeScript>): TypeScript;
13
+ /** `ts` when it is TypeScript 6 or older (with its JavaScript API); otherwise an error saying what to install. */
14
+ export declare function requireTypeScript6(ts?: Partial<TypeScript>): TypeScript;
15
+ /** A program with `virtualFile` (the .tscl file's script and declarations) as its one root. Reused between files. */
16
+ export declare function typeProgram(ts: TypeScript, file: string, virtualFile: string, text: string): TS.Program;
17
+ export {};
@@ -0,0 +1,76 @@
1
+ // Type-aware linting of .tscl scripts (#339): a TypeScript program in which the .tscl file is its script, every offset
2
+ // where it was, followed by declarations for what the script uses without importing (inputs, imported data, signals).
3
+ // typescript-eslint reads types from it; the declarations are cut from the tree ESLint sees.
4
+ //
5
+ // ponytail: built with TypeScript 6's JavaScript API, the one typescript-eslint runs on today. Once it runs on
6
+ // TypeScript 7.1, typeProgram() becomes the content mapper's program (clarusjs registered), and the TypeScript 6
7
+ // requirement goes (#342).
8
+ import { createRequire } from 'node:module';
9
+ import { dirname, resolve } from 'node:path';
10
+ /** What the script uses without importing it, as TypeScript, appended after the file's own text. */
11
+ export function declarations(parsed) {
12
+ const lines = [
13
+ 'declare function state<T>(value: T): T extends never[] ? any[] : T',
14
+ 'declare function derived<T>(fn: () => T): T',
15
+ 'declare function shared<T>(store: { get(): T }): T',
16
+ ...parsed.typeImports.map((t) => `import type ${t.clause} from ${JSON.stringify(t.from)}`),
17
+ ...parsed.dataImports.map((d) => `import ${d.clause} from ${JSON.stringify(d.from)}`),
18
+ ...parsed.types.map((t) => (t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ${t.type}` : `type ${t.name}${t.params ?? ''} = ${t.type}`)),
19
+ ...parsed.inputs.map((i) => `declare ${i.model ? 'let' : 'const'} ${i.name}: ${i.type}`),
20
+ 'export {}',
21
+ ];
22
+ return '\n' + lines.join('\n') + '\n';
23
+ }
24
+ /** require() from where the project's typescript-eslint parser is (its TypeScript, its scope manager). */
25
+ export function fromTypescriptEslint(file) {
26
+ return createRequire(createRequire(resolve(dirname(file), 'package.json')).resolve('@typescript-eslint/parser'));
27
+ }
28
+ /**
29
+ * The TypeScript typescript-eslint runs on: the one its typescript-estree resolves from the project (or `override`).
30
+ * Throws when it isn't TypeScript 6 or older, saying what to install.
31
+ */
32
+ export function loadTypeScript(file, override) {
33
+ let ts = override;
34
+ if (!ts) {
35
+ try {
36
+ ts = createRequire(fromTypescriptEslint(file).resolve('@typescript-eslint/typescript-estree'))('typescript');
37
+ }
38
+ catch { }
39
+ }
40
+ return requireTypeScript6(ts);
41
+ }
42
+ /** `ts` when it is TypeScript 6 or older (with its JavaScript API); otherwise an error saying what to install. */
43
+ export function requireTypeScript6(ts) {
44
+ if (ts && Number(ts.versionMajorMinor?.split('.')[0]) <= 6 && typeof ts.createProgram === 'function')
45
+ return ts;
46
+ throw new Error(`clarusjs: type-aware linting of .tscl files needs TypeScript 6 for typescript-eslint, which doesn't run on 7 yet; ` +
47
+ `found ${ts ? `TypeScript ${ts.version}` : 'no TypeScript'}. Install Microsoft's compatibility package as "typescript" ` +
48
+ `and keep TypeScript 7 for tsc under another name: ` +
49
+ `pnpm add -D typescript@npm:@typescript/typescript6 @typescript/native@npm:typescript@^7. ` +
50
+ `Or turn typeAware off: the other rules don't need it.`);
51
+ }
52
+ const projects = new Map(); // by tsconfig (or folder, without one)
53
+ /** Compiler options: the project's tsconfig.json (or jsconfig.json), else strict defaults with browser types. */
54
+ function compilerOptions(ts, file) {
55
+ const config = ts.findConfigFile(dirname(file), ts.sys.fileExists, 'tsconfig.json') ?? ts.findConfigFile(dirname(file), ts.sys.fileExists, 'jsconfig.json');
56
+ const defaults = { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, lib: ['lib.es2023.d.ts', 'lib.dom.d.ts'] };
57
+ if (!config)
58
+ return { key: dirname(file), options: defaults };
59
+ const read = ts.readConfigFile(config, ts.sys.readFile);
60
+ const parsed = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, dirname(config));
61
+ return { key: config, options: parsed.options };
62
+ }
63
+ /** A program with `virtualFile` (the .tscl file's script and declarations) as its one root. Reused between files. */
64
+ export function typeProgram(ts, file, virtualFile, text) {
65
+ const { key, options: own } = compilerOptions(ts, file);
66
+ let cached = projects.get(key);
67
+ if (!cached || cached.ts !== ts)
68
+ projects.set(key, (cached = { ts, options: { ...own, noEmit: true, allowJs: true, allowImportingTsExtensions: true } }));
69
+ const host = ts.createCompilerHost(cached.options, true);
70
+ const getSourceFile = host.getSourceFile.bind(host);
71
+ host.getSourceFile = (name, language, ...rest) => (name === virtualFile ? ts.createSourceFile(name, text, language, true, ts.ScriptKind.TS) : getSourceFile(name, language, ...rest));
72
+ const fileExists = host.fileExists.bind(host);
73
+ host.fileExists = (name) => name === virtualFile || fileExists(name);
74
+ cached.program = ts.createProgram([virtualFile], cached.options, host, cached.program);
75
+ return cached.program;
76
+ }
package/package.json CHANGED
@@ -1,10 +1,51 @@
1
1
  {
2
2
  "name": "@clarusjs/eslint-plugin",
3
- "version": "0.0.0",
4
- "description": "Placeholder: the first release is published from https://github.com/forinda/clarusjs",
3
+ "version": "0.1.1",
4
+ "description": "Lint clarusjs .tscl components with ESLint: their <script> blocks with your rules, and the template rules of clarusjs check",
5
5
  "license": "MIT",
6
+ "type": "module",
6
7
  "repository": {
7
8
  "type": "git",
8
- "url": "git+https://github.com/forinda/clarusjs.git"
9
+ "url": "git+https://github.com/forinda/clarusjs.git",
10
+ "directory": "packages/eslint-plugin"
11
+ },
12
+ "homepage": "https://clarusjs.com/guide/lint",
13
+ "keywords": [
14
+ "clarusjs",
15
+ "eslint",
16
+ "eslint-plugin",
17
+ "tscl"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "LICENSE",
28
+ "README.md"
29
+ ],
30
+ "peerDependencies": {
31
+ "clarusjs": ">=0.14.0",
32
+ "eslint": "^9.0.0 || ^10.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^26.6.6",
36
+ "@typescript/native": "npm:typescript@^7.0.2",
37
+ "clarusjs": "0.14.0",
38
+ "eslint": "10.15.0",
39
+ "typescript": "npm:@typescript/typescript6@6.0.2",
40
+ "typescript-eslint": "8.73.0",
41
+ "vitest": "^5.1.1"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.build.json",
48
+ "test": "vitest run",
49
+ "typecheck": "tsc --noEmit -p ."
9
50
  }
10
- }
51
+ }