@zgeoff/oxlint-config 0.3.0 → 0.5.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.
@@ -0,0 +1,609 @@
1
+ import findFunctionName from './find-function-name.js';
2
+ import isVerbMatch from './is-verb-match.js';
3
+
4
+ // each named function is a frame; I/O inside an unnamed callback counts
5
+ // against the nearest named function around it, since that name makes the
6
+ // promise, while a return counts only for the function it returns from
7
+ const verbContract = {
8
+ meta: {
9
+ type: 'problem',
10
+ messages: {
11
+ pureVerbIO:
12
+ "'{{name}}' starts with '{{verb}}', which promises no I/O, but it {{reason}} — move the I/O out, or rename it with a verb that may do I/O, such as `read` or `probe`.",
13
+ predicateNotBoolean:
14
+ "'{{name}}' starts with '{{verb}}', which promises a boolean, but it declares another return type.",
15
+ booleanWithoutPredicate:
16
+ "'{{name}}' returns a boolean and does no I/O — start its name with `is`, `has`, `can` or `should`.",
17
+ findCannotMiss:
18
+ "'{{name}}' starts with 'find', which promises it can miss, but its return type holds no null or undefined — name it `get` if it cannot miss.",
19
+ getCanMiss:
20
+ "'{{name}}' starts with 'get', which promises it cannot miss, but it can return null or undefined — name it `find`.",
21
+ },
22
+ schema: [],
23
+ },
24
+ create(context) {
25
+ const frames = [];
26
+
27
+ const findNamedFrame = () => frames.findLast((frame) => frame.name !== null) ?? null;
28
+
29
+ const markIO = (reason) => {
30
+ const frame = findNamedFrame();
31
+
32
+ if (frame !== null && frame.ioReason === null) {
33
+ frame.ioReason = reason;
34
+ }
35
+ };
36
+
37
+ // a bare `return` returns undefined as `return undefined` does
38
+ const markReturn = (argument) => {
39
+ const frame = frames.at(-1);
40
+
41
+ if (frame !== undefined && (argument === null || isNullishLiteral(argument))) {
42
+ frame.returnsNullish = true;
43
+ }
44
+ };
45
+
46
+ const enterFunction = (node) => {
47
+ const name = findFunctionName(node);
48
+
49
+ frames.push({ node, name, ioReason: null, returnsNullish: false });
50
+
51
+ // an unnamed async callback counts only through what it awaits
52
+ if (node.async && name !== null) {
53
+ markIO('is async');
54
+ }
55
+
56
+ if (node.type === 'ArrowFunctionExpression' && node.expression) {
57
+ markReturn(node.body);
58
+ }
59
+ };
60
+
61
+ const exitFunction = () => {
62
+ const frame = frames.pop();
63
+
64
+ if (frame.name !== null) {
65
+ checkFrame(context, frame);
66
+ }
67
+ };
68
+
69
+ return {
70
+ FunctionDeclaration: enterFunction,
71
+ FunctionExpression: enterFunction,
72
+ ArrowFunctionExpression: enterFunction,
73
+ 'FunctionDeclaration:exit': exitFunction,
74
+ 'FunctionExpression:exit': exitFunction,
75
+ 'ArrowFunctionExpression:exit': exitFunction,
76
+ ReturnStatement(node) {
77
+ markReturn(node.argument);
78
+ },
79
+ AwaitExpression() {
80
+ markIO('awaits');
81
+ },
82
+ ForOfStatement(node) {
83
+ if (node.await) {
84
+ markIO('awaits');
85
+ }
86
+ },
87
+ CallExpression(node) {
88
+ const frame = findNamedFrame();
89
+ const reason = frame === null ? null : findCallIO(context, node, frame.node);
90
+
91
+ if (reason !== null) {
92
+ markIO(reason);
93
+ }
94
+ },
95
+ TaggedTemplateExpression(node) {
96
+ if (isShellTarget(resolveCallTarget(context, node, node.tag))) {
97
+ markIO('runs a `$` shell command');
98
+ }
99
+ },
100
+ MemberExpression(node) {
101
+ if (isEnvRead(context, node)) {
102
+ markIO('reads the environment');
103
+ }
104
+ },
105
+ };
106
+ },
107
+ };
108
+
109
+ export default verbContract;
110
+
111
+ // the role table's verbs that promise no I/O
112
+ const pureVerbs = [
113
+ 'is',
114
+ 'has',
115
+ 'can',
116
+ 'should',
117
+ 'build',
118
+ 'parse',
119
+ 'format',
120
+ 'render',
121
+ 'pick',
122
+ 'find',
123
+ 'get',
124
+ 'collect',
125
+ 'to',
126
+ ];
127
+
128
+ const predicateVerbs = ['is', 'has', 'can', 'should', 'probe'];
129
+
130
+ // the role table's verbs that may do I/O, and common free verbs that name a
131
+ // change to the world; a call to a function named with one is I/O
132
+ const effectfulVerbs = [
133
+ 'probe',
134
+ 'read',
135
+ 'write',
136
+ 'run',
137
+ 'create',
138
+ 'remove',
139
+ 'load',
140
+ 'update',
141
+ 'send',
142
+ 'start',
143
+ 'stop',
144
+ 'wait',
145
+ 'set',
146
+ 'apply',
147
+ 'record',
148
+ 'claim',
149
+ 'open',
150
+ 'close',
151
+ 'spawn',
152
+ 'print',
153
+ 'emit',
154
+ 'release',
155
+ 'register',
156
+ 'upsert',
157
+ 'insert',
158
+ 'refresh',
159
+ 'restart',
160
+ ];
161
+
162
+ // a function returning a success flag, such as `removeFile` or `tryLock`,
163
+ // rightly returns a boolean without a predicate verb, and a framework prefix
164
+ // such as a React hook's `use` wins over the predicate verbs
165
+ const flagVerbs = [...effectfulVerbs, 'try', 'use', 'on', 'handle'];
166
+
167
+ function checkFrame(context, frame) {
168
+ const name = frame.name.name;
169
+ const returnType = frame.node.returnType?.typeAnnotation ?? null;
170
+ const pureVerb = findVerb(name, pureVerbs);
171
+ const predicateVerb = findVerb(name, predicateVerbs);
172
+ const report = (messageId, data) =>
173
+ context.report({ node: frame.name, messageId, data: { name, ...data } });
174
+
175
+ if (pureVerb !== null && frame.ioReason !== null) {
176
+ report('pureVerbIO', { verb: pureVerb, reason: frame.ioReason });
177
+ }
178
+
179
+ const localTypes = collectLocalTypes(context.sourceCode.ast);
180
+ const declared = returnType === null ? null : collectTypeKinds(returnType, localTypes);
181
+ const resolved = returnType === null ? null : collectTypeKinds(returnType, localTypes, true);
182
+
183
+ if (predicateVerb !== null && resolved !== null && !isBooleanOrOpen(resolved)) {
184
+ report('predicateNotBoolean', { verb: predicateVerb });
185
+ }
186
+
187
+ const isUnnamedFlag =
188
+ predicateVerb === null &&
189
+ frame.ioReason === null &&
190
+ declared !== null &&
191
+ declared.every((kind) => kind === 'boolean') &&
192
+ findVerb(name, flagVerbs) === null;
193
+
194
+ if (isUnnamedFlag) {
195
+ report('booleanWithoutPredicate', {});
196
+ }
197
+
198
+ const missKinds = new Set(['nullish', 'void', 'open']);
199
+
200
+ if (pureVerb === 'find' && resolved !== null && !resolved.some((kind) => missKinds.has(kind))) {
201
+ report('findCannotMiss', {});
202
+ }
203
+
204
+ const declaresMiss = resolved !== null && resolved.includes('nullish');
205
+
206
+ if (pureVerb === 'get' && (frame.returnsNullish === true || declaresMiss)) {
207
+ report('getCanMiss', {});
208
+ }
209
+ }
210
+
211
+ function findVerb(name, verbs) {
212
+ return verbs.find((verb) => isVerbMatch(name, verb)) ?? null;
213
+ }
214
+
215
+ function isBooleanOrOpen(kinds) {
216
+ return kinds.every((kind) => kind === 'boolean' || kind === 'open');
217
+ }
218
+
219
+ // the kind of each member of a declared type, read without type information:
220
+ // a union splits into its members, a reference follows the file's own type
221
+ // aliases, and `resolvePromise` reads a promise as the value it resolves to
222
+ function collectTypeKinds(type, localTypes, resolvePromise = false, seen = new Set()) {
223
+ if (type.type === 'TSUnionType') {
224
+ return type.types.flatMap((member) =>
225
+ collectTypeKinds(member, localTypes, resolvePromise, seen),
226
+ );
227
+ }
228
+
229
+ if (type.type === 'TSParenthesizedType' || isReadonlyOperator(type)) {
230
+ return collectTypeKinds(type.typeAnnotation, localTypes, resolvePromise, seen);
231
+ }
232
+
233
+ if (type.type !== 'TSTypeReference') {
234
+ return [pickTypeKind(type)];
235
+ }
236
+
237
+ const name = type.typeName.type === 'Identifier' ? type.typeName.name : null;
238
+ const alias = name === null ? undefined : localTypes.aliases.get(name);
239
+
240
+ if (alias !== undefined && !seen.has(name)) {
241
+ return collectTypeKinds(alias, localTypes, resolvePromise, new Set([...seen, name]));
242
+ }
243
+
244
+ const typeArguments = type.typeArguments ?? type.typeParameters;
245
+
246
+ if (resolvePromise && name === 'Promise' && typeArguments?.params.length === 1) {
247
+ const [value] = typeArguments.params;
248
+
249
+ return collectTypeKinds(value, localTypes, resolvePromise, seen);
250
+ }
251
+
252
+ // an interface never holds null; any other reference, such as an import or
253
+ // a type parameter, is a type the rule cannot read
254
+ return [localTypes.interfaces.has(name) ? 'value' : 'open'];
255
+ }
256
+
257
+ function isReadonlyOperator(type) {
258
+ return type.type === 'TSTypeOperator' && type.operator === 'readonly';
259
+ }
260
+
261
+ // a type whose members the rule can see and that never holds null; any other
262
+ // shape, such as an indexed access or a conditional type, is open
263
+ const valueTypes = new Set([
264
+ 'TSStringKeyword',
265
+ 'TSNumberKeyword',
266
+ 'TSBigIntKeyword',
267
+ 'TSSymbolKeyword',
268
+ 'TSObjectKeyword',
269
+ 'TSNeverKeyword',
270
+ 'TSLiteralType',
271
+ 'TSTemplateLiteralType',
272
+ 'TSArrayType',
273
+ 'TSTupleType',
274
+ 'TSTypeLiteral',
275
+ 'TSFunctionType',
276
+ 'TSConstructorType',
277
+ ]);
278
+
279
+ function pickTypeKind(type) {
280
+ if (
281
+ type.type === 'TSBooleanKeyword' ||
282
+ (type.type === 'TSTypePredicate' && !type.asserts) ||
283
+ (type.type === 'TSLiteralType' && typeof type.literal.value === 'boolean')
284
+ ) {
285
+ return 'boolean';
286
+ }
287
+
288
+ if (type.type === 'TSNullKeyword' || type.type === 'TSUndefinedKeyword') {
289
+ return 'nullish';
290
+ }
291
+
292
+ if (type.type === 'TSVoidKeyword') {
293
+ return 'void';
294
+ }
295
+
296
+ // `asserts value is T` throws instead of returning a boolean
297
+ if (type.type === 'TSTypePredicate' || valueTypes.has(type.type)) {
298
+ return 'value';
299
+ }
300
+
301
+ return 'open';
302
+ }
303
+
304
+ const localTypesByProgram = new WeakMap();
305
+
306
+ function collectLocalTypes(program) {
307
+ const cached = localTypesByProgram.get(program);
308
+
309
+ if (cached !== undefined) {
310
+ return cached;
311
+ }
312
+
313
+ const localTypes = { aliases: new Map(), interfaces: new Set() };
314
+
315
+ for (const statement of program.body) {
316
+ const declaration =
317
+ statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
318
+
319
+ if (
320
+ declaration?.type === 'TSTypeAliasDeclaration' &&
321
+ (declaration.typeParameters ?? null) === null
322
+ ) {
323
+ localTypes.aliases.set(declaration.id.name, declaration.typeAnnotation);
324
+ }
325
+
326
+ if (declaration?.type === 'TSInterfaceDeclaration') {
327
+ localTypes.interfaces.add(declaration.id.name);
328
+ }
329
+ }
330
+
331
+ localTypesByProgram.set(program, localTypes);
332
+
333
+ return localTypes;
334
+ }
335
+
336
+ function isNullishLiteral(node) {
337
+ return (
338
+ (node.type === 'Literal' && node.raw === 'null') ||
339
+ (node.type === 'Identifier' && node.name === 'undefined')
340
+ );
341
+ }
342
+
343
+ const kyselyRunMethods = new Set(['execute', 'executeTakeFirst', 'executeTakeFirstOrThrow']);
344
+ const bunIOMembers = new Set(['spawn', 'spawnSync', 'file', 'write', '$']);
345
+
346
+ function findCallIO(context, node, frameNode) {
347
+ const callee = node.callee;
348
+ const rootName = findRootName(callee);
349
+ const memberName = callee.type === 'MemberExpression' ? findMemberName(callee) : null;
350
+ const binding = rootName === null ? null : findBinding(context, node, rootName);
351
+ const target = resolveCallTarget(context, node, callee);
352
+ const targetSource = findImportSource(target.binding);
353
+
354
+ if (isShellTarget(target)) {
355
+ return 'runs a `$` shell command';
356
+ }
357
+
358
+ if (target.rootName === 'fetch' && target.binding === null && target.memberName === null) {
359
+ return 'calls `fetch`';
360
+ }
361
+
362
+ if (memberName !== null && kyselyRunMethods.has(memberName)) {
363
+ return 'runs a database query';
364
+ }
365
+
366
+ if (isBunGlobal(target) && bunIOMembers.has(target.memberName)) {
367
+ return `calls \`Bun.${target.memberName}\``;
368
+ }
369
+
370
+ if (targetSource !== null && isIOImport(targetSource, target)) {
371
+ return `calls \`${rootName}\` from \`${targetSource}\``;
372
+ }
373
+
374
+ const isOwn =
375
+ isOwnCallee({ rootName, binding, source: findImportSource(binding), memberName }, frameNode) &&
376
+ isOwnCallee({ ...target, source: targetSource }, frameNode);
377
+
378
+ if (!isOwn) {
379
+ return null;
380
+ }
381
+
382
+ // a bare method name such as `map.set` or `fn.apply` is a built-in that a
383
+ // name cannot tell from I/O, whether the call names it or an alias holds it
384
+ const names = [
385
+ {
386
+ name: callee.type === 'Identifier' ? callee.name : memberName,
387
+ isMethod: memberName !== null,
388
+ },
389
+ { name: target.memberName ?? target.rootName, isMethod: target.memberName !== null },
390
+ ];
391
+
392
+ const effectful = names.find((entry) => {
393
+ const verb = entry.name === null ? null : findVerb(entry.name, effectfulVerbs);
394
+
395
+ return verb !== null && !(entry.isMethod && entry.name === verb);
396
+ });
397
+
398
+ return effectful === undefined ? null : `calls '${effectful.name}', whose verb may do I/O`;
399
+ }
400
+
401
+ // the source a call reaches: its root binding and the member taken straight
402
+ // off the root, as `spawn` in `Bun.spawn(...)`, followed through each local
403
+ // alias such as `const read = fs.readFileSync` or `const { spawn } = Bun`
404
+ function resolveCallTarget(context, node, callee) {
405
+ const rootName = findRootName(callee);
406
+ let current = {
407
+ rootName,
408
+ binding: rootName === null ? null : findBinding(context, node, rootName),
409
+ memberName: findRootMemberName(callee),
410
+ };
411
+
412
+ for (let depth = 0; depth < 8; depth++) {
413
+ const declarator = findAliasDeclarator(current.binding);
414
+
415
+ if (declarator === null) {
416
+ return current;
417
+ }
418
+
419
+ const init = declarator.init;
420
+ const initRoot = findRootName(init);
421
+
422
+ current = {
423
+ rootName: initRoot,
424
+ binding: initRoot === null ? null : findBinding(context, init, initRoot),
425
+ memberName:
426
+ findRootMemberName(init) ??
427
+ findPatternKey(declarator.id, current.rootName) ??
428
+ current.memberName,
429
+ };
430
+ }
431
+
432
+ return current;
433
+ }
434
+
435
+ // the member read straight off a chain's root: `$` in `bun.$.cwd('a')`
436
+ function findRootMemberName(node) {
437
+ let current = node;
438
+ let memberName = null;
439
+
440
+ while (current.type === 'MemberExpression' || current.type === 'CallExpression') {
441
+ if (current.type === 'MemberExpression') {
442
+ memberName = findMemberName(current);
443
+ current = current.object;
444
+ } else {
445
+ current = current.callee;
446
+ }
447
+ }
448
+
449
+ return memberName;
450
+ }
451
+
452
+ function findAliasDeclarator(binding) {
453
+ const definition = binding?.defs[0];
454
+ const declarator = definition?.type === 'Variable' ? definition.node : null;
455
+ const init = declarator?.init ?? null;
456
+
457
+ return init !== null && (init.type === 'Identifier' || init.type === 'MemberExpression')
458
+ ? declarator
459
+ : null;
460
+ }
461
+
462
+ // the key a destructured binding takes, as `spawn` in `const { spawn: run } = Bun`
463
+ function findPatternKey(pattern, name) {
464
+ if (pattern.type !== 'ObjectPattern') {
465
+ return null;
466
+ }
467
+
468
+ const property = pattern.properties.find(
469
+ (entry) =>
470
+ entry.type === 'Property' && entry.value.type === 'Identifier' && entry.value.name === name,
471
+ );
472
+
473
+ return property === undefined ? null : findKeyName(property);
474
+ }
475
+
476
+ function findKeyName(property) {
477
+ return !property.computed && property.key.type === 'Identifier' ? property.key.name : null;
478
+ }
479
+
480
+ function isBunGlobal(target) {
481
+ return target.rootName === 'Bun' && target.binding === null;
482
+ }
483
+
484
+ // Bun's shell: the `$` export of `bun` under any import form or alias, or
485
+ // `Bun.$`; a parameter or local named `$` is some other function
486
+ function isShellTarget(target) {
487
+ if (isBunGlobal(target)) {
488
+ return target.memberName === '$';
489
+ }
490
+
491
+ if (findImportSource(target.binding) !== 'bun') {
492
+ return false;
493
+ }
494
+
495
+ const specifier = target.binding.defs[0].node;
496
+
497
+ return specifier.type === 'ImportSpecifier'
498
+ ? specifier.imported.name === '$'
499
+ : target.memberName === '$';
500
+ }
501
+
502
+ function findMemberName(member) {
503
+ return !member.computed && member.property.type === 'Identifier' ? member.property.name : null;
504
+ }
505
+
506
+ function findRootName(node) {
507
+ let current = node;
508
+
509
+ while (current.type === 'MemberExpression' || current.type === 'CallExpression') {
510
+ current = current.type === 'MemberExpression' ? current.object : current.callee;
511
+ }
512
+
513
+ if (current.type === 'ThisExpression') {
514
+ return 'this';
515
+ }
516
+
517
+ return current.type === 'Identifier' ? current.name : null;
518
+ }
519
+
520
+ // the global itself, so a local binding of the same name passes
521
+ function isGlobalName(context, node, name) {
522
+ return (
523
+ node !== undefined &&
524
+ node.type === 'Identifier' &&
525
+ node.name === name &&
526
+ findBinding(context, node, name) === null
527
+ );
528
+ }
529
+
530
+ function findBinding(context, node, name) {
531
+ let scope = context.sourceCode.getScope(node);
532
+
533
+ while (scope !== null) {
534
+ const variable = scope.set.get(name);
535
+
536
+ if (variable !== undefined && variable.defs.length > 0) {
537
+ return variable;
538
+ }
539
+
540
+ scope = scope.upper;
541
+ }
542
+
543
+ return null;
544
+ }
545
+
546
+ function findImportSource(variable) {
547
+ if (variable === null) {
548
+ return null;
549
+ }
550
+
551
+ const [definition] = variable.defs;
552
+
553
+ return definition.type === 'ImportBinding' ? definition.parent.source.value : null;
554
+ }
555
+
556
+ const ioModules = new Set(['fs', 'fs/promises', 'child_process']);
557
+
558
+ function isIOImport(source, target) {
559
+ if (ioModules.has(source.replace(/^node:/u, ''))) {
560
+ return true;
561
+ }
562
+
563
+ if (source !== 'bun') {
564
+ return false;
565
+ }
566
+
567
+ const specifier = target.binding.defs[0].node;
568
+ const imported =
569
+ specifier.type === 'ImportSpecifier' ? specifier.imported.name : target.memberName;
570
+
571
+ return bunIOMembers.has(imported);
572
+ }
573
+
574
+ // a callee declared in the file or imported by a relative or aliased path; a
575
+ // package keeps its own naming, and a method on a value the function makes
576
+ // itself, such as `date.setUTCDate`, changes only that value
577
+ function isOwnCallee(callee, frameNode) {
578
+ if (callee.rootName === 'this') {
579
+ return true;
580
+ }
581
+
582
+ if (callee.binding === null) {
583
+ return false;
584
+ }
585
+
586
+ if (callee.source !== null) {
587
+ return ['.', '/', '#', '~/', '@/'].some((prefix) => callee.source.startsWith(prefix));
588
+ }
589
+
590
+ return callee.memberName === null || !isLocalVariable(callee.binding, frameNode);
591
+ }
592
+
593
+ function isLocalVariable(binding, frameNode) {
594
+ const [definition] = binding.defs;
595
+ const [start, end] = frameNode.range;
596
+
597
+ return (
598
+ definition.type === 'Variable' &&
599
+ definition.name.range[0] >= start &&
600
+ definition.name.range[1] <= end
601
+ );
602
+ }
603
+
604
+ function isEnvRead(context, node) {
605
+ return (
606
+ findMemberName(node) === 'env' &&
607
+ (isGlobalName(context, node.object, 'process') || isGlobalName(context, node.object, 'Bun'))
608
+ );
609
+ }