eslint-plugin-jsdoc 48.0.0 → 48.0.2

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.
Files changed (64) hide show
  1. package/package.json +2 -2
  2. package/src/WarnSettings.js +34 -0
  3. package/src/alignTransform.js +356 -0
  4. package/src/defaultTagOrder.js +168 -0
  5. package/src/exportParser.js +957 -0
  6. package/src/getDefaultTagStructureForMode.js +969 -0
  7. package/src/index.js +266 -0
  8. package/src/iterateJsdoc.js +2555 -0
  9. package/src/jsdocUtils.js +1693 -0
  10. package/src/rules/checkAccess.js +45 -0
  11. package/src/rules/checkAlignment.js +63 -0
  12. package/src/rules/checkExamples.js +594 -0
  13. package/src/rules/checkIndentation.js +75 -0
  14. package/src/rules/checkLineAlignment.js +364 -0
  15. package/src/rules/checkParamNames.js +404 -0
  16. package/src/rules/checkPropertyNames.js +152 -0
  17. package/src/rules/checkSyntax.js +30 -0
  18. package/src/rules/checkTagNames.js +314 -0
  19. package/src/rules/checkTypes.js +535 -0
  20. package/src/rules/checkValues.js +220 -0
  21. package/src/rules/emptyTags.js +88 -0
  22. package/src/rules/implementsOnClasses.js +64 -0
  23. package/src/rules/importsAsDependencies.js +131 -0
  24. package/src/rules/informativeDocs.js +182 -0
  25. package/src/rules/matchDescription.js +286 -0
  26. package/src/rules/matchName.js +147 -0
  27. package/src/rules/multilineBlocks.js +333 -0
  28. package/src/rules/noBadBlocks.js +109 -0
  29. package/src/rules/noBlankBlockDescriptions.js +69 -0
  30. package/src/rules/noBlankBlocks.js +53 -0
  31. package/src/rules/noDefaults.js +85 -0
  32. package/src/rules/noMissingSyntax.js +195 -0
  33. package/src/rules/noMultiAsterisks.js +134 -0
  34. package/src/rules/noRestrictedSyntax.js +91 -0
  35. package/src/rules/noTypes.js +73 -0
  36. package/src/rules/noUndefinedTypes.js +328 -0
  37. package/src/rules/requireAsteriskPrefix.js +189 -0
  38. package/src/rules/requireDescription.js +161 -0
  39. package/src/rules/requireDescriptionCompleteSentence.js +333 -0
  40. package/src/rules/requireExample.js +118 -0
  41. package/src/rules/requireFileOverview.js +154 -0
  42. package/src/rules/requireHyphenBeforeParamDescription.js +178 -0
  43. package/src/rules/requireJsdoc.js +629 -0
  44. package/src/rules/requireParam.js +592 -0
  45. package/src/rules/requireParamDescription.js +89 -0
  46. package/src/rules/requireParamName.js +55 -0
  47. package/src/rules/requireParamType.js +89 -0
  48. package/src/rules/requireProperty.js +48 -0
  49. package/src/rules/requirePropertyDescription.js +25 -0
  50. package/src/rules/requirePropertyName.js +25 -0
  51. package/src/rules/requirePropertyType.js +25 -0
  52. package/src/rules/requireReturns.js +238 -0
  53. package/src/rules/requireReturnsCheck.js +141 -0
  54. package/src/rules/requireReturnsDescription.js +59 -0
  55. package/src/rules/requireReturnsType.js +51 -0
  56. package/src/rules/requireThrows.js +111 -0
  57. package/src/rules/requireYields.js +216 -0
  58. package/src/rules/requireYieldsCheck.js +208 -0
  59. package/src/rules/sortTags.js +557 -0
  60. package/src/rules/tagLines.js +359 -0
  61. package/src/rules/textEscaping.js +146 -0
  62. package/src/rules/validTypes.js +368 -0
  63. package/src/tagNames.js +234 -0
  64. package/src/utils/hasReturnValue.js +549 -0
@@ -0,0 +1,2555 @@
1
+ import jsdocUtils from './jsdocUtils.js';
2
+ import {
3
+ commentHandler,
4
+ getJSDocComment,
5
+ parseComment,
6
+ } from '@es-joy/jsdoccomment';
7
+ import {
8
+ stringify as commentStringify,
9
+ util,
10
+ } from 'comment-parser';
11
+ import esquery from 'esquery';
12
+
13
+ /**
14
+ * @typedef {number} Integer
15
+ */
16
+
17
+ /**
18
+ * @typedef {import('@es-joy/jsdoccomment').JsdocBlockWithInline} JsdocBlockWithInline
19
+ */
20
+
21
+ /**
22
+ * @typedef {{
23
+ * disallowName?: string,
24
+ * allowName?: string,
25
+ * context?: string,
26
+ * comment?: string,
27
+ * tags?: string[],
28
+ * replacement?: string,
29
+ * minimum?: Integer,
30
+ * message?: string,
31
+ * forceRequireReturn?: boolean
32
+ * }} ContextObject
33
+ */
34
+ /**
35
+ * @typedef {string|ContextObject} Context
36
+ */
37
+
38
+ /**
39
+ * @callback CheckJsdoc
40
+ * @param {{
41
+ * lastIndex?: Integer,
42
+ * isFunctionContext?: boolean,
43
+ * selector?: string,
44
+ * comment?: string
45
+ * }} info
46
+ * @param {null|((jsdoc: import('@es-joy/jsdoccomment').JsdocBlockWithInline) => boolean|undefined)} handler
47
+ * @param {import('eslint').Rule.Node} node
48
+ * @returns {void}
49
+ */
50
+
51
+ /**
52
+ * @callback ForEachPreferredTag
53
+ * @param {string} tagName
54
+ * @param {(
55
+ * matchingJsdocTag: import('@es-joy/jsdoccomment').JsdocTagWithInline,
56
+ * targetTagName: string
57
+ * ) => void} arrayHandler
58
+ * @param {boolean} [skipReportingBlockedTag]
59
+ * @returns {void}
60
+ */
61
+
62
+ /**
63
+ * @callback ReportSettings
64
+ * @param {string} message
65
+ * @returns {void}
66
+ */
67
+
68
+ /**
69
+ * @callback ParseClosureTemplateTag
70
+ * @param {import('comment-parser').Spec} tag
71
+ * @returns {string[]}
72
+ */
73
+
74
+ /**
75
+ * @callback GetPreferredTagNameObject
76
+ * @param {{
77
+ * tagName: string
78
+ * }} cfg
79
+ * @returns {string|false|{
80
+ * message: string;
81
+ * replacement?: string|undefined
82
+ * }|{
83
+ * blocked: true,
84
+ * tagName: string
85
+ * }}
86
+ */
87
+
88
+ /**
89
+ * @typedef {{
90
+ * forEachPreferredTag: ForEachPreferredTag,
91
+ * reportSettings: ReportSettings,
92
+ * parseClosureTemplateTag: ParseClosureTemplateTag,
93
+ * getPreferredTagNameObject: GetPreferredTagNameObject,
94
+ * pathDoesNotBeginWith: import('./jsdocUtils.js').PathDoesNotBeginWith
95
+ * }} BasicUtils
96
+ */
97
+
98
+ /**
99
+ * @callback IsIteratingFunction
100
+ * @returns {boolean}
101
+ */
102
+
103
+ /**
104
+ * @callback IsVirtualFunction
105
+ * @returns {boolean}
106
+ */
107
+
108
+ /**
109
+ * @callback Stringify
110
+ * @param {import('comment-parser').Block} tagBlock
111
+ * @param {boolean} [specRewire]
112
+ * @returns {string}
113
+ */
114
+
115
+ /**
116
+ * @callback ReportJSDoc
117
+ * @param {string} msg
118
+ * @param {null|import('comment-parser').Spec|{line: Integer, column?: Integer}} [tag]
119
+ * @param {(() => void)|null} [handler]
120
+ * @param {boolean} [specRewire]
121
+ * @param {undefined|{
122
+ * [key: string]: string
123
+ * }} [data]
124
+ */
125
+
126
+ /**
127
+ * @callback GetRegexFromString
128
+ * @param {string} str
129
+ * @param {string} [requiredFlags]
130
+ * @returns {RegExp}
131
+ */
132
+
133
+ /**
134
+ * @callback GetTagDescription
135
+ * @param {import('comment-parser').Spec} tg
136
+ * @param {boolean} [returnArray]
137
+ * @returns {string[]|string}
138
+ */
139
+
140
+ /**
141
+ * @callback SetTagDescription
142
+ * @param {import('comment-parser').Spec} tg
143
+ * @param {RegExp} matcher
144
+ * @param {(description: string) => string} setter
145
+ * @returns {Integer}
146
+ */
147
+
148
+ /**
149
+ * @callback GetDescription
150
+ * @returns {{
151
+ * description: string,
152
+ * descriptions: string[],
153
+ * lastDescriptionLine: Integer
154
+ * }}
155
+ */
156
+
157
+ /**
158
+ * @callback SetBlockDescription
159
+ * @param {(
160
+ * info: {
161
+ * delimiter: string,
162
+ * postDelimiter: string,
163
+ * start: string
164
+ * },
165
+ * seedTokens: (
166
+ * tokens?: Partial<import('comment-parser').Tokens>
167
+ * ) => import('comment-parser').Tokens,
168
+ * descLines: string[]
169
+ * ) => import('comment-parser').Line[]} setter
170
+ * @returns {void}
171
+ */
172
+
173
+ /**
174
+ * @callback SetDescriptionLines
175
+ * @param {RegExp} matcher
176
+ * @param {(description: string) => string} setter
177
+ * @returns {Integer}
178
+ */
179
+
180
+ /**
181
+ * @callback ChangeTag
182
+ * @param {import('comment-parser').Spec} tag
183
+ * @param {...Partial<import('comment-parser').Tokens>} tokens
184
+ * @returns {void}
185
+ */
186
+
187
+ /**
188
+ * @callback SetTag
189
+ * @param {import('comment-parser').Spec & {
190
+ * line: Integer
191
+ * }} tag
192
+ * @param {Partial<import('comment-parser').Tokens>} [tokens]
193
+ * @returns {void}
194
+ */
195
+
196
+ /**
197
+ * @callback RemoveTag
198
+ * @param {Integer} tagIndex
199
+ * @param {{
200
+ * removeEmptyBlock?: boolean,
201
+ * tagSourceOffset?: Integer
202
+ * }} [cfg]
203
+ * @returns {void}
204
+ */
205
+
206
+ /**
207
+ * @callback AddTag
208
+ * @param {string} targetTagName
209
+ * @param {Integer} [number]
210
+ * @param {import('comment-parser').Tokens|{}} [tokens]
211
+ * @returns {void}
212
+ */
213
+
214
+ /**
215
+ * @callback GetFirstLine
216
+ * @returns {Integer|undefined}
217
+ */
218
+
219
+ /**
220
+ * @typedef {(
221
+ * tokens?: Partial<import('comment-parser').Tokens> | undefined
222
+ * ) => import('comment-parser').Tokens} SeedTokens
223
+ */
224
+
225
+ /**
226
+ * Sets tokens to empty string.
227
+ * @callback EmptyTokens
228
+ * @param {import('comment-parser').Tokens} tokens
229
+ * @returns {void}
230
+ */
231
+
232
+ /**
233
+ * @callback AddLine
234
+ * @param {Integer} sourceIndex
235
+ * @param {Partial<import('comment-parser').Tokens>} tokens
236
+ * @returns {void}
237
+ */
238
+
239
+ /**
240
+ * @callback AddLines
241
+ * @param {Integer} tagIndex
242
+ * @param {Integer} tagSourceOffset
243
+ * @param {Integer} numLines
244
+ * @returns {void}
245
+ */
246
+
247
+ /**
248
+ * @callback MakeMultiline
249
+ * @returns {void}
250
+ */
251
+
252
+ /**
253
+ * @callback GetFunctionParameterNames
254
+ * @param {boolean} [useDefaultObjectProperties]
255
+ * @returns {import('./jsdocUtils.js').ParamNameInfo[]}
256
+ */
257
+
258
+ /**
259
+ * @callback HasParams
260
+ * @returns {Integer}
261
+ */
262
+
263
+ /**
264
+ * @callback IsGenerator
265
+ * @returns {boolean}
266
+ */
267
+
268
+ /**
269
+ * @callback IsConstructor
270
+ * @returns {boolean}
271
+ */
272
+
273
+ /**
274
+ * @callback GetJsdocTagsDeep
275
+ * @param {string} tagName
276
+ * @returns {false|{
277
+ * idx: Integer,
278
+ * name: string,
279
+ * type: string
280
+ * }[]}
281
+ */
282
+
283
+ /**
284
+ * @callback GetPreferredTagName
285
+ * @param {{
286
+ * tagName: string,
287
+ * skipReportingBlockedTag?: boolean,
288
+ * allowObjectReturn?: boolean,
289
+ * defaultMessage?: string
290
+ * }} cfg
291
+ * @returns {string|undefined|false|{
292
+ * message: string;
293
+ * replacement?: string|undefined;
294
+ * }|{
295
+ * blocked: true,
296
+ * tagName: string
297
+ * }}
298
+ */
299
+
300
+ /**
301
+ * @callback IsValidTag
302
+ * @param {string} name
303
+ * @param {string[]} definedTags
304
+ * @returns {boolean}
305
+ */
306
+
307
+ /**
308
+ * @callback HasATag
309
+ * @param {string[]} names
310
+ * @returns {boolean}
311
+ */
312
+
313
+ /**
314
+ * @callback HasTag
315
+ * @param {string} name
316
+ * @returns {boolean}
317
+ */
318
+
319
+ /**
320
+ * @callback ComparePaths
321
+ * @param {string} name
322
+ * @returns {(otherPathName: string) => boolean}
323
+ */
324
+
325
+ /**
326
+ * @callback DropPathSegmentQuotes
327
+ * @param {string} name
328
+ * @returns {string}
329
+ */
330
+
331
+ /**
332
+ * @callback AvoidDocs
333
+ * @returns {boolean}
334
+ */
335
+
336
+ /**
337
+ * @callback TagMightHaveNamePositionTypePosition
338
+ * @param {string} tagName
339
+ * @param {import('./getDefaultTagStructureForMode.js').
340
+ * TagStructure[]} [otherModeMaps]
341
+ * @returns {boolean|{otherMode: true}}
342
+ */
343
+
344
+ /**
345
+ * @callback TagMustHave
346
+ * @param {string} tagName
347
+ * @param {import('./getDefaultTagStructureForMode.js').
348
+ * TagStructure[]} otherModeMaps
349
+ * @returns {boolean|{
350
+ * otherMode: false
351
+ * }}
352
+ */
353
+
354
+ /**
355
+ * @callback TagMissingRequiredTypeOrNamepath
356
+ * @param {import('comment-parser').Spec} tag
357
+ * @param {import('./getDefaultTagStructureForMode.js').
358
+ * TagStructure[]} otherModeMaps
359
+ * @returns {boolean|{
360
+ * otherMode: false
361
+ * }}
362
+ */
363
+
364
+ /**
365
+ * @callback IsNamepathX
366
+ * @param {string} tagName
367
+ * @returns {boolean}
368
+ */
369
+
370
+ /**
371
+ * @callback GetTagStructureForMode
372
+ * @param {import('./jsdocUtils.js').ParserMode} mde
373
+ * @returns {import('./getDefaultTagStructureForMode.js').TagStructure}
374
+ */
375
+
376
+ /**
377
+ * @callback MayBeUndefinedTypeTag
378
+ * @param {import('comment-parser').Spec} tag
379
+ * @returns {boolean}
380
+ */
381
+
382
+ /**
383
+ * @callback HasValueOrExecutorHasNonEmptyResolveValue
384
+ * @param {boolean} anyPromiseAsReturn
385
+ * @param {boolean} [allBranches]
386
+ * @returns {boolean}
387
+ */
388
+
389
+ /**
390
+ * @callback HasYieldValue
391
+ * @returns {boolean}
392
+ */
393
+
394
+ /**
395
+ * @callback HasYieldReturnValue
396
+ * @returns {boolean}
397
+ */
398
+
399
+ /**
400
+ * @callback HasThrowValue
401
+ * @returns {boolean}
402
+ */
403
+
404
+ /**
405
+ * @callback IsAsync
406
+ * @returns {boolean|undefined}
407
+ */
408
+
409
+ /**
410
+ * @callback GetTags
411
+ * @param {string} tagName
412
+ * @returns {import('comment-parser').Spec[]}
413
+ */
414
+
415
+ /**
416
+ * @callback GetPresentTags
417
+ * @param {string[]} tagList
418
+ * @returns {import('@es-joy/jsdoccomment').JsdocTagWithInline[]}
419
+ */
420
+
421
+ /**
422
+ * @callback FilterTags
423
+ * @param {(tag: import('@es-joy/jsdoccomment').JsdocTagWithInline) => boolean} filter
424
+ * @returns {import('@es-joy/jsdoccomment').JsdocTagWithInline[]}
425
+ */
426
+
427
+ /**
428
+ * @callback FilterAllTags
429
+ * @param {(tag: (import('comment-parser').Spec|
430
+ * import('@es-joy/jsdoccomment').JsdocInlineTagNoType)) => boolean} filter
431
+ * @returns {(import('comment-parser').Spec|
432
+ * import('@es-joy/jsdoccomment').JsdocInlineTagNoType)[]}
433
+ */
434
+
435
+ /**
436
+ * @callback GetTagsByType
437
+ * @param {import('comment-parser').Spec[]} tags
438
+ * @returns {{
439
+ * tagsWithNames: import('comment-parser').Spec[],
440
+ * tagsWithoutNames: import('comment-parser').Spec[]
441
+ * }}
442
+ */
443
+
444
+ /**
445
+ * @callback HasOptionTag
446
+ * @param {string} tagName
447
+ * @returns {boolean}
448
+ */
449
+
450
+ /**
451
+ * @callback GetClassNode
452
+ * @returns {Node|null}
453
+ */
454
+
455
+ /**
456
+ * @callback GetClassJsdoc
457
+ * @returns {null|JsdocBlockWithInline}
458
+ */
459
+
460
+ /**
461
+ * @callback ClassHasTag
462
+ * @param {string} tagName
463
+ * @returns {boolean}
464
+ */
465
+
466
+ /**
467
+ * @callback FindContext
468
+ * @param {Context[]} contexts
469
+ * @param {string|undefined} comment
470
+ * @returns {{
471
+ * foundContext: Context|undefined,
472
+ * contextStr: string
473
+ * }}
474
+ */
475
+
476
+ /**
477
+ * @typedef {BasicUtils & {
478
+ * isIteratingFunction: IsIteratingFunction,
479
+ * isVirtualFunction: IsVirtualFunction,
480
+ * stringify: Stringify,
481
+ * reportJSDoc: ReportJSDoc,
482
+ * getRegexFromString: GetRegexFromString,
483
+ * getTagDescription: GetTagDescription,
484
+ * setTagDescription: SetTagDescription,
485
+ * getDescription: GetDescription,
486
+ * setBlockDescription: SetBlockDescription,
487
+ * setDescriptionLines: SetDescriptionLines,
488
+ * changeTag: ChangeTag,
489
+ * setTag: SetTag,
490
+ * removeTag: RemoveTag,
491
+ * addTag: AddTag,
492
+ * getFirstLine: GetFirstLine,
493
+ * seedTokens: SeedTokens,
494
+ * emptyTokens: EmptyTokens,
495
+ * addLine: AddLine,
496
+ * addLines: AddLines,
497
+ * makeMultiline: MakeMultiline,
498
+ * flattenRoots: import('./jsdocUtils.js').FlattenRoots,
499
+ * getFunctionParameterNames: GetFunctionParameterNames,
500
+ * hasParams: HasParams,
501
+ * isGenerator: IsGenerator,
502
+ * isConstructor: IsConstructor,
503
+ * getJsdocTagsDeep: GetJsdocTagsDeep,
504
+ * getPreferredTagName: GetPreferredTagName,
505
+ * isValidTag: IsValidTag,
506
+ * hasATag: HasATag,
507
+ * hasTag: HasTag,
508
+ * comparePaths: ComparePaths,
509
+ * dropPathSegmentQuotes: DropPathSegmentQuotes,
510
+ * avoidDocs: AvoidDocs,
511
+ * tagMightHaveNamePosition: TagMightHaveNamePositionTypePosition,
512
+ * tagMightHaveTypePosition: TagMightHaveNamePositionTypePosition,
513
+ * tagMustHaveNamePosition: TagMustHave,
514
+ * tagMustHaveTypePosition: TagMustHave,
515
+ * tagMissingRequiredTypeOrNamepath: TagMissingRequiredTypeOrNamepath,
516
+ * isNamepathDefiningTag: IsNamepathX,
517
+ * isNamepathReferencingTag: IsNamepathX,
518
+ * isNamepathOrUrlReferencingTag: IsNamepathX,
519
+ * tagMightHaveNamepath: IsNamepathX,
520
+ * getTagStructureForMode: GetTagStructureForMode,
521
+ * mayBeUndefinedTypeTag: MayBeUndefinedTypeTag,
522
+ * hasValueOrExecutorHasNonEmptyResolveValue: HasValueOrExecutorHasNonEmptyResolveValue,
523
+ * hasYieldValue: HasYieldValue,
524
+ * hasYieldReturnValue: HasYieldReturnValue,
525
+ * hasThrowValue: HasThrowValue,
526
+ * isAsync: IsAsync,
527
+ * getTags: GetTags,
528
+ * getPresentTags: GetPresentTags,
529
+ * filterTags: FilterTags,
530
+ * filterAllTags: FilterAllTags,
531
+ * getTagsByType: GetTagsByType,
532
+ * hasOptionTag: HasOptionTag,
533
+ * getClassNode: GetClassNode,
534
+ * getClassJsdoc: GetClassJsdoc,
535
+ * classHasTag: ClassHasTag,
536
+ * findContext: FindContext
537
+ * }} Utils
538
+ */
539
+
540
+ const {
541
+ rewireSpecs,
542
+ seedTokens,
543
+ } = util;
544
+
545
+ // todo: Change these `any` types once importing types properly.
546
+
547
+ /**
548
+ * Should use ESLint rule's typing.
549
+ * @typedef {import('eslint').Rule.RuleMetaData} EslintRuleMeta
550
+ */
551
+
552
+ /**
553
+ * A plain object for tracking state as needed by rules across iterations.
554
+ * @typedef {{
555
+ * globalTags: {},
556
+ * hasDuplicates: {
557
+ * [key: string]: boolean
558
+ * },
559
+ * selectorMap: {
560
+ * [selector: string]: {
561
+ * [comment: string]: Integer
562
+ * }
563
+ * },
564
+ * hasTag: {
565
+ * [key: string]: boolean
566
+ * },
567
+ * hasNonComment: number,
568
+ * hasNonCommentBeforeTag: {
569
+ * [key: string]: boolean|number
570
+ * }
571
+ * }} StateObject
572
+ */
573
+
574
+ /**
575
+ * The Node AST as supplied by the parser.
576
+ * @typedef {import('eslint').Rule.Node} Node
577
+ */
578
+
579
+ /*
580
+ const {
581
+ align as commentAlign,
582
+ flow: commentFlow,
583
+ indent: commentIndent,
584
+ } = transforms;
585
+ */
586
+
587
+ const globalState = new Map();
588
+ /**
589
+ * @param {import('eslint').Rule.RuleContext} context
590
+ * @param {{
591
+ * tagNamePreference?: import('./jsdocUtils.js').TagNamePreference,
592
+ * mode?: import('./jsdocUtils.js').ParserMode
593
+ * }} cfg
594
+ * @returns {BasicUtils}
595
+ */
596
+ const getBasicUtils = (context, {
597
+ tagNamePreference,
598
+ mode,
599
+ }) => {
600
+ /** @type {BasicUtils} */
601
+ const utils = {};
602
+
603
+ /** @type {ReportSettings} */
604
+ utils.reportSettings = (message) => {
605
+ context.report({
606
+ loc: {
607
+ end: {
608
+ column: 1,
609
+ line: 1,
610
+ },
611
+ start: {
612
+ column: 1,
613
+ line: 1,
614
+ },
615
+ },
616
+ message,
617
+ });
618
+ };
619
+
620
+ /** @type {ParseClosureTemplateTag} */
621
+ utils.parseClosureTemplateTag = (tag) => {
622
+ return jsdocUtils.parseClosureTemplateTag(tag);
623
+ };
624
+
625
+ utils.pathDoesNotBeginWith = jsdocUtils.pathDoesNotBeginWith;
626
+
627
+ /** @type {GetPreferredTagNameObject} */
628
+ utils.getPreferredTagNameObject = ({
629
+ tagName,
630
+ }) => {
631
+ const ret = jsdocUtils.getPreferredTagName(
632
+ context,
633
+ /** @type {import('./jsdocUtils.js').ParserMode} */ (mode),
634
+ tagName,
635
+ tagNamePreference,
636
+ );
637
+ const isObject = ret && typeof ret === 'object';
638
+ if (ret === false || (isObject && !ret.replacement)) {
639
+ return {
640
+ blocked: true,
641
+ tagName,
642
+ };
643
+ }
644
+
645
+ return ret;
646
+ };
647
+
648
+ return utils;
649
+ };
650
+
651
+ /**
652
+ * @callback Report
653
+ * @param {string} message
654
+ * @param {import('eslint').Rule.ReportFixer|null} [fix]
655
+ * @param {null|
656
+ * {line?: Integer, column?: Integer}|
657
+ * import('comment-parser').Spec & {line?: Integer}
658
+ * } [jsdocLoc]
659
+ * @param {undefined|{
660
+ * [key: string]: string
661
+ * }} [data]
662
+ * @returns {void}
663
+ */
664
+
665
+ /**
666
+ * @param {Node|null} node
667
+ * @param {JsdocBlockWithInline} jsdoc
668
+ * @param {import('eslint').AST.Token} jsdocNode
669
+ * @param {Settings} settings
670
+ * @param {Report} report
671
+ * @param {import('eslint').Rule.RuleContext} context
672
+ * @param {import('eslint').SourceCode} sc
673
+ * @param {boolean|undefined} iteratingAll
674
+ * @param {RuleConfig} ruleConfig
675
+ * @param {string} indent
676
+ * @returns {Utils}
677
+ */
678
+ const getUtils = (
679
+ node,
680
+ jsdoc,
681
+ jsdocNode,
682
+ settings,
683
+ report,
684
+ context,
685
+ sc,
686
+ iteratingAll,
687
+ ruleConfig,
688
+ indent,
689
+ ) => {
690
+ const ancestors = /** @type {import('eslint').Rule.Node[]} */ (node ?
691
+ (sc.getAncestors ?
692
+ (
693
+ sc.getAncestors(node)
694
+ /* c8 ignore next 4 */
695
+ ) :
696
+ (
697
+ context.getAncestors()
698
+ )) :
699
+ []);
700
+
701
+ /* c8 ignore next -- Fallback to deprecated method */
702
+ const {
703
+ sourceCode = context.getSourceCode(),
704
+ } = context;
705
+
706
+ const utils = /** @type {Utils} */ (getBasicUtils(context, settings));
707
+
708
+ const {
709
+ tagNamePreference,
710
+ overrideReplacesDocs,
711
+ ignoreReplacesDocs,
712
+ implementsReplacesDocs,
713
+ augmentsExtendsReplacesDocs,
714
+ maxLines,
715
+ minLines,
716
+ mode,
717
+ } = settings;
718
+
719
+ /** @type {IsIteratingFunction} */
720
+ utils.isIteratingFunction = () => {
721
+ return !iteratingAll || [
722
+ 'MethodDefinition',
723
+ 'ArrowFunctionExpression',
724
+ 'FunctionDeclaration',
725
+ 'FunctionExpression',
726
+ ].includes(String(node && node.type));
727
+ };
728
+
729
+ /** @type {IsVirtualFunction} */
730
+ utils.isVirtualFunction = () => {
731
+ return Boolean(iteratingAll) && utils.hasATag([
732
+ 'callback', 'function', 'func', 'method',
733
+ ]);
734
+ };
735
+
736
+ /** @type {Stringify} */
737
+ utils.stringify = (tagBlock, specRewire) => {
738
+ let block;
739
+ if (specRewire) {
740
+ block = rewireSpecs(tagBlock);
741
+ }
742
+
743
+ return commentStringify(/** @type {import('comment-parser').Block} */ (
744
+ specRewire ? block : tagBlock));
745
+ };
746
+
747
+ /** @type {ReportJSDoc} */
748
+ utils.reportJSDoc = (msg, tag, handler, specRewire, data) => {
749
+ report(msg, handler ? /** @type {import('eslint').Rule.ReportFixer} */ (
750
+ fixer,
751
+ ) => {
752
+ handler();
753
+ const replacement = utils.stringify(jsdoc, specRewire);
754
+
755
+ if (!replacement) {
756
+ const text = sourceCode.getText();
757
+ const lastLineBreakPos = text.slice(
758
+ 0, jsdocNode.range[0],
759
+ ).search(/\n[ \t]*$/u);
760
+ if (lastLineBreakPos > -1) {
761
+ return fixer.removeRange([
762
+ lastLineBreakPos, jsdocNode.range[1],
763
+ ]);
764
+ }
765
+
766
+ return fixer.removeRange(
767
+ (/\s/u).test(text.charAt(jsdocNode.range[1])) ?
768
+ [
769
+ jsdocNode.range[0], jsdocNode.range[1] + 1,
770
+ ] :
771
+ jsdocNode.range,
772
+ );
773
+ }
774
+
775
+ return fixer.replaceText(jsdocNode, replacement);
776
+ } : null, tag, data);
777
+ };
778
+
779
+ /** @type {GetRegexFromString} */
780
+ utils.getRegexFromString = (str, requiredFlags) => {
781
+ return jsdocUtils.getRegexFromString(str, requiredFlags);
782
+ };
783
+
784
+ /** @type {GetTagDescription} */
785
+ utils.getTagDescription = (tg, returnArray) => {
786
+ /**
787
+ * @type {string[]}
788
+ */
789
+ const descriptions = [];
790
+ tg.source.some(({
791
+ tokens: {
792
+ end,
793
+ lineEnd,
794
+ postDelimiter,
795
+ tag,
796
+ postTag,
797
+ name,
798
+ type,
799
+ description,
800
+ },
801
+ }) => {
802
+ const desc = (
803
+ tag && postTag ||
804
+ !tag && !name && !type && postDelimiter || ''
805
+
806
+ // Remove space
807
+ ).slice(1) +
808
+ (description || '') + (lineEnd || '');
809
+
810
+ if (end) {
811
+ if (desc) {
812
+ descriptions.push(desc);
813
+ }
814
+
815
+ return true;
816
+ }
817
+
818
+ descriptions.push(desc);
819
+
820
+ return false;
821
+ });
822
+
823
+ return returnArray ? descriptions : descriptions.join('\n');
824
+ };
825
+
826
+ /** @type {SetTagDescription} */
827
+ utils.setTagDescription = (tg, matcher, setter) => {
828
+ let finalIdx = 0;
829
+ tg.source.some(({
830
+ tokens: {
831
+ description,
832
+ },
833
+ }, idx) => {
834
+ if (description && matcher.test(description)) {
835
+ tg.source[idx].tokens.description = setter(description);
836
+ finalIdx = idx;
837
+ return true;
838
+ }
839
+
840
+ return false;
841
+ });
842
+
843
+ return finalIdx;
844
+ };
845
+
846
+ /** @type {GetDescription} */
847
+ utils.getDescription = () => {
848
+ /** @type {string[]} */
849
+ const descriptions = [];
850
+ let lastDescriptionLine = 0;
851
+ let tagsBegun = false;
852
+ jsdoc.source.some(({
853
+ tokens: {
854
+ description,
855
+ tag,
856
+ end,
857
+ },
858
+ }, idx) => {
859
+ if (tag) {
860
+ tagsBegun = true;
861
+ }
862
+
863
+ if (idx && (tag || end)) {
864
+ lastDescriptionLine = idx - 1;
865
+ if (!tagsBegun && description) {
866
+ descriptions.push(description);
867
+ }
868
+
869
+ return true;
870
+ }
871
+
872
+ if (!tagsBegun && (idx || description)) {
873
+ descriptions.push(description || (descriptions.length ? '' : '\n'));
874
+ }
875
+
876
+ return false;
877
+ });
878
+
879
+ return {
880
+ description: descriptions.join('\n'),
881
+ descriptions,
882
+ lastDescriptionLine,
883
+ };
884
+ };
885
+
886
+ /** @type {SetBlockDescription} */
887
+ utils.setBlockDescription = (setter) => {
888
+ /** @type {string[]} */
889
+ const descLines = [];
890
+ /**
891
+ * @type {undefined|Integer}
892
+ */
893
+ let startIdx;
894
+ /**
895
+ * @type {undefined|Integer}
896
+ */
897
+ let endIdx;
898
+
899
+ /**
900
+ * @type {undefined|{
901
+ * delimiter: string,
902
+ * postDelimiter: string,
903
+ * start: string
904
+ * }}
905
+ */
906
+ let info;
907
+
908
+ jsdoc.source.some(({
909
+ tokens: {
910
+ description,
911
+ start,
912
+ delimiter,
913
+ postDelimiter,
914
+ tag,
915
+ end,
916
+ },
917
+ }, idx) => {
918
+ if (delimiter === '/**') {
919
+ return false;
920
+ }
921
+
922
+ if (startIdx === undefined) {
923
+ startIdx = idx;
924
+ info = {
925
+ delimiter,
926
+ postDelimiter,
927
+ start,
928
+ };
929
+ }
930
+
931
+ if (tag || end) {
932
+ endIdx = idx;
933
+ return true;
934
+ }
935
+
936
+ descLines.push(description);
937
+ return false;
938
+ });
939
+
940
+ /* c8 ignore else -- Won't be called if missing */
941
+ if (descLines.length) {
942
+ jsdoc.source.splice(
943
+ /** @type {Integer} */ (startIdx),
944
+ /** @type {Integer} */ (endIdx) - /** @type {Integer} */ (startIdx),
945
+ ...setter(
946
+ /**
947
+ * @type {{
948
+ * delimiter: string,
949
+ * postDelimiter: string,
950
+ * start: string
951
+ * }}
952
+ */
953
+ (info),
954
+ seedTokens,
955
+ descLines,
956
+ ),
957
+ );
958
+ }
959
+ };
960
+
961
+ /** @type {SetDescriptionLines} */
962
+ utils.setDescriptionLines = (matcher, setter) => {
963
+ let finalIdx = 0;
964
+ jsdoc.source.some(({
965
+ tokens: {
966
+ description,
967
+ tag,
968
+ end,
969
+ },
970
+ }, idx) => {
971
+ /* c8 ignore next 3 -- Already checked */
972
+ if (idx && (tag || end)) {
973
+ return true;
974
+ }
975
+
976
+ if (description && matcher.test(description)) {
977
+ jsdoc.source[idx].tokens.description = setter(description);
978
+ finalIdx = idx;
979
+ return true;
980
+ }
981
+
982
+ return false;
983
+ });
984
+
985
+ return finalIdx;
986
+ };
987
+
988
+ /** @type {ChangeTag} */
989
+ utils.changeTag = (tag, ...tokens) => {
990
+ for (const [
991
+ idx,
992
+ src,
993
+ ] of tag.source.entries()) {
994
+ src.tokens = {
995
+ ...src.tokens,
996
+ ...tokens[idx],
997
+ };
998
+ }
999
+ };
1000
+
1001
+ /** @type {SetTag} */
1002
+ utils.setTag = (tag, tokens) => {
1003
+ tag.source = [
1004
+ {
1005
+ number: tag.line,
1006
+ // Or tag.source[0].number?
1007
+ source: '',
1008
+ tokens: seedTokens({
1009
+ delimiter: '*',
1010
+ postDelimiter: ' ',
1011
+ start: indent + ' ',
1012
+ tag: '@' + tag.tag,
1013
+ ...tokens,
1014
+ }),
1015
+ },
1016
+ ];
1017
+ };
1018
+
1019
+ /** @type {RemoveTag} */
1020
+ utils.removeTag = (tagIndex, {
1021
+ removeEmptyBlock = false,
1022
+ tagSourceOffset = 0,
1023
+ } = {}) => {
1024
+ const {
1025
+ source: tagSource,
1026
+ } = jsdoc.tags[tagIndex];
1027
+ /** @type {Integer|undefined} */
1028
+ let lastIndex;
1029
+ const firstNumber = jsdoc.source[0].number;
1030
+ tagSource.some(({
1031
+ number,
1032
+ }, tagIdx) => {
1033
+ const sourceIndex = jsdoc.source.findIndex(({
1034
+ number: srcNumber,
1035
+ }) => {
1036
+ return number === srcNumber;
1037
+ });
1038
+ // c8 ignore else
1039
+ if (sourceIndex > -1) {
1040
+ let spliceCount = 1;
1041
+ tagSource.slice(tagIdx + 1).some(({
1042
+ tokens: {
1043
+ tag,
1044
+ end: ending,
1045
+ },
1046
+ }) => {
1047
+ if (!tag && !ending) {
1048
+ spliceCount++;
1049
+
1050
+ return false;
1051
+ }
1052
+
1053
+ return true;
1054
+ });
1055
+
1056
+ const spliceIdx = sourceIndex + tagSourceOffset;
1057
+
1058
+ const {
1059
+ delimiter,
1060
+ end,
1061
+ } = jsdoc.source[spliceIdx].tokens;
1062
+
1063
+ if (
1064
+ spliceIdx === 0 && jsdoc.tags.length >= 2 ||
1065
+ !removeEmptyBlock && (end || delimiter === '/**')
1066
+ ) {
1067
+ const {
1068
+ tokens,
1069
+ } = jsdoc.source[spliceIdx];
1070
+ for (const item of [
1071
+ 'postDelimiter',
1072
+ 'tag',
1073
+ 'postTag',
1074
+ 'type',
1075
+ 'postType',
1076
+ 'name',
1077
+ 'postName',
1078
+ 'description',
1079
+ ]) {
1080
+ tokens[
1081
+ /**
1082
+ * @type {"postDelimiter"|"tag"|"type"|"postType"|
1083
+ * "postTag"|"name"|"postName"|"description"}
1084
+ */ (
1085
+ item
1086
+ )
1087
+ ] = '';
1088
+ }
1089
+ } else {
1090
+ jsdoc.source.splice(spliceIdx, spliceCount - tagSourceOffset + (spliceIdx ? 0 : jsdoc.source.length));
1091
+ tagSource.splice(tagIdx + tagSourceOffset, spliceCount - tagSourceOffset + (spliceIdx ? 0 : jsdoc.source.length));
1092
+ }
1093
+
1094
+ lastIndex = sourceIndex;
1095
+
1096
+ return true;
1097
+ }
1098
+ /* c8 ignore next */
1099
+ return false;
1100
+ });
1101
+ for (const [
1102
+ idx,
1103
+ src,
1104
+ ] of jsdoc.source.slice(lastIndex).entries()) {
1105
+ src.number = firstNumber + /** @type {Integer} */ (lastIndex) + idx;
1106
+ }
1107
+
1108
+ // Todo: Once rewiring of tags may be fixed in comment-parser to reflect
1109
+ // missing tags, this step should be added here (so that, e.g.,
1110
+ // if accessing `jsdoc.tags`, such as to add a new tag, the
1111
+ // correct information will be available)
1112
+ };
1113
+
1114
+ /** @type {AddTag} */
1115
+ utils.addTag = (
1116
+ targetTagName,
1117
+ number = (jsdoc.tags[jsdoc.tags.length - 1]?.source[0]?.number ?? jsdoc.source.findIndex(({
1118
+ tokens: {
1119
+ tag,
1120
+ },
1121
+ }) => {
1122
+ return tag;
1123
+ }) - 1) + 1,
1124
+ tokens = {},
1125
+ ) => {
1126
+ jsdoc.source.splice(number, 0, {
1127
+ number,
1128
+ source: '',
1129
+ tokens: seedTokens({
1130
+ delimiter: '*',
1131
+ postDelimiter: ' ',
1132
+ start: indent + ' ',
1133
+ tag: `@${targetTagName}`,
1134
+ ...tokens,
1135
+ }),
1136
+ });
1137
+ for (const src of jsdoc.source.slice(number + 1)) {
1138
+ src.number++;
1139
+ }
1140
+ };
1141
+
1142
+ /** @type {GetFirstLine} */
1143
+ utils.getFirstLine = () => {
1144
+ let firstLine;
1145
+ for (const {
1146
+ number,
1147
+ tokens: {
1148
+ tag,
1149
+ },
1150
+ } of jsdoc.source) {
1151
+ if (tag) {
1152
+ firstLine = number;
1153
+ break;
1154
+ }
1155
+ }
1156
+
1157
+ return firstLine;
1158
+ };
1159
+
1160
+ /** @type {SeedTokens} */
1161
+ utils.seedTokens = seedTokens;
1162
+
1163
+ /** @type {EmptyTokens} */
1164
+ utils.emptyTokens = (tokens) => {
1165
+ for (const prop of [
1166
+ 'start',
1167
+ 'postDelimiter',
1168
+ 'tag',
1169
+ 'type',
1170
+ 'postType',
1171
+ 'postTag',
1172
+ 'name',
1173
+ 'postName',
1174
+ 'description',
1175
+ 'end',
1176
+ 'lineEnd',
1177
+ ]) {
1178
+ tokens[
1179
+ /**
1180
+ * @type {"start"|"postDelimiter"|"tag"|"type"|"postType"|
1181
+ * "postTag"|"name"|"postName"|"description"|"end"|"lineEnd"}
1182
+ */ (
1183
+ prop
1184
+ )
1185
+ ] = '';
1186
+ }
1187
+ };
1188
+
1189
+ /** @type {AddLine} */
1190
+ utils.addLine = (sourceIndex, tokens) => {
1191
+ const number = (jsdoc.source[sourceIndex - 1]?.number || 0) + 1;
1192
+ jsdoc.source.splice(sourceIndex, 0, {
1193
+ number,
1194
+ source: '',
1195
+ tokens: seedTokens(tokens),
1196
+ });
1197
+
1198
+ for (const src of jsdoc.source.slice(number + 1)) {
1199
+ src.number++;
1200
+ }
1201
+ // If necessary, we can rewire the tags (misnamed method)
1202
+ // rewireSource(jsdoc);
1203
+ };
1204
+
1205
+ /** @type {AddLines} */
1206
+ utils.addLines = (tagIndex, tagSourceOffset, numLines) => {
1207
+ const {
1208
+ source: tagSource,
1209
+ } = jsdoc.tags[tagIndex];
1210
+ /** @type {Integer|undefined} */
1211
+ let lastIndex;
1212
+ const firstNumber = jsdoc.source[0].number;
1213
+ tagSource.some(({
1214
+ number,
1215
+ }) => {
1216
+ const makeLine = () => {
1217
+ return {
1218
+ number,
1219
+ source: '',
1220
+ tokens: seedTokens({
1221
+ delimiter: '*',
1222
+ start: indent + ' ',
1223
+ }),
1224
+ };
1225
+ };
1226
+
1227
+ const makeLines = () => {
1228
+ return Array.from({
1229
+ length: numLines,
1230
+ }, makeLine);
1231
+ };
1232
+
1233
+ const sourceIndex = jsdoc.source.findIndex(({
1234
+ number: srcNumber,
1235
+ tokens: {
1236
+ end,
1237
+ },
1238
+ }) => {
1239
+ return number === srcNumber && !end;
1240
+ });
1241
+ // c8 ignore else
1242
+ if (sourceIndex > -1) {
1243
+ const lines = makeLines();
1244
+ jsdoc.source.splice(sourceIndex + tagSourceOffset, 0, ...lines);
1245
+
1246
+ // tagSource.splice(tagIdx + 1, 0, ...makeLines());
1247
+ lastIndex = sourceIndex;
1248
+
1249
+ return true;
1250
+ }
1251
+ /* c8 ignore next */
1252
+ return false;
1253
+ });
1254
+
1255
+ for (const [
1256
+ idx,
1257
+ src,
1258
+ ] of jsdoc.source.slice(lastIndex).entries()) {
1259
+ src.number = firstNumber + /** @type {Integer} */ (lastIndex) + idx;
1260
+ }
1261
+ };
1262
+
1263
+ /** @type {MakeMultiline} */
1264
+ utils.makeMultiline = () => {
1265
+ const {
1266
+ source: [
1267
+ {
1268
+ tokens,
1269
+ },
1270
+ ],
1271
+ } = jsdoc;
1272
+ const {
1273
+ postDelimiter,
1274
+ description,
1275
+ lineEnd,
1276
+ tag,
1277
+ name,
1278
+ type,
1279
+ } = tokens;
1280
+
1281
+ let {
1282
+ tokens: {
1283
+ postName,
1284
+ postTag,
1285
+ postType,
1286
+ },
1287
+ } = jsdoc.source[0];
1288
+
1289
+ // Strip trailing leftovers from single line ending
1290
+ if (!description) {
1291
+ if (postName) {
1292
+ postName = '';
1293
+ } else if (postType) {
1294
+ postType = '';
1295
+ } else /* c8 ignore else -- `comment-parser` prevents empty blocks currently per https://github.com/syavorsky/comment-parser/issues/128 */ if (postTag) {
1296
+ postTag = '';
1297
+ }
1298
+ }
1299
+
1300
+ utils.emptyTokens(tokens);
1301
+
1302
+ utils.addLine(1, {
1303
+ delimiter: '*',
1304
+
1305
+ // If a description were present, it may have whitespace attached
1306
+ // due to being at the end of the single line
1307
+ description: description.trimEnd(),
1308
+ name,
1309
+ postDelimiter,
1310
+ postName,
1311
+ postTag,
1312
+ postType,
1313
+ start: indent + ' ',
1314
+ tag,
1315
+ type,
1316
+ });
1317
+ utils.addLine(2, {
1318
+ end: '*/',
1319
+ lineEnd,
1320
+ start: indent + ' ',
1321
+ });
1322
+ };
1323
+
1324
+ /**
1325
+ * @type {import('./jsdocUtils.js').FlattenRoots}
1326
+ */
1327
+ utils.flattenRoots = jsdocUtils.flattenRoots;
1328
+
1329
+ /** @type {GetFunctionParameterNames} */
1330
+ utils.getFunctionParameterNames = (useDefaultObjectProperties) => {
1331
+ return jsdocUtils.getFunctionParameterNames(node, useDefaultObjectProperties);
1332
+ };
1333
+
1334
+ /** @type {HasParams} */
1335
+ utils.hasParams = () => {
1336
+ return jsdocUtils.hasParams(/** @type {Node} */ (node));
1337
+ };
1338
+
1339
+ /** @type {IsGenerator} */
1340
+ utils.isGenerator = () => {
1341
+ return node !== null && Boolean(
1342
+ /**
1343
+ * @type {import('estree').FunctionDeclaration|
1344
+ * import('estree').FunctionExpression}
1345
+ */ (node).generator ||
1346
+ node.type === 'MethodDefinition' && node.value.generator ||
1347
+ [
1348
+ 'ExportNamedDeclaration', 'ExportDefaultDeclaration',
1349
+ ].includes(node.type) &&
1350
+ /** @type {import('estree').FunctionDeclaration} */
1351
+ (
1352
+ /**
1353
+ * @type {import('estree').ExportNamedDeclaration|
1354
+ * import('estree').ExportDefaultDeclaration}
1355
+ */ (node).declaration
1356
+ ).generator,
1357
+ );
1358
+ };
1359
+
1360
+ /** @type {IsConstructor} */
1361
+ utils.isConstructor = () => {
1362
+ return jsdocUtils.isConstructor(/** @type {Node} */ (node));
1363
+ };
1364
+
1365
+ /** @type {GetJsdocTagsDeep} */
1366
+ utils.getJsdocTagsDeep = (tagName) => {
1367
+ const name = /** @type {string|false} */ (utils.getPreferredTagName({
1368
+ tagName,
1369
+ }));
1370
+ if (!name) {
1371
+ return false;
1372
+ }
1373
+
1374
+ return jsdocUtils.getJsdocTagsDeep(jsdoc, name);
1375
+ };
1376
+
1377
+ /** @type {GetPreferredTagName} */
1378
+ utils.getPreferredTagName = ({
1379
+ tagName,
1380
+ skipReportingBlockedTag = false,
1381
+ allowObjectReturn = false,
1382
+ defaultMessage = `Unexpected tag \`@${tagName}\``,
1383
+ }) => {
1384
+ const ret = jsdocUtils.getPreferredTagName(context, mode, tagName, tagNamePreference);
1385
+ const isObject = ret && typeof ret === 'object';
1386
+ if (utils.hasTag(tagName) && (ret === false || isObject && !ret.replacement)) {
1387
+ if (skipReportingBlockedTag) {
1388
+ return {
1389
+ blocked: true,
1390
+ tagName,
1391
+ };
1392
+ }
1393
+
1394
+ const message = isObject && ret.message || defaultMessage;
1395
+ report(message, null, utils.getTags(tagName)[0]);
1396
+
1397
+ return false;
1398
+ }
1399
+
1400
+ return isObject && !allowObjectReturn ? ret.replacement : ret;
1401
+ };
1402
+
1403
+ /** @type {IsValidTag} */
1404
+ utils.isValidTag = (name, definedTags) => {
1405
+ return jsdocUtils.isValidTag(context, mode, name, definedTags);
1406
+ };
1407
+
1408
+ /** @type {HasATag} */
1409
+ utils.hasATag = (names) => {
1410
+ return jsdocUtils.hasATag(jsdoc, names);
1411
+ };
1412
+
1413
+ /** @type {HasTag} */
1414
+ utils.hasTag = (name) => {
1415
+ return jsdocUtils.hasTag(jsdoc, name);
1416
+ };
1417
+
1418
+ /** @type {ComparePaths} */
1419
+ utils.comparePaths = (name) => {
1420
+ return jsdocUtils.comparePaths(name);
1421
+ };
1422
+
1423
+ /** @type {DropPathSegmentQuotes} */
1424
+ utils.dropPathSegmentQuotes = (name) => {
1425
+ return jsdocUtils.dropPathSegmentQuotes(name);
1426
+ };
1427
+
1428
+ /** @type {AvoidDocs} */
1429
+ utils.avoidDocs = () => {
1430
+ if (
1431
+ ignoreReplacesDocs !== false &&
1432
+ (utils.hasTag('ignore') || utils.classHasTag('ignore')) ||
1433
+ overrideReplacesDocs !== false &&
1434
+ (utils.hasTag('override') || utils.classHasTag('override')) ||
1435
+ implementsReplacesDocs !== false &&
1436
+ (utils.hasTag('implements') || utils.classHasTag('implements')) ||
1437
+
1438
+ augmentsExtendsReplacesDocs &&
1439
+ (utils.hasATag([
1440
+ 'augments', 'extends',
1441
+ ]) ||
1442
+ utils.classHasTag('augments') ||
1443
+ utils.classHasTag('extends'))) {
1444
+ return true;
1445
+ }
1446
+
1447
+ if (jsdocUtils.exemptSpeciaMethods(
1448
+ jsdoc,
1449
+ node,
1450
+ context,
1451
+ /** @type {import('json-schema').JSONSchema4|import('json-schema').JSONSchema4[]} */ (
1452
+ ruleConfig.meta.schema
1453
+ ),
1454
+ )) {
1455
+ return true;
1456
+ }
1457
+
1458
+ const exemptedBy = context.options[0]?.exemptedBy ?? [
1459
+ 'inheritDoc',
1460
+ ...mode === 'closure' ? [] : [
1461
+ 'inheritdoc',
1462
+ ],
1463
+ ];
1464
+ if (exemptedBy.length && utils.getPresentTags(exemptedBy).length) {
1465
+ return true;
1466
+ }
1467
+
1468
+ return false;
1469
+ };
1470
+
1471
+ for (const method of [
1472
+ 'tagMightHaveNamePosition',
1473
+ 'tagMightHaveTypePosition',
1474
+ ]) {
1475
+ /** @type {TagMightHaveNamePositionTypePosition} */
1476
+ utils[
1477
+ /** @type {"tagMightHaveNamePosition"|"tagMightHaveTypePosition"} */ (
1478
+ method
1479
+ )
1480
+ ] = (tagName, otherModeMaps) => {
1481
+ const result = jsdocUtils[
1482
+ /** @type {"tagMightHaveNamePosition"|"tagMightHaveTypePosition"} */
1483
+ (method)
1484
+ ](tagName);
1485
+ if (result) {
1486
+ return true;
1487
+ }
1488
+
1489
+ if (!otherModeMaps) {
1490
+ return false;
1491
+ }
1492
+
1493
+ const otherResult = otherModeMaps.some((otherModeMap) => {
1494
+ return jsdocUtils[
1495
+ /** @type {"tagMightHaveNamePosition"|"tagMightHaveTypePosition"} */
1496
+ (method)
1497
+ ](tagName, otherModeMap);
1498
+ });
1499
+
1500
+ return otherResult ? {
1501
+ otherMode: true,
1502
+ } : false;
1503
+ };
1504
+ }
1505
+
1506
+ /** @type {TagMissingRequiredTypeOrNamepath} */
1507
+ utils.tagMissingRequiredTypeOrNamepath = (tagName, otherModeMaps) => {
1508
+ const result = jsdocUtils.tagMissingRequiredTypeOrNamepath(tagName);
1509
+ if (!result) {
1510
+ return false;
1511
+ }
1512
+
1513
+ const otherResult = otherModeMaps.every((otherModeMap) => {
1514
+ return jsdocUtils.tagMissingRequiredTypeOrNamepath(tagName, otherModeMap);
1515
+ });
1516
+
1517
+ return otherResult ? true : {
1518
+ otherMode: false,
1519
+ };
1520
+ };
1521
+
1522
+ for (const method of [
1523
+ 'tagMustHaveNamePosition',
1524
+ 'tagMustHaveTypePosition',
1525
+ ]) {
1526
+ /** @type {TagMustHave} */
1527
+ utils[
1528
+ /** @type {"tagMustHaveNamePosition"|"tagMustHaveTypePosition"} */
1529
+ (method)
1530
+ ] = (tagName, otherModeMaps) => {
1531
+ const result = jsdocUtils[
1532
+ /** @type {"tagMustHaveNamePosition"|"tagMustHaveTypePosition"} */
1533
+ (method)
1534
+ ](tagName);
1535
+ if (!result) {
1536
+ return false;
1537
+ }
1538
+
1539
+ // if (!otherModeMaps) { return true; }
1540
+
1541
+ const otherResult = otherModeMaps.every((otherModeMap) => {
1542
+ return jsdocUtils[
1543
+ /** @type {"tagMustHaveNamePosition"|"tagMustHaveTypePosition"} */
1544
+ (method)
1545
+ ](tagName, otherModeMap);
1546
+ });
1547
+
1548
+ return otherResult ? true : {
1549
+ otherMode: false,
1550
+ };
1551
+ };
1552
+ }
1553
+
1554
+ for (const method of [
1555
+ 'isNamepathDefiningTag',
1556
+ 'isNamepathReferencingTag',
1557
+ 'isNamepathOrUrlReferencingTag',
1558
+ 'tagMightHaveNamepath',
1559
+ ]) {
1560
+ /** @type {IsNamepathX} */
1561
+ utils[
1562
+ /** @type {"isNamepathDefiningTag"|"isNamepathReferencingTag"|"isNamepathOrUrlReferencingTag"|"tagMightHaveNamepath"} */ (
1563
+ method
1564
+ )] = (tagName) => {
1565
+ return jsdocUtils[
1566
+ /** @type {"isNamepathDefiningTag"|"isNamepathReferencingTag"|"isNamepathOrUrlReferencingTag"|"tagMightHaveNamepath"} */
1567
+ (method)
1568
+ ](tagName);
1569
+ };
1570
+ }
1571
+
1572
+ /** @type {GetTagStructureForMode} */
1573
+ utils.getTagStructureForMode = (mde) => {
1574
+ return jsdocUtils.getTagStructureForMode(mde, settings.structuredTags);
1575
+ };
1576
+
1577
+ /** @type {MayBeUndefinedTypeTag} */
1578
+ utils.mayBeUndefinedTypeTag = (tag) => {
1579
+ return jsdocUtils.mayBeUndefinedTypeTag(tag, settings.mode);
1580
+ };
1581
+
1582
+ /** @type {HasValueOrExecutorHasNonEmptyResolveValue} */
1583
+ utils.hasValueOrExecutorHasNonEmptyResolveValue = (anyPromiseAsReturn, allBranches) => {
1584
+ return jsdocUtils.hasValueOrExecutorHasNonEmptyResolveValue(
1585
+ /** @type {Node} */ (node), anyPromiseAsReturn, allBranches,
1586
+ );
1587
+ };
1588
+
1589
+ /** @type {HasYieldValue} */
1590
+ utils.hasYieldValue = () => {
1591
+ if ([
1592
+ 'ExportNamedDeclaration', 'ExportDefaultDeclaration',
1593
+ ].includes(/** @type {Node} */ (node).type)) {
1594
+ return jsdocUtils.hasYieldValue(
1595
+ /** @type {import('estree').Declaration|import('estree').Expression} */ (
1596
+ /** @type {import('estree').ExportNamedDeclaration|import('estree').ExportDefaultDeclaration} */
1597
+ (node).declaration
1598
+ ),
1599
+ );
1600
+ }
1601
+
1602
+ return jsdocUtils.hasYieldValue(/** @type {Node} */ (node));
1603
+ };
1604
+
1605
+ /** @type {HasYieldReturnValue} */
1606
+ utils.hasYieldReturnValue = () => {
1607
+ return jsdocUtils.hasYieldValue(/** @type {Node} */ (node), true);
1608
+ };
1609
+
1610
+ /** @type {HasThrowValue} */
1611
+ utils.hasThrowValue = () => {
1612
+ return jsdocUtils.hasThrowValue(node);
1613
+ };
1614
+
1615
+ /** @type {IsAsync} */
1616
+ utils.isAsync = () => {
1617
+ return 'async' in /** @type {Node} */ (node) && node.async;
1618
+ };
1619
+
1620
+ /** @type {GetTags} */
1621
+ utils.getTags = (tagName) => {
1622
+ return utils.filterTags((item) => {
1623
+ return item.tag === tagName;
1624
+ });
1625
+ };
1626
+
1627
+ /** @type {GetPresentTags} */
1628
+ utils.getPresentTags = (tagList) => {
1629
+ return utils.filterTags((tag) => {
1630
+ return tagList.includes(tag.tag);
1631
+ });
1632
+ };
1633
+
1634
+ /** @type {FilterTags} */
1635
+ utils.filterTags = (filter) => {
1636
+ return jsdoc.tags.filter((tag) => {
1637
+ return filter(tag);
1638
+ });
1639
+ };
1640
+
1641
+ /** @type {FilterAllTags} */
1642
+ utils.filterAllTags = (filter) => {
1643
+ const tags = jsdocUtils.getAllTags(jsdoc);
1644
+ return tags.filter((tag) => {
1645
+ return filter(tag);
1646
+ });
1647
+ };
1648
+
1649
+ /** @type {GetTagsByType} */
1650
+ utils.getTagsByType = (tags) => {
1651
+ return jsdocUtils.getTagsByType(context, mode, tags);
1652
+ };
1653
+
1654
+ /** @type {HasOptionTag} */
1655
+ utils.hasOptionTag = (tagName) => {
1656
+ const {
1657
+ tags,
1658
+ } = context.options[0] ?? {};
1659
+
1660
+ return Boolean(tags && tags.includes(tagName));
1661
+ };
1662
+
1663
+ /** @type {GetClassNode} */
1664
+ utils.getClassNode = () => {
1665
+ return [
1666
+ ...ancestors, node,
1667
+ ].reverse().find((parent) => {
1668
+ return parent && [
1669
+ 'ClassDeclaration', 'ClassExpression',
1670
+ ].includes(parent.type);
1671
+ }) ?? null;
1672
+ };
1673
+
1674
+ /** @type {GetClassJsdoc} */
1675
+ utils.getClassJsdoc = () => {
1676
+ const classNode = utils.getClassNode();
1677
+
1678
+ if (!classNode) {
1679
+ return null;
1680
+ }
1681
+
1682
+ const classJsdocNode = getJSDocComment(sourceCode, classNode, {
1683
+ maxLines,
1684
+ minLines,
1685
+ });
1686
+
1687
+ if (classJsdocNode) {
1688
+ return parseComment(classJsdocNode, '');
1689
+ }
1690
+
1691
+ return null;
1692
+ };
1693
+
1694
+ /** @type {ClassHasTag} */
1695
+ utils.classHasTag = (tagName) => {
1696
+ const classJsdoc = utils.getClassJsdoc();
1697
+
1698
+ return classJsdoc !== null && jsdocUtils.hasTag(classJsdoc, tagName);
1699
+ };
1700
+
1701
+ /** @type {ForEachPreferredTag} */
1702
+ utils.forEachPreferredTag = (tagName, arrayHandler, skipReportingBlockedTag = false) => {
1703
+ const targetTagName = /** @type {string|false} */ (
1704
+ utils.getPreferredTagName({
1705
+ skipReportingBlockedTag,
1706
+ tagName,
1707
+ })
1708
+ );
1709
+ if (!targetTagName ||
1710
+ skipReportingBlockedTag && targetTagName && typeof targetTagName === 'object'
1711
+ ) {
1712
+ return;
1713
+ }
1714
+
1715
+ const matchingJsdocTags = jsdoc.tags.filter(({
1716
+ tag,
1717
+ }) => {
1718
+ return tag === targetTagName;
1719
+ });
1720
+
1721
+ for (const matchingJsdocTag of matchingJsdocTags) {
1722
+ arrayHandler(
1723
+ /**
1724
+ * @type {import('@es-joy/jsdoccomment').JsdocTagWithInline}
1725
+ */ (
1726
+ matchingJsdocTag
1727
+ ), targetTagName,
1728
+ );
1729
+ }
1730
+ };
1731
+
1732
+ /** @type {FindContext} */
1733
+ utils.findContext = (contexts, comment) => {
1734
+ const foundContext = contexts.find((cntxt) => {
1735
+ return typeof cntxt === 'string' ?
1736
+ esquery.matches(
1737
+ /** @type {Node} */ (node),
1738
+ esquery.parse(cntxt),
1739
+ undefined,
1740
+ {
1741
+ visitorKeys: sourceCode.visitorKeys,
1742
+ },
1743
+ ) :
1744
+ (!cntxt.context || cntxt.context === 'any' ||
1745
+ esquery.matches(
1746
+ /** @type {Node} */ (node),
1747
+ esquery.parse(cntxt.context),
1748
+ undefined,
1749
+ {
1750
+ visitorKeys: sourceCode.visitorKeys,
1751
+ },
1752
+ )) && comment === cntxt.comment;
1753
+ });
1754
+
1755
+ const contextStr = typeof foundContext === 'object' ?
1756
+ foundContext.context ?? 'any' :
1757
+ String(foundContext);
1758
+
1759
+ return {
1760
+ contextStr,
1761
+ foundContext,
1762
+ };
1763
+ };
1764
+
1765
+ return utils;
1766
+ };
1767
+
1768
+ /**
1769
+ * @typedef {{
1770
+ * [key: string]: false|string|{
1771
+ * message: string,
1772
+ * replacement?: false|string
1773
+ * skipRootChecking?: boolean
1774
+ * }
1775
+ * }} PreferredTypes
1776
+ */
1777
+ /**
1778
+ * @typedef {{
1779
+ * [key: string]: {
1780
+ * name?: "text"|"namepath-defining"|"namepath-referencing"|false,
1781
+ * type?: boolean|string[],
1782
+ * required?: ("name"|"type"|"typeOrNameRequired")[]
1783
+ * }
1784
+ * }} StructuredTags
1785
+ */
1786
+ /**
1787
+ * Settings from ESLint types.
1788
+ * @typedef {{
1789
+ * maxLines: Integer,
1790
+ * minLines: Integer,
1791
+ * tagNamePreference: import('./jsdocUtils.js').TagNamePreference,
1792
+ * mode: import('./jsdocUtils.js').ParserMode,
1793
+ * preferredTypes: PreferredTypes,
1794
+ * structuredTags: StructuredTags,
1795
+ * [name: string]: any,
1796
+ * contexts?: Context[]
1797
+ * }} Settings
1798
+ */
1799
+
1800
+ /**
1801
+ * @param {import('eslint').Rule.RuleContext} context
1802
+ * @returns {Settings|false}
1803
+ */
1804
+ const getSettings = (context) => {
1805
+ /* dslint-disable canonical/sort-keys */
1806
+ const settings = {
1807
+ // All rules
1808
+ ignorePrivate: Boolean(context.settings.jsdoc?.ignorePrivate),
1809
+ ignoreInternal: Boolean(context.settings.jsdoc?.ignoreInternal),
1810
+ maxLines: Number(context.settings.jsdoc?.maxLines ?? 1),
1811
+ minLines: Number(context.settings.jsdoc?.minLines ?? 0),
1812
+
1813
+ // `check-tag-names` and many returns/param rules
1814
+ tagNamePreference: context.settings.jsdoc?.tagNamePreference ?? {},
1815
+
1816
+ // `check-types` and `no-undefined-types`
1817
+ preferredTypes: context.settings.jsdoc?.preferredTypes ?? {},
1818
+
1819
+ // `check-types`, `no-undefined-types`, `valid-types`
1820
+ structuredTags: context.settings.jsdoc?.structuredTags ?? {},
1821
+
1822
+ // `require-param`, `require-description`, `require-example`,
1823
+ // `require-returns`, `require-throw`, `require-yields`
1824
+ overrideReplacesDocs: context.settings.jsdoc?.overrideReplacesDocs,
1825
+ ignoreReplacesDocs: context.settings.jsdoc?.ignoreReplacesDocs,
1826
+ implementsReplacesDocs: context.settings.jsdoc?.implementsReplacesDocs,
1827
+ augmentsExtendsReplacesDocs: context.settings.jsdoc?.augmentsExtendsReplacesDocs,
1828
+
1829
+ // `require-param-type`, `require-param-description`
1830
+ exemptDestructuredRootsFromChecks: context.settings.jsdoc?.exemptDestructuredRootsFromChecks,
1831
+
1832
+ // Many rules, e.g., `check-tag-names`
1833
+ mode: context.settings.jsdoc?.mode ?? 'typescript',
1834
+
1835
+ // Many rules
1836
+ contexts: context.settings.jsdoc?.contexts,
1837
+ };
1838
+ /* dslint-enable canonical/sort-keys */
1839
+
1840
+ jsdocUtils.setTagStructure(settings.mode);
1841
+ try {
1842
+ jsdocUtils.overrideTagStructure(settings.structuredTags);
1843
+ } catch (error) {
1844
+ context.report({
1845
+ loc: {
1846
+ end: {
1847
+ column: 1,
1848
+ line: 1,
1849
+ },
1850
+ start: {
1851
+ column: 1,
1852
+ line: 1,
1853
+ },
1854
+ },
1855
+ message: /** @type {Error} */ (error).message,
1856
+ });
1857
+
1858
+ return false;
1859
+ }
1860
+
1861
+ return settings;
1862
+ };
1863
+
1864
+ /**
1865
+ * Create the report function
1866
+ * @callback MakeReport
1867
+ * @param {import('eslint').Rule.RuleContext} context
1868
+ * @param {import('estree').Node} commentNode
1869
+ * @returns {Report}
1870
+ */
1871
+
1872
+ /** @type {MakeReport} */
1873
+ const makeReport = (context, commentNode) => {
1874
+ /** @type {Report} */
1875
+ const report = (message, fix = null, jsdocLoc = null, data = undefined) => {
1876
+ let loc;
1877
+
1878
+ if (jsdocLoc) {
1879
+ if (!('line' in jsdocLoc)) {
1880
+ jsdocLoc.line = /** @type {import('comment-parser').Spec & {line?: Integer}} */ (
1881
+ jsdocLoc
1882
+ ).source[0].number;
1883
+ }
1884
+
1885
+ const lineNumber = /** @type {import('eslint').AST.SourceLocation} */ (
1886
+ commentNode.loc
1887
+ ).start.line +
1888
+ /** @type {Integer} */ (jsdocLoc.line);
1889
+
1890
+ loc = {
1891
+ end: {
1892
+ column: 0,
1893
+ line: lineNumber,
1894
+ },
1895
+ start: {
1896
+ column: 0,
1897
+ line: lineNumber,
1898
+ },
1899
+ };
1900
+
1901
+ // Todo: Remove ignore once `check-examples` can be restored for ESLint 8+
1902
+ if ('column' in jsdocLoc && typeof jsdocLoc.column === 'number') {
1903
+ const colNumber = /** @type {import('eslint').AST.SourceLocation} */ (
1904
+ commentNode.loc
1905
+ ).start.column + jsdocLoc.column;
1906
+
1907
+ loc.end.column = colNumber;
1908
+ loc.start.column = colNumber;
1909
+ }
1910
+ }
1911
+
1912
+ context.report({
1913
+ data,
1914
+ fix,
1915
+ loc,
1916
+ message,
1917
+ node: commentNode,
1918
+ });
1919
+ };
1920
+
1921
+ return report;
1922
+ };
1923
+
1924
+ /**
1925
+ * @typedef {(
1926
+ * arg: {
1927
+ * context: import('eslint').Rule.RuleContext,
1928
+ * sourceCode: import('eslint').SourceCode,
1929
+ * indent?: string,
1930
+ * info?: {
1931
+ * comment?: string|undefined,
1932
+ * lastIndex?: Integer|undefined
1933
+ * },
1934
+ * state?: StateObject,
1935
+ * globalState?: Map<string, Map<string, string>>,
1936
+ * jsdoc?: JsdocBlockWithInline,
1937
+ * jsdocNode?: import('eslint').Rule.Node & {
1938
+ * range: [number, number]
1939
+ * },
1940
+ * node?: Node,
1941
+ * allComments?: import('estree').Node[]
1942
+ * report?: Report,
1943
+ * makeReport?: MakeReport,
1944
+ * settings: Settings,
1945
+ * utils: BasicUtils,
1946
+ * }
1947
+ * ) => any } JsdocVisitorBasic
1948
+ */
1949
+ /**
1950
+ * @typedef {(
1951
+ * arg: {
1952
+ * context: import('eslint').Rule.RuleContext,
1953
+ * sourceCode: import('eslint').SourceCode,
1954
+ * indent: string,
1955
+ * info: {
1956
+ * comment?: string|undefined,
1957
+ * lastIndex?: Integer|undefined
1958
+ * },
1959
+ * state: StateObject,
1960
+ * globalState: Map<string, Map<string, string>>,
1961
+ * jsdoc: JsdocBlockWithInline,
1962
+ * jsdocNode: import('eslint').Rule.Node & {
1963
+ * range: [number, number]
1964
+ * },
1965
+ * node: Node|null,
1966
+ * allComments?: import('estree').Node[]
1967
+ * report: Report,
1968
+ * makeReport?: MakeReport,
1969
+ * settings: Settings,
1970
+ * utils: Utils,
1971
+ * }
1972
+ * ) => any } JsdocVisitor
1973
+ */
1974
+
1975
+ /**
1976
+ * @param {{
1977
+ * comment?: string,
1978
+ * lastIndex?: Integer,
1979
+ * selector?: string,
1980
+ * isFunctionContext?: boolean,
1981
+ * }} info
1982
+ * @param {string} indent
1983
+ * @param {JsdocBlockWithInline} jsdoc
1984
+ * @param {RuleConfig} ruleConfig
1985
+ * @param {import('eslint').Rule.RuleContext} context
1986
+ * @param {import('@es-joy/jsdoccomment').Token} jsdocNode
1987
+ * @param {Node|null} node
1988
+ * @param {Settings} settings
1989
+ * @param {import('eslint').SourceCode} sourceCode
1990
+ * @param {JsdocVisitor} iterator
1991
+ * @param {StateObject} state
1992
+ * @param {boolean} [iteratingAll]
1993
+ * @returns {void}
1994
+ */
1995
+ const iterate = (
1996
+ info,
1997
+ indent, jsdoc,
1998
+ ruleConfig, context, jsdocNode, node, settings,
1999
+ sourceCode, iterator, state, iteratingAll,
2000
+ ) => {
2001
+ const jsdocNde = /** @type {unknown} */ (jsdocNode);
2002
+ const report = makeReport(
2003
+ context,
2004
+ /** @type {import('estree').Node} */
2005
+ (jsdocNde),
2006
+ );
2007
+
2008
+ const utils = getUtils(
2009
+ node,
2010
+ jsdoc,
2011
+ /** @type {import('eslint').AST.Token} */
2012
+ (jsdocNode),
2013
+ settings,
2014
+ report,
2015
+ context,
2016
+ sourceCode,
2017
+ iteratingAll,
2018
+ ruleConfig,
2019
+ indent,
2020
+ );
2021
+
2022
+ if (
2023
+ !ruleConfig.checkInternal && settings.ignoreInternal &&
2024
+ utils.hasTag('internal')
2025
+ ) {
2026
+ return;
2027
+ }
2028
+
2029
+ if (
2030
+ !ruleConfig.checkPrivate && settings.ignorePrivate &&
2031
+ (
2032
+ utils.hasTag('private') ||
2033
+ jsdoc.tags
2034
+ .filter(({
2035
+ tag,
2036
+ }) => {
2037
+ return tag === 'access';
2038
+ })
2039
+ .some(({
2040
+ description,
2041
+ }) => {
2042
+ return description === 'private';
2043
+ })
2044
+ )
2045
+ ) {
2046
+ return;
2047
+ }
2048
+
2049
+ iterator({
2050
+ context,
2051
+ globalState,
2052
+ indent,
2053
+ info,
2054
+ jsdoc,
2055
+ jsdocNode: /**
2056
+ * @type {import('eslint').Rule.Node & {
2057
+ * range: [number, number];}}
2058
+ */ (jsdocNde),
2059
+ node,
2060
+ report,
2061
+ settings,
2062
+ sourceCode,
2063
+ state,
2064
+ utils,
2065
+ });
2066
+ };
2067
+
2068
+ /**
2069
+ * @param {string[]} lines
2070
+ * @param {import('estree').Comment} jsdocNode
2071
+ * @returns {[indent: string, jsdoc: JsdocBlockWithInline]}
2072
+ */
2073
+ const getIndentAndJSDoc = function (lines, jsdocNode) {
2074
+ const sourceLine = lines[
2075
+ /** @type {import('estree').SourceLocation} */
2076
+ (jsdocNode.loc).start.line - 1
2077
+ ];
2078
+ const indnt = sourceLine.charAt(0).repeat(
2079
+ /** @type {import('estree').SourceLocation} */
2080
+ (jsdocNode.loc).start.column,
2081
+ );
2082
+
2083
+ const jsdc = parseComment(jsdocNode, '');
2084
+
2085
+ return [
2086
+ indnt, jsdc,
2087
+ ];
2088
+ };
2089
+
2090
+ /**
2091
+ *
2092
+ * @typedef {{node: Node & {
2093
+ * range: [number, number]
2094
+ * }, state: StateObject}} NonCommentArgs
2095
+ */
2096
+
2097
+ /**
2098
+ * @typedef {object} RuleConfig
2099
+ * @property {EslintRuleMeta} meta ESLint rule meta
2100
+ * @property {import('./jsdocUtils.js').DefaultContexts} [contextDefaults] Any default contexts
2101
+ * @property {true} [contextSelected] Whether to force a `contexts` check
2102
+ * @property {true} [iterateAllJsdocs] Whether to iterate all JSDoc blocks by default
2103
+ * regardless of context
2104
+ * @property {true} [checkPrivate] Whether to check `@private` blocks (normally exempted)
2105
+ * @property {true} [checkInternal] Whether to check `@internal` blocks (normally exempted)
2106
+ * @property {true} [checkFile] Whether to iterates over all JSDoc blocks regardless of attachment
2107
+ * @property {true} [nonGlobalSettings] Whether to avoid relying on settings for global contexts
2108
+ * @property {true} [noTracking] Whether to disable the tracking of visited comment nodes (as
2109
+ * non-tracked may conduct further actions)
2110
+ * @property {true} [matchContext] Whether the rule expects contexts to be based on a match option
2111
+ * @property {(args: {
2112
+ * context: import('eslint').Rule.RuleContext,
2113
+ * state: StateObject,
2114
+ * settings: Settings,
2115
+ * utils: BasicUtils
2116
+ * }) => void} [exit] Handler to be executed upon exiting iteration of program AST
2117
+ * @property {(nca: NonCommentArgs) => void} [nonComment] Handler to be executed if rule wishes
2118
+ * to be supplied nodes without comments
2119
+ */
2120
+
2121
+ /**
2122
+ * Create an eslint rule that iterates over all JSDocs, regardless of whether
2123
+ * they are attached to a function-like node.
2124
+ * @param {JsdocVisitor} iterator
2125
+ * @param {RuleConfig} ruleConfig The rule's configuration
2126
+ * @param {ContextObject[]|null} [contexts] The `contexts` containing relevant `comment` info.
2127
+ * @param {boolean} [additiveCommentContexts] If true, will have a separate
2128
+ * iteration for each matching comment context. Otherwise, will iterate
2129
+ * once if there is a single matching comment context.
2130
+ * @returns {import('eslint').Rule.RuleModule}
2131
+ */
2132
+ const iterateAllJsdocs = (iterator, ruleConfig, contexts, additiveCommentContexts) => {
2133
+ const trackedJsdocs = new Set();
2134
+
2135
+ /** @type {import('@es-joy/jsdoccomment').CommentHandler} */
2136
+ let handler;
2137
+
2138
+ /** @type {Settings|false} */
2139
+ let settings;
2140
+
2141
+ /**
2142
+ * @param {import('eslint').Rule.RuleContext} context
2143
+ * @param {Node|null} node
2144
+ * @param {import('estree').Comment[]} jsdocNodes
2145
+ * @param {StateObject} state
2146
+ * @param {boolean} [lastCall]
2147
+ * @returns {void}
2148
+ */
2149
+ const callIterator = (context, node, jsdocNodes, state, lastCall) => {
2150
+ /* c8 ignore next -- Fallback to deprecated method */
2151
+ const {
2152
+ sourceCode = context.getSourceCode(),
2153
+ } = context;
2154
+ const {
2155
+ lines,
2156
+ } = sourceCode;
2157
+
2158
+ const utils = getBasicUtils(context, /** @type {Settings} */ (settings));
2159
+ for (const jsdocNode of jsdocNodes) {
2160
+ const jsdocNde = /** @type {unknown} */ (jsdocNode);
2161
+ if (!(/^\/\*\*\s/u).test(sourceCode.getText(
2162
+ /** @type {import('estree').Node} */
2163
+ (jsdocNde),
2164
+ ))) {
2165
+ continue;
2166
+ }
2167
+
2168
+ const [
2169
+ indent,
2170
+ jsdoc,
2171
+ ] = getIndentAndJSDoc(
2172
+ lines, jsdocNode,
2173
+ );
2174
+
2175
+ if (additiveCommentContexts) {
2176
+ for (const [
2177
+ idx,
2178
+ {
2179
+ comment,
2180
+ },
2181
+ ] of /** @type {ContextObject[]} */ (contexts).entries()) {
2182
+ if (comment && handler(comment, jsdoc) === false) {
2183
+ continue;
2184
+ }
2185
+
2186
+ iterate(
2187
+ {
2188
+ comment,
2189
+ lastIndex: idx,
2190
+ selector: node?.type,
2191
+ },
2192
+ indent,
2193
+ jsdoc,
2194
+ ruleConfig,
2195
+ context,
2196
+ jsdocNode,
2197
+ /** @type {Node} */
2198
+ (node),
2199
+ /** @type {Settings} */
2200
+ (settings),
2201
+ sourceCode,
2202
+ iterator,
2203
+ state,
2204
+ true,
2205
+ );
2206
+ }
2207
+
2208
+ continue;
2209
+ }
2210
+
2211
+ let lastComment;
2212
+ let lastIndex;
2213
+ // eslint-disable-next-line no-loop-func
2214
+ if (contexts && contexts.every(({
2215
+ comment,
2216
+ }, idx) => {
2217
+ lastComment = comment;
2218
+ lastIndex = idx;
2219
+
2220
+ return comment && handler(comment, jsdoc) === false;
2221
+ })) {
2222
+ continue;
2223
+ }
2224
+
2225
+ iterate(
2226
+ lastComment ? {
2227
+ comment: lastComment,
2228
+ lastIndex,
2229
+ selector: node?.type,
2230
+ } : {
2231
+ lastIndex,
2232
+ selector: node?.type,
2233
+ },
2234
+ indent,
2235
+ jsdoc,
2236
+ ruleConfig,
2237
+ context,
2238
+ jsdocNode,
2239
+ node,
2240
+ /** @type {Settings} */
2241
+ (settings),
2242
+ sourceCode,
2243
+ iterator,
2244
+ state,
2245
+ true,
2246
+ );
2247
+ }
2248
+
2249
+ const settngs = /** @type {Settings} */ (settings);
2250
+
2251
+ if (lastCall && ruleConfig.exit) {
2252
+ ruleConfig.exit({
2253
+ context,
2254
+ settings: settngs,
2255
+ state,
2256
+ utils,
2257
+ });
2258
+ }
2259
+ };
2260
+
2261
+ return {
2262
+ // @ts-expect-error ESLint accepts
2263
+ create (context) {
2264
+ /* c8 ignore next -- Fallback to deprecated method */
2265
+ const {
2266
+ sourceCode = context.getSourceCode(),
2267
+ } = context;
2268
+ settings = getSettings(context);
2269
+ if (!settings) {
2270
+ return {};
2271
+ }
2272
+
2273
+ if (contexts) {
2274
+ handler = commentHandler(settings);
2275
+ }
2276
+
2277
+ const state = {};
2278
+
2279
+ return {
2280
+ /**
2281
+ * @param {import('eslint').Rule.Node & {
2282
+ * range: [Integer, Integer];
2283
+ * }} node
2284
+ * @returns {void}
2285
+ */
2286
+ '*:not(Program)' (node) {
2287
+ const commentNode = getJSDocComment(
2288
+ sourceCode, node, /** @type {Settings} */ (settings),
2289
+ );
2290
+ if (!ruleConfig.noTracking && trackedJsdocs.has(commentNode)) {
2291
+ return;
2292
+ }
2293
+
2294
+ if (!commentNode) {
2295
+ if (ruleConfig.nonComment) {
2296
+ const ste = /** @type {StateObject} */ (state);
2297
+ ruleConfig.nonComment({
2298
+ node,
2299
+ state: ste,
2300
+ });
2301
+ }
2302
+
2303
+ return;
2304
+ }
2305
+
2306
+ trackedJsdocs.add(commentNode);
2307
+ callIterator(context, node, [
2308
+ /** @type {import('estree').Comment} */
2309
+ (commentNode),
2310
+ ], /** @type {StateObject} */ (state));
2311
+ },
2312
+ 'Program:exit' () {
2313
+ const allComments = sourceCode.getAllComments();
2314
+ const untrackedJSdoc = allComments.filter((node) => {
2315
+ return !trackedJsdocs.has(node);
2316
+ });
2317
+
2318
+ callIterator(
2319
+ context,
2320
+ null,
2321
+ untrackedJSdoc,
2322
+ /** @type {StateObject} */
2323
+ (state),
2324
+ true,
2325
+ );
2326
+ },
2327
+ };
2328
+ },
2329
+ meta: ruleConfig.meta,
2330
+ };
2331
+ };
2332
+
2333
+ /**
2334
+ * Create an eslint rule that iterates over all JSDocs, regardless of whether
2335
+ * they are attached to a function-like node.
2336
+ * @param {JsdocVisitorBasic} iterator
2337
+ * @param {RuleConfig} ruleConfig
2338
+ * @returns {import('eslint').Rule.RuleModule}
2339
+ */
2340
+ const checkFile = (iterator, ruleConfig) => {
2341
+ return {
2342
+ create (context) {
2343
+ /* c8 ignore next -- Fallback to deprecated method */
2344
+ const {
2345
+ sourceCode = context.getSourceCode(),
2346
+ } = context;
2347
+ const settings = getSettings(context);
2348
+ if (!settings) {
2349
+ return {};
2350
+ }
2351
+
2352
+ return {
2353
+ 'Program:exit' () {
2354
+ const allComms = /** @type {unknown} */ (sourceCode.getAllComments());
2355
+ const utils = getBasicUtils(context, settings);
2356
+
2357
+ iterator({
2358
+ allComments: /** @type {import('estree').Node[]} */ (allComms),
2359
+ context,
2360
+ makeReport,
2361
+ settings,
2362
+ sourceCode,
2363
+ utils,
2364
+ });
2365
+ },
2366
+ };
2367
+ },
2368
+ meta: ruleConfig.meta,
2369
+ };
2370
+ };
2371
+
2372
+ export {
2373
+ getSettings,
2374
+ // dslint-disable-next-line unicorn/prefer-export-from -- Avoid experimental parser
2375
+ parseComment,
2376
+ };
2377
+
2378
+ /**
2379
+ * @param {JsdocVisitor} iterator
2380
+ * @param {RuleConfig} ruleConfig
2381
+ * @returns {import('eslint').Rule.RuleModule}
2382
+ */
2383
+ export default function iterateJsdoc (iterator, ruleConfig) {
2384
+ const metaType = ruleConfig?.meta?.type;
2385
+ if (!metaType || ![
2386
+ 'problem', 'suggestion', 'layout',
2387
+ ].includes(metaType)) {
2388
+ throw new TypeError('Rule must include `meta.type` option (with value "problem", "suggestion", or "layout")');
2389
+ }
2390
+
2391
+ if (typeof iterator !== 'function') {
2392
+ throw new TypeError('The iterator argument must be a function.');
2393
+ }
2394
+
2395
+ if (ruleConfig.checkFile) {
2396
+ return checkFile(
2397
+ /** @type {JsdocVisitorBasic} */ (iterator),
2398
+ ruleConfig,
2399
+ );
2400
+ }
2401
+
2402
+ if (ruleConfig.iterateAllJsdocs) {
2403
+ return iterateAllJsdocs(iterator, ruleConfig);
2404
+ }
2405
+
2406
+ /** @type {import('eslint').Rule.RuleModule} */
2407
+ return {
2408
+ /**
2409
+ * The entrypoint for the JSDoc rule.
2410
+ * @param {import('eslint').Rule.RuleContext} context
2411
+ * a reference to the context which hold all important information
2412
+ * like settings and the sourcecode to check.
2413
+ * @returns {import('eslint').Rule.RuleListener}
2414
+ * a listener with parser callback function.
2415
+ */
2416
+ create (context) {
2417
+ const settings = getSettings(context);
2418
+ if (!settings) {
2419
+ return {};
2420
+ }
2421
+
2422
+ /**
2423
+ * @type {Context[]|undefined}
2424
+ */
2425
+ let contexts;
2426
+ if (ruleConfig.contextDefaults || ruleConfig.contextSelected || ruleConfig.matchContext) {
2427
+ contexts = ruleConfig.matchContext && context.options[0]?.match ?
2428
+ context.options[0].match :
2429
+ jsdocUtils.enforcedContexts(context, ruleConfig.contextDefaults, ruleConfig.nonGlobalSettings ? {} : settings);
2430
+
2431
+ if (contexts) {
2432
+ contexts = contexts.map((obj) => {
2433
+ if (typeof obj === 'object' && !obj.context) {
2434
+ return {
2435
+ ...obj,
2436
+ context: 'any',
2437
+ };
2438
+ }
2439
+
2440
+ return obj;
2441
+ });
2442
+ }
2443
+
2444
+ const hasPlainAny = contexts?.includes('any');
2445
+ const hasObjectAny = !hasPlainAny && contexts?.find((ctxt) => {
2446
+ if (typeof ctxt === 'string') {
2447
+ return false;
2448
+ }
2449
+
2450
+ return ctxt?.context === 'any';
2451
+ });
2452
+ if (hasPlainAny || hasObjectAny) {
2453
+ return iterateAllJsdocs(
2454
+ iterator,
2455
+ ruleConfig,
2456
+ hasObjectAny ? /** @type {ContextObject[]} */ (contexts) : null,
2457
+ ruleConfig.matchContext,
2458
+ ).create(context);
2459
+ }
2460
+ }
2461
+
2462
+ /* c8 ignore next -- Fallback to deprecated method */
2463
+ const {
2464
+ sourceCode = context.getSourceCode(),
2465
+ } = context;
2466
+ const {
2467
+ lines,
2468
+ } = sourceCode;
2469
+
2470
+ /** @type {Partial<StateObject>} */
2471
+ const state = {};
2472
+
2473
+ /** @type {CheckJsdoc} */
2474
+ const checkJsdoc = (info, handler, node) => {
2475
+ const jsdocNode = getJSDocComment(sourceCode, node, settings);
2476
+ if (!jsdocNode) {
2477
+ return;
2478
+ }
2479
+
2480
+ const [
2481
+ indent,
2482
+ jsdoc,
2483
+ ] = getIndentAndJSDoc(
2484
+ lines,
2485
+ /** @type {import('estree').Comment} */
2486
+ (jsdocNode),
2487
+ );
2488
+
2489
+ if (
2490
+ // Note, `handler` should already be bound in its first argument
2491
+ // with these only to be called after the value of
2492
+ // `comment`
2493
+ handler && handler(jsdoc) === false
2494
+ ) {
2495
+ return;
2496
+ }
2497
+
2498
+ iterate(
2499
+ info,
2500
+ indent,
2501
+ jsdoc,
2502
+ ruleConfig,
2503
+ context,
2504
+ jsdocNode,
2505
+ node,
2506
+ settings,
2507
+ sourceCode,
2508
+ iterator,
2509
+ /** @type {StateObject} */
2510
+ (state),
2511
+ );
2512
+ };
2513
+
2514
+ /** @type {import('eslint').Rule.RuleListener} */
2515
+ let contextObject = {};
2516
+
2517
+ if (contexts && (
2518
+ ruleConfig.contextDefaults || ruleConfig.contextSelected || ruleConfig.matchContext
2519
+ )) {
2520
+ contextObject = jsdocUtils.getContextObject(
2521
+ contexts,
2522
+ checkJsdoc,
2523
+ commentHandler(settings),
2524
+ );
2525
+ } else {
2526
+ for (const prop of [
2527
+ 'ArrowFunctionExpression',
2528
+ 'FunctionDeclaration',
2529
+ 'FunctionExpression',
2530
+ 'TSDeclareFunction',
2531
+ ]) {
2532
+ contextObject[prop] = checkJsdoc.bind(null, {
2533
+ selector: prop,
2534
+ }, null);
2535
+ }
2536
+ }
2537
+
2538
+ if (typeof ruleConfig.exit === 'function') {
2539
+ contextObject['Program:exit'] = () => {
2540
+ const ste = /** @type {StateObject} */ (state);
2541
+
2542
+ // @ts-expect-error `utils` not needed at this point
2543
+ /** @type {Required<RuleConfig>} */ (ruleConfig).exit({
2544
+ context,
2545
+ settings,
2546
+ state: ste,
2547
+ });
2548
+ };
2549
+ }
2550
+
2551
+ return contextObject;
2552
+ },
2553
+ meta: ruleConfig.meta,
2554
+ };
2555
+ }