@naturalcycles/dev-lib 20.75.0 → 20.76.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.
@@ -1,5 +1,3 @@
1
- import { _last } from '@naturalcycles/js-lib/array/array.util.js'
2
-
3
1
  export class CollectReporter {
4
2
  constructor(cfg = {}) {
5
3
  this.cfg = cfg
@@ -7,7 +5,8 @@ export class CollectReporter {
7
5
 
8
6
  onTestModuleEnd(testModule) {
9
7
  const { threshold = 0 } = this.cfg
10
- const shortModuleId = _last(testModule.moduleId.split('/'))
8
+ // oxlint-disable-next-line nc/prefer-last -- no js-lib import in this reporter, for performance
9
+ const shortModuleId = testModule.moduleId.split('/').at(-1)
11
10
 
12
11
  const selfTimeMap = {}
13
12
  const totalTimeMap = {}
@@ -5,6 +5,7 @@ type Rule = Parameters<RuleTester['run']>[1]
5
5
  declare const ncPlugin: {
6
6
  meta: { name: string }
7
7
  rules: {
8
+ 'no-singleton-self-reference': Rule
8
9
  'prefer-assert': Rule
9
10
  'prefer-env-destructuring': Rule
10
11
  'prefer-last': Rule
@@ -45,7 +45,6 @@ const preferAssertRule = {
45
45
  return {
46
46
  IfStatement(node) {
47
47
  if (node.alternate || node.parent.type === 'IfStatement') return
48
- if (!isAssertableTest(node.test)) return
49
48
 
50
49
  const { consequent } = node
51
50
  const statement =
@@ -59,11 +58,14 @@ const preferAssertRule = {
59
58
  error.type !== 'NewExpression' ||
60
59
  error.callee.type !== 'Identifier' ||
61
60
  !ASSERTABLE_ERRORS.has(error.callee.name) ||
62
- error.arguments.length > maxArguments(error.callee.name) ||
63
- error.arguments.some(argument => containsEvaluation(argument))
61
+ error.arguments.length > maxArguments(error.callee.name)
64
62
  ) {
65
63
  return
66
64
  }
65
+ // The checks below walk subtrees, so they run after the cheap shape checks above: most `if`
66
+ // statements do not throw and never reach them
67
+ if (!isAssertableTest(node.test)) return
68
+ if (error.arguments.some(argument => containsEvaluation(argument))) return
67
69
  const narrowed = referencedNames(node.test)
68
70
  if (error.arguments.some(argument => referencesAny(argument, narrowed))) return
69
71
 
@@ -140,6 +142,247 @@ function visit(node, fn) {
140
142
  return false
141
143
  }
142
144
 
145
+ // Report-only, like the rules above: `this` is only the same object while the method is called on
146
+ // the instance, so a method handed over unbound (`router.get(path, service.handle)`) needs a look
147
+ const noSingletonSelfReferenceRule = {
148
+ meta: {
149
+ type: 'suggestion',
150
+ docs: {
151
+ description:
152
+ 'Inside a class, use `this` rather than the single instance of that class declared in the same file',
153
+ },
154
+ messages: {
155
+ useThis: 'Use `this` instead of {{name}} inside {{className}}',
156
+ },
157
+ },
158
+ create(context) {
159
+ const { sourceCode } = context
160
+ const classes = []
161
+ const instantiations = []
162
+
163
+ return {
164
+ ClassDeclaration(node) {
165
+ // `export default class {}` has no name to be instantiated by
166
+ if (node.id && isModuleLevel(node)) classes.push(node)
167
+ },
168
+ NewExpression(node) {
169
+ if (node.callee.type === 'Identifier') instantiations.push(node)
170
+ },
171
+ 'Program:exit'() {
172
+ for (const classNode of classes) {
173
+ const className = classNode.id.name
174
+ // Every `new ClassName()` that refers to this class, wherever it is in the file
175
+ const ownInstantiations = instantiations.filter(
176
+ node => node.callee.name === className && !isShadowed(node, className, null),
177
+ )
178
+ // With several instances in the file, the one named is not necessarily `this`
179
+ if (ownInstantiations.length !== 1) continue
180
+ const [instantiation] = ownInstantiations
181
+ const declarator = instantiation.parent
182
+ if (!isModuleLevelConst(declarator, instantiation)) continue
183
+
184
+ const name = declarator.id.name
185
+ const classSource = sourceCode.text.slice(classNode.start, classNode.end)
186
+ if (!new RegExp(String.raw`(?<![\w$])${escapeRegExp(name)}(?![\w$])`).test(classSource)) {
187
+ continue
188
+ }
189
+ forEachValueIdentifier(classNode.body, name, node => {
190
+ if (isInstanceCodeOf(node, classNode) && !isShadowed(node, name, classNode)) {
191
+ context.report({ node, messageId: 'useThis', data: { name, className } })
192
+ }
193
+ })
194
+ }
195
+ },
196
+ }
197
+ },
198
+ }
199
+
200
+ function escapeRegExp(text) {
201
+ return text.replaceAll('$', String.raw`\$`)
202
+ }
203
+
204
+ // Type annotations, type declarations and labels hold no runtime reference
205
+ const TYPE_ONLY_KEYS = new Set([
206
+ 'typeAnnotation',
207
+ 'returnType',
208
+ 'typeParameters',
209
+ 'typeArguments',
210
+ 'superTypeArguments',
211
+ 'implements',
212
+ 'label',
213
+ ])
214
+ const TYPE_ONLY_NODES = new Set(['TSInterfaceDeclaration', 'TSTypeAliasDeclaration'])
215
+
216
+ // Calls `fn` for each identifier named `name` below `node` that is a value, not a type or a key
217
+ function forEachValueIdentifier(node, name, fn) {
218
+ visit(node, child => {
219
+ if (TYPE_ONLY_NODES.has(child.type)) return false
220
+ if (child.type === 'Identifier' && child.name === name && !isTypeOnly(child, node)) fn(child)
221
+ return false
222
+ })
223
+ }
224
+
225
+ function isTypeOnly(identifier, root) {
226
+ let child = identifier
227
+ for (
228
+ let { parent } = identifier;
229
+ parent && child !== root;
230
+ child = parent, parent = parent.parent
231
+ ) {
232
+ if (TYPE_ONLY_NODES.has(parent.type)) return true
233
+ for (const key of TYPE_ONLY_KEYS) {
234
+ if (parent[key] === child) return true
235
+ if (Array.isArray(parent[key]) && parent[key].includes(child)) return true
236
+ }
237
+ }
238
+ return false
239
+ }
240
+
241
+ // Whether a declaration between `node` and `boundary` (or the file, when null) binds `name`
242
+ function isShadowed(node, name, boundary) {
243
+ let child = node
244
+ for (
245
+ let { parent } = node;
246
+ parent && parent !== boundary;
247
+ child = parent, parent = parent.parent
248
+ ) {
249
+ if (parent.type === 'Program') return false
250
+ // All cases of a switch share one scope; the discriminant is outside it
251
+ if (parent.type === 'SwitchStatement') {
252
+ if (child === parent.discriminant) continue
253
+ const cases = parent.cases.flatMap(switchCase => switchCase.consequent)
254
+ if (cases.some(statement => statementBindsName(statement, name))) return true
255
+ continue
256
+ }
257
+ if (declaresName(parent, name)) return true
258
+ }
259
+ return false
260
+ }
261
+
262
+ function declaresName(node, name) {
263
+ switch (node.type) {
264
+ case 'FunctionDeclaration':
265
+ case 'FunctionExpression':
266
+ case 'ArrowFunctionExpression': {
267
+ if (node.type === 'FunctionExpression' && node.id?.name === name) return true
268
+ return node.params.some(param => bindsName(param, name))
269
+ }
270
+ // A class declaration's own name binds in the enclosing block (checked there); a named class
271
+ // expression binds it inside itself
272
+ case 'ClassExpression': {
273
+ return node.id?.name === name
274
+ }
275
+ case 'CatchClause': {
276
+ return !!node.param && bindsName(node.param, name)
277
+ }
278
+ case 'ForStatement':
279
+ case 'ForInStatement':
280
+ case 'ForOfStatement': {
281
+ const head = node.type === 'ForStatement' ? node.init : node.left
282
+ return head?.type === 'VariableDeclaration' && statementBindsName(head, name)
283
+ }
284
+ case 'BlockStatement':
285
+ case 'StaticBlock': {
286
+ return node.body.some(statement => statementBindsName(statement, name))
287
+ }
288
+ default: {
289
+ return false
290
+ }
291
+ }
292
+ }
293
+
294
+ function statementBindsName(statement, name) {
295
+ const declaration =
296
+ statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
297
+ if (!declaration) return false
298
+ if (declaration.type === 'VariableDeclaration') {
299
+ return declaration.declarations.some(declarator => bindsName(declarator.id, name))
300
+ }
301
+ return (
302
+ (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
303
+ declaration.id?.name === name
304
+ )
305
+ }
306
+
307
+ // Whether a parameter or destructuring pattern introduces `name`
308
+ function bindsName(pattern, name) {
309
+ switch (pattern?.type) {
310
+ case 'Identifier': {
311
+ return pattern.name === name
312
+ }
313
+ case 'AssignmentPattern': {
314
+ return bindsName(pattern.left, name)
315
+ }
316
+ case 'RestElement': {
317
+ return bindsName(pattern.argument, name)
318
+ }
319
+ case 'TSParameterProperty': {
320
+ return bindsName(pattern.parameter, name)
321
+ }
322
+ case 'ArrayPattern': {
323
+ return pattern.elements.some(element => bindsName(element, name))
324
+ }
325
+ case 'ObjectPattern': {
326
+ return pattern.properties.some(property =>
327
+ bindsName(property.type === 'RestElement' ? property : property.value, name),
328
+ )
329
+ }
330
+ default: {
331
+ return false
332
+ }
333
+ }
334
+ }
335
+
336
+ // `const service = new Service()` or `export const service = new Service()`, not nested in a function
337
+ function isModuleLevelConst(declarator, init) {
338
+ if (declarator.type !== 'VariableDeclarator' || declarator.init !== init) return false
339
+ if (declarator.id.type !== 'Identifier') return false
340
+ const declaration = declarator.parent
341
+ return declaration.kind === 'const' && isModuleLevel(declaration)
342
+ }
343
+
344
+ // Directly in the file, exported or not
345
+ function isModuleLevel(node) {
346
+ const { parent } = node
347
+ return (
348
+ parent.type === 'Program' ||
349
+ (parent.type.startsWith('Export') && parent.parent.type === 'Program')
350
+ )
351
+ }
352
+
353
+ // Whether `this` at `node` is an instance of the class: in an instance method, accessor, constructor
354
+ // or field initializer, with nothing in between that has a `this` of its own
355
+ function isInstanceCodeOf(node, classNode) {
356
+ let child = node
357
+ for (let { parent } = node; parent; child = parent, { parent } = parent) {
358
+ switch (parent.type) {
359
+ // `typeof service` in a type
360
+ case 'TSTypeQuery':
361
+ // A decorator runs when the class is defined, also one on a parameter
362
+ case 'Decorator':
363
+ case 'FunctionDeclaration':
364
+ case 'StaticBlock': {
365
+ return false
366
+ }
367
+ case 'FunctionExpression': {
368
+ if (parent.parent.type !== 'MethodDefinition') return false
369
+ break
370
+ }
371
+ case 'MethodDefinition':
372
+ case 'PropertyDefinition':
373
+ case 'AccessorProperty': {
374
+ // Not a static member, and not its decorator or computed key
375
+ if (parent.static || parent.value !== child) return false
376
+ break
377
+ }
378
+ case 'ClassBody': {
379
+ return parent.parent === classNode
380
+ }
381
+ }
382
+ }
383
+ return false
384
+ }
385
+
143
386
  const preferLastRule = {
144
387
  meta: {
145
388
  type: 'suggestion',
@@ -319,6 +562,7 @@ const ncPlugin = {
319
562
  name: 'nc',
320
563
  },
321
564
  rules: {
565
+ 'no-singleton-self-reference': noSingletonSelfReferenceRule,
322
566
  'prefer-assert': preferAssertRule,
323
567
  'prefer-env-destructuring': preferEnvDestructuringRule,
324
568
  'prefer-last': preferLastRule,
@@ -75,6 +75,7 @@ export const sharedConfig = {
75
75
  { blankLine: 'always', prev: '*', next: 'class' },
76
76
  ],
77
77
  '@stylistic/lines-between-class-members': [2, 'always', { exceptAfterSingleLine: true }],
78
+ 'nc/no-singleton-self-reference': 2,
78
79
  'nc/prefer-assert': 2,
79
80
  'nc/prefer-env-destructuring': 2,
80
81
  'nc/prefer-last': 2,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/dev-lib",
3
3
  "type": "module",
4
- "version": "20.75.0",
4
+ "version": "20.76.1",
5
5
  "dependencies": {
6
6
  "prompts": "^2",
7
7
  "@naturalcycles/js-lib": "^15",