@zgeoff/oxlint-config 0.10.2 → 0.10.4

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,5 +1,7 @@
1
1
  import { basename } from 'node:path';
2
2
  import buildLaneLimits from './build-lane-limits.js';
3
+ import findConstInitializer from './find-const-initializer.js';
4
+ import findVariable from './find-variable.js';
3
5
  import getImportedName from './get-imported-name.js';
4
6
  import resolveSuiteDirectory from './resolve-suite-directory.js';
5
7
 
@@ -103,6 +105,7 @@ function findRunnerName(context, callee) {
103
105
 
104
106
  const variable = findVariable(context, current);
105
107
 
108
+ // a name with no declaration reads the global that `bun test` defines
106
109
  if (variable === null) {
107
110
  return current.name;
108
111
  }
@@ -124,19 +127,6 @@ function findRunnerName(context, callee) {
124
127
  return definition.node.type === 'ImportSpecifier' ? getImportedName(definition.node) : null;
125
128
  }
126
129
 
127
- // a name with no declaration reads the global that `bun test` defines
128
- function findVariable(context, identifier) {
129
- for (let scope = context.sourceCode.getScope(identifier); scope !== null; scope = scope.upper) {
130
- const variable = scope.set.get(identifier.name);
131
-
132
- if (variable !== undefined && variable.defs.length > 0) {
133
- return variable;
134
- }
135
- }
136
-
137
- return null;
138
- }
139
-
140
130
  function emitTimeouts(context, args, limit) {
141
131
  for (const argument of args) {
142
132
  const value = argument.type === 'ObjectExpression' ? findTimeoutValue(argument) : argument;
@@ -182,16 +172,9 @@ function findNumber(context, node, seen) {
182
172
  return null;
183
173
  }
184
174
 
185
- const definition = findVariable(context, node)?.defs[0];
186
-
187
- if (
188
- definition?.type !== 'Variable' ||
189
- definition.parent.kind !== 'const' ||
190
- definition.node.id.type !== 'Identifier' ||
191
- definition.node.init === null
192
- ) {
193
- return null;
194
- }
175
+ const initializer = findConstInitializer(context, node);
195
176
 
196
- return findNumber(context, definition.node.init, new Set([...seen, node.name]));
177
+ return initializer === null
178
+ ? null
179
+ : findNumber(context, initializer, new Set([...seen, node.name]));
197
180
  }
@@ -1,8 +1,8 @@
1
1
  import { basename, dirname } from 'node:path';
2
+ import collectCreatedTables from './collect-created-tables.js';
2
3
  import collectSQLWrites from './collect-sql-writes.js';
3
4
  import collectWrittenTables from './collect-written-tables.js';
4
- import findBunTestName from './find-bun-test-name.js';
5
- import findChainRoot from './find-chain-root.js';
5
+ import findConstInitializer from './find-const-initializer.js';
6
6
  import findFunctionName from './find-function-name.js';
7
7
  import isInTestUtils from './is-in-test-utils.js';
8
8
  import isVerbMatch from './is-verb-match.js';
@@ -49,44 +49,64 @@ export default function buildSeedOnly(readFolderSources) {
49
49
  return {};
50
50
  }
51
51
 
52
- const checkWrite = (node, table) => {
53
- if (kind.inTestUtils && isInSeedFunction(node)) {
52
+ // a table the file creates is the test's own, so a write to it counts only once the whole
53
+ // file is read
54
+ const writes = [];
55
+ const createdTables = new Set();
56
+
57
+ const collectText = (node) => {
58
+ const text = toSQLText(context, node, new Set());
59
+
60
+ if (text === null) {
54
61
  return;
55
62
  }
56
63
 
57
- if (table === null) {
58
- context.report({ node, messageId: 'nonLiteral' });
59
- } else if (!kind.isTest || !readFolderTables(dirname(filename)).has(table)) {
60
- context.report({ node, messageId: 'write', data: { table } });
64
+ for (const table of collectSQLWrites(text)) {
65
+ // the statement, not its call, so a disable comment above a statement inside a
66
+ // multi-line call covers it
67
+ writes.push({ node, table });
68
+ }
69
+
70
+ for (const table of collectCreatedTables(text)) {
71
+ createdTables.add(table);
61
72
  }
62
73
  };
63
74
 
64
- const checkText = (node, text) => {
65
- if (!isTestTitle(context, node)) {
66
- for (const table of collectSQLWrites(text)) {
67
- checkWrite(node, table);
68
- }
75
+ const checkWrite = (write) => {
76
+ if ((kind.inTestUtils && isInSeedFunction(write.node)) || createdTables.has(write.table)) {
77
+ return;
78
+ }
79
+
80
+ if (write.table === null) {
81
+ context.report({ node: write.node, messageId: 'nonLiteral' });
82
+ } else if (!kind.isTest || !readFolderTables(dirname(filename)).has(write.table)) {
83
+ context.report({ node: write.node, messageId: 'write', data: { table: write.table } });
69
84
  }
70
85
  };
71
86
 
72
87
  return {
73
88
  CallExpression(node) {
74
89
  if (isKyselyWrite(node)) {
75
- checkWrite(node, findLiteralTable(node.arguments[0]));
90
+ writes.push({ node, table: findLiteralTable(node.arguments[0]) });
91
+ } else if (isKyselyCreateTable(node)) {
92
+ const table = findLiteralTable(node.arguments[0]);
93
+
94
+ if (table !== null) {
95
+ createdTables.add(table);
96
+ }
97
+ } else if (isSQLCall(context, node.callee)) {
98
+ collectText(node.arguments[0]);
76
99
  }
77
100
  },
78
- Literal(node) {
79
- if (typeof node.value === 'string') {
80
- checkText(node, node.value);
101
+ TaggedTemplateExpression(node) {
102
+ if (isSQLTag(node.tag)) {
103
+ collectText(node.quasi);
81
104
  }
82
105
  },
83
- TemplateLiteral(node) {
84
- const text = node.quasis
85
- .map((quasi) => quasi.value.cooked ?? quasi.value.raw)
86
- // oxlint-disable-next-line no-template-curly-in-string -- marks each interpolation as a module's text shows it
87
- .join('${}');
88
-
89
- checkText(node, text);
106
+ 'Program:exit'() {
107
+ for (const write of writes) {
108
+ checkWrite(write);
109
+ }
90
110
  },
91
111
  };
92
112
  },
@@ -109,6 +129,40 @@ function pickFileKind(repoPath, name) {
109
129
  return isTest || inTestUtils ? { inTestUtils, isTest } : null;
110
130
  }
111
131
 
132
+ // oxlint-disable-next-line no-template-curly-in-string -- marks an interpolation as a module's text shows it
133
+ const interpolation = '${}';
134
+
135
+ function toSQLText(context, node, seen) {
136
+ if (node?.type === 'Literal' && typeof node.value === 'string') {
137
+ return node.value;
138
+ }
139
+
140
+ if (node?.type === 'TemplateLiteral') {
141
+ return node.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(interpolation);
142
+ }
143
+
144
+ // a part the rule cannot read stands for an interpolation, so its table name counts as not a
145
+ // string literal
146
+ if (node?.type === 'BinaryExpression' && node.operator === '+') {
147
+ const left = toSQLText(context, node.left, seen);
148
+ const right = toSQLText(context, node.right, seen);
149
+
150
+ return left === null && right === null
151
+ ? null
152
+ : `${left ?? interpolation}${right ?? interpolation}`;
153
+ }
154
+
155
+ if (node?.type !== 'Identifier' || seen.has(node.name)) {
156
+ return null;
157
+ }
158
+
159
+ const initializer = findConstInitializer(context, node);
160
+
161
+ return initializer === null
162
+ ? null
163
+ : toSQLText(context, initializer, new Set([...seen, node.name]));
164
+ }
165
+
112
166
  const functionTypes = new Set([
113
167
  'FunctionDeclaration',
114
168
  'FunctionExpression',
@@ -134,20 +188,6 @@ function isInSeedFunction(node) {
134
188
  return name !== null && isVerbMatch(name.name, 'seed');
135
189
  }
136
190
 
137
- const testRunnerNames = new Set(['test', 'it', 'describe']);
138
-
139
- function isTestTitle(context, node) {
140
- const call = node.parent;
141
-
142
- if (call?.type !== 'CallExpression' || call.arguments[0] !== node) {
143
- return false;
144
- }
145
-
146
- const root = findChainRoot(call.callee, true);
147
-
148
- return root !== null && testRunnerNames.has(findBunTestName(context, root));
149
- }
150
-
151
191
  const kyselyWriteMethods = new Set(['insertInto', 'updateTable', 'deleteFrom']);
152
192
 
153
193
  function isKyselyWrite(node) {
@@ -166,3 +206,58 @@ function findLiteralTable(argument) {
166
206
  ? toTableName(argument.value)
167
207
  : null;
168
208
  }
209
+
210
+ function isKyselyCreateTable(node) {
211
+ const callee = node.callee;
212
+
213
+ return (
214
+ callee.type === 'MemberExpression' &&
215
+ !callee.computed &&
216
+ callee.property.type === 'Identifier' &&
217
+ callee.property.name === 'createTable'
218
+ );
219
+ }
220
+
221
+ // bun:sqlite and better-sqlite3 run SQL through `run`, `exec`, `query` and `prepare`, Kysely
222
+ // through `sql.raw` and `CompiledQuery.raw`, and postgres.js through `sql(…)` and `sql.unsafe`
223
+ const sqlMethods = new Set(['run', 'exec', 'query', 'prepare', 'raw', 'unsafe']);
224
+
225
+ function isSQLCall(context, callee) {
226
+ if (callee.type === 'Identifier') {
227
+ return callee.name === 'sql';
228
+ }
229
+
230
+ // a regular expression's `exec` takes prose
231
+ return (
232
+ callee.type === 'MemberExpression' &&
233
+ !callee.computed &&
234
+ callee.property.type === 'Identifier' &&
235
+ sqlMethods.has(callee.property.name) &&
236
+ !isRegularExpression(context, callee.object)
237
+ );
238
+ }
239
+
240
+ function isRegularExpression(context, node) {
241
+ if (node.type === 'Identifier') {
242
+ const initializer = findConstInitializer(context, node);
243
+
244
+ return (
245
+ initializer !== null &&
246
+ initializer.type !== 'Identifier' &&
247
+ isRegularExpression(context, initializer)
248
+ );
249
+ }
250
+
251
+ return (
252
+ node.regex !== undefined ||
253
+ ((node.type === 'NewExpression' || node.type === 'CallExpression') &&
254
+ node.callee.type === 'Identifier' &&
255
+ node.callee.name === 'RegExp')
256
+ );
257
+ }
258
+
259
+ function isSQLTag(tag) {
260
+ const name = tag.type === 'MemberExpression' && !tag.computed ? tag.property : tag;
261
+
262
+ return name.type === 'Identifier' && name.name === 'sql';
263
+ }
@@ -0,0 +1,13 @@
1
+ import { tablePattern } from './collect-sql-writes.js';
2
+ import toTableName from './to-table-name.js';
3
+
4
+ const createTablePattern = new RegExp(
5
+ String.raw`\bcreate\s+(?:(?:temp|temporary|virtual)\s+)?table\s+(?:if\s+not\s+exists\s+)?${tablePattern}`,
6
+ 'giu',
7
+ );
8
+
9
+ export default function collectCreatedTables(text) {
10
+ return [...text.matchAll(createTablePattern)]
11
+ .map((match) => toTableName(match.groups.table))
12
+ .filter((table) => table !== null);
13
+ }
@@ -1,6 +1,6 @@
1
1
  import toTableName from './to-table-name.js';
2
2
 
3
- const tablePattern = String.raw`(?<table>[^\s(),;'\x60]+)`;
3
+ export const tablePattern = String.raw`(?<table>[^\s(),;'\x60]+)`;
4
4
 
5
5
  const sqlWritePatterns = [
6
6
  new RegExp(String.raw`\binsert\s+(?:or\s+[a-z]+\s+)?into\s+${tablePattern}`, 'giu'),
@@ -1,4 +1,4 @@
1
- import { basename, join, posix, relative, sep } from 'node:path';
1
+ import { basename, join } from 'node:path';
2
2
  import buildImportSettings from './build-import-settings.js';
3
3
  import findFeatureFolder from './find-feature-folder.js';
4
4
  import pickFolderKind from './pick-folder-kind.js';
@@ -8,6 +8,8 @@ import readStalePending from './read-stale-pending.js';
8
8
  import resolveImportTarget from './resolve-import-target.js';
9
9
  import resolveRepoRoot from './resolve-repo-root.js';
10
10
  import resolveSourcePackage from './resolve-source-package.js';
11
+ import toPendingPath from './to-pending-path.js';
12
+ import toRootPath from './to-root-path.js';
11
13
 
12
14
  const looseModuleLimit = 8;
13
15
 
@@ -88,14 +90,6 @@ const featureFolders = {
88
90
 
89
91
  export default featureFolders;
90
92
 
91
- function toPendingPath(entry) {
92
- return posix.normalize(entry).replace(/(?<=.)\/+$/u, '');
93
- }
94
-
95
- function toRootPath(root, path) {
96
- return relative(root, path).split(sep).join('/') || '.';
97
- }
98
-
99
93
  function buildUtilsVisitors(file) {
100
94
  const settings = buildImportSettings(file.root);
101
95
  const check = (node) => {
@@ -1,20 +1,63 @@
1
- import { basename } from 'node:path';
1
+ import { existsSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import resolvePackageDirectory from './resolve-package-directory.js';
4
+ import resolveRepoRoot from './resolve-repo-root.js';
5
+ import toPendingPath from './to-pending-path.js';
6
+ import toRootPath from './to-root-path.js';
2
7
 
3
8
  const exemptBases = new Set(['index', 'types', 'constants']);
4
9
 
10
+ // a report on one file per repo shows once per run, and an editor's
11
+ // language server keeps it on that file across edits
12
+ const anchorFiles = new Map();
13
+
5
14
  const fileNamedForExport = {
6
15
  meta: {
7
16
  type: 'suggestion',
8
17
  messages: {
9
18
  mismatch:
10
19
  "No export of '{{file}}' is named for the file: name the main export '{{base}}' in camelCase, PascalCase or SCREAMING_SNAKE_CASE, or rename the file for its main export.",
20
+ pendingMissing:
21
+ '`{{entry}}` in the `pending` option of zgeoff/file-named-for-export names no package; remove it from `pending`.',
11
22
  },
12
- schema: [],
23
+ schema: [
24
+ {
25
+ type: 'object',
26
+ properties: { pending: { type: 'array', items: { type: 'string' } } },
27
+ additionalProperties: false,
28
+ },
29
+ ],
13
30
  },
14
31
  create(context) {
32
+ const filename = context.physicalFilename;
33
+ const root = resolveRepoRoot(filename) ?? context.cwd;
34
+ const pending = (context.options[0]?.pending ?? []).map((entry) => toPendingPath(entry));
35
+ const directory = pending.length === 0 ? null : resolvePackageDirectory(filename, root);
36
+ const isPending = directory !== null && pending.includes(toRootPath(root, directory));
37
+
38
+ if (!anchorFiles.has(root)) {
39
+ anchorFiles.set(root, filename);
40
+ }
41
+
15
42
  return {
16
43
  Program(program) {
17
- const file = basename(context.physicalFilename);
44
+ if (anchorFiles.get(root) === filename) {
45
+ const start = program.body[0]?.loc.start ?? { line: 1, column: 0 };
46
+
47
+ for (const entry of readMissingPending(root, pending)) {
48
+ context.report({
49
+ loc: { start, end: start },
50
+ messageId: 'pendingMissing',
51
+ data: { entry },
52
+ });
53
+ }
54
+ }
55
+
56
+ if (isPending) {
57
+ return;
58
+ }
59
+
60
+ const file = basename(filename);
18
61
  const [base, ...suffixes] = file.split('.');
19
62
 
20
63
  // a role suffix, such as `.config` or `.bench`, marks a file that a tool loads, and the
@@ -47,6 +90,10 @@ const fileNamedForExport = {
47
90
 
48
91
  export default fileNamedForExport;
49
92
 
93
+ function readMissingPending(root, pending) {
94
+ return pending.filter((entry) => !existsSync(join(root, entry, 'package.json')));
95
+ }
96
+
50
97
  const exportTypes = new Set([
51
98
  'ExportNamedDeclaration',
52
99
  'ExportDefaultDeclaration',
@@ -0,0 +1,15 @@
1
+ import findVariable from './find-variable.js';
2
+
3
+ export default function findConstInitializer(context, identifier) {
4
+ const definition = findVariable(context, identifier)?.defs[0];
5
+
6
+ if (
7
+ definition?.type !== 'Variable' ||
8
+ definition.parent.kind !== 'const' ||
9
+ definition.node.id.type !== 'Identifier'
10
+ ) {
11
+ return null;
12
+ }
13
+
14
+ return definition.node.init;
15
+ }
@@ -0,0 +1,11 @@
1
+ export default function findVariable(context, identifier) {
2
+ for (let scope = context.sourceCode.getScope(identifier); scope !== null; scope = scope.upper) {
3
+ const variable = scope.set.get(identifier.name);
4
+
5
+ if (variable !== undefined && variable.defs.length > 0) {
6
+ return variable;
7
+ }
8
+ }
9
+
10
+ return null;
11
+ }
package/import-zones.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { isBuiltin } from 'node:module';
2
- import { relative, sep } from 'node:path';
3
2
  import collectZoneNames from './collect-zone-names.js';
4
3
  import getZoneOptions from './get-zone-options.js';
5
4
  import importZonesSchema from './import-zones-schema.js';
@@ -9,6 +8,7 @@ import isInAnyZone from './is-in-any-zone.js';
9
8
  import loadWorkspaceManifests from './load-workspace-manifests.js';
10
9
  import resolveImportTarget from './resolve-import-target.js';
11
10
  import resolveRepoRoot from './resolve-repo-root.js';
11
+ import toRootPath from './to-root-path.js';
12
12
 
13
13
  const importZones = {
14
14
  meta: {
@@ -100,10 +100,6 @@ function loadFileState(context) {
100
100
  };
101
101
  }
102
102
 
103
- function toRootPath(root, path) {
104
- return relative(root, path).split(sep).join('/');
105
- }
106
-
107
103
  function checkUnzoned(file, program) {
108
104
  // anchor on the first statement, not offset 0, so a disable comment at the
109
105
  // top of the file covers the report
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/oxlint-config",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "description": "Shareable oxlint config: strict categories, house-style rules, and a custom JS plugin",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -73,9 +73,15 @@
73
73
  "build-seed-only.js",
74
74
  "test-beside-seed.js",
75
75
  "file-named-for-export.js",
76
+ "resolve-package-directory.js",
77
+ "to-pending-path.js",
78
+ "to-root-path.js",
76
79
  "read-folder-sources.js",
77
80
  "collect-written-tables.js",
78
81
  "collect-sql-writes.js",
82
+ "collect-created-tables.js",
83
+ "find-const-initializer.js",
84
+ "find-variable.js",
79
85
  "to-table-name.js",
80
86
  "resolve-repo-path.js",
81
87
  "is-in-test-utils.js",
@@ -0,0 +1,29 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join, relative, sep } from 'node:path';
3
+
4
+ // a folder whose `src/` holds the file wins over every `package.json` below it, so one inside
5
+ // `src/`, such as one that sets `type`, does not stand in for the package; the walk stops at the
6
+ // repo root, so a `package.json` above the checkout never counts
7
+ export default function resolvePackageDirectory(filename, root) {
8
+ let nearest = null;
9
+ let source = null;
10
+ let directory = dirname(filename);
11
+
12
+ while (true) {
13
+ if (existsSync(join(directory, 'package.json'))) {
14
+ nearest ??= directory;
15
+
16
+ if (!relative(join(directory, 'src'), filename).startsWith(`..${sep}`)) {
17
+ source = directory;
18
+ }
19
+ }
20
+
21
+ const parent = dirname(directory);
22
+
23
+ if (directory === root || parent === directory) {
24
+ return source ?? nearest;
25
+ }
26
+
27
+ directory = parent;
28
+ }
29
+ }
@@ -0,0 +1,5 @@
1
+ import { posix } from 'node:path';
2
+
3
+ export default function toPendingPath(entry) {
4
+ return posix.normalize(entry.replaceAll('\\', '/')).replace(/(?<=.)\/+$/u, '');
5
+ }
@@ -0,0 +1,5 @@
1
+ import { relative, sep } from 'node:path';
2
+
3
+ export default function toRootPath(root, path) {
4
+ return relative(root, path).split(sep).join('/') || '.';
5
+ }