@khanacademy/perseus-linter 0.0.0-PR443-20230328215601

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 (53) hide show
  1. package/.eslintrc.js +12 -0
  2. package/CHANGELOG.md +68 -0
  3. package/dist/es/index.js +1841 -0
  4. package/dist/es/index.js.map +1 -0
  5. package/dist/index.js +1835 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +34 -0
  8. package/src/README.md +41 -0
  9. package/src/__tests__/matcher.test.ts +498 -0
  10. package/src/__tests__/rule.test.ts +110 -0
  11. package/src/__tests__/rules.test.ts +548 -0
  12. package/src/__tests__/selector-parser.test.ts +51 -0
  13. package/src/__tests__/tree-transformer.test.ts +444 -0
  14. package/src/index.ts +279 -0
  15. package/src/proptypes.ts +19 -0
  16. package/src/rule.ts +419 -0
  17. package/src/rules/absolute-url.ts +23 -0
  18. package/src/rules/all-rules.ts +71 -0
  19. package/src/rules/blockquoted-math.ts +9 -0
  20. package/src/rules/blockquoted-widget.ts +9 -0
  21. package/src/rules/double-spacing-after-terminal.ts +11 -0
  22. package/src/rules/extra-content-spacing.ts +11 -0
  23. package/src/rules/heading-level-1.ts +13 -0
  24. package/src/rules/heading-level-skip.ts +19 -0
  25. package/src/rules/heading-sentence-case.ts +10 -0
  26. package/src/rules/heading-title-case.ts +68 -0
  27. package/src/rules/image-alt-text.ts +20 -0
  28. package/src/rules/image-in-table.ts +9 -0
  29. package/src/rules/image-spaces-around-urls.ts +34 -0
  30. package/src/rules/image-widget.ts +49 -0
  31. package/src/rules/link-click-here.ts +10 -0
  32. package/src/rules/lint-utils.ts +47 -0
  33. package/src/rules/long-paragraph.ts +13 -0
  34. package/src/rules/math-adjacent.ts +9 -0
  35. package/src/rules/math-align-extra-break.ts +10 -0
  36. package/src/rules/math-align-linebreaks.ts +42 -0
  37. package/src/rules/math-empty.ts +9 -0
  38. package/src/rules/math-font-size.ts +11 -0
  39. package/src/rules/math-frac.ts +9 -0
  40. package/src/rules/math-nested.ts +10 -0
  41. package/src/rules/math-starts-with-space.ts +11 -0
  42. package/src/rules/math-text-empty.ts +9 -0
  43. package/src/rules/math-without-dollars.ts +13 -0
  44. package/src/rules/nested-lists.ts +10 -0
  45. package/src/rules/profanity.ts +9 -0
  46. package/src/rules/table-missing-cells.ts +19 -0
  47. package/src/rules/unbalanced-code-delimiters.ts +13 -0
  48. package/src/rules/unescaped-dollar.ts +9 -0
  49. package/src/rules/widget-in-table.ts +9 -0
  50. package/src/selector.ts +504 -0
  51. package/src/tree-transformer.ts +587 -0
  52. package/src/types.ts +7 -0
  53. package/tsconfig.json +12 -0
package/dist/index.js ADDED
@@ -0,0 +1,1835 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var perseusError = require('@khanacademy/perseus-error');
6
+ var PropTypes = require('prop-types');
7
+
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
+
10
+ var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
11
+
12
+ function _defineProperty(obj, key, value) {
13
+ key = _toPropertyKey(key);
14
+ if (key in obj) {
15
+ Object.defineProperty(obj, key, {
16
+ value: value,
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true
20
+ });
21
+ } else {
22
+ obj[key] = value;
23
+ }
24
+ return obj;
25
+ }
26
+ function _toPrimitive(input, hint) {
27
+ if (typeof input !== "object" || input === null) return input;
28
+ var prim = input[Symbol.toPrimitive];
29
+ if (prim !== undefined) {
30
+ var res = prim.call(input, hint || "default");
31
+ if (typeof res !== "object") return res;
32
+ throw new TypeError("@@toPrimitive must return a primitive value.");
33
+ }
34
+ return (hint === "string" ? String : Number)(input);
35
+ }
36
+ function _toPropertyKey(arg) {
37
+ var key = _toPrimitive(arg, "string");
38
+ return typeof key === "symbol" ? key : String(key);
39
+ }
40
+
41
+ /**
42
+ * This is the base class for all Selector types. The key method that all
43
+ * selector subclasses must implement is match(). It takes a TraversalState
44
+ * object (from a TreeTransformer traversal) and tests whether the selector
45
+ * matches at the current node. See the comment at the start of this file for
46
+ * more details on the match() method.
47
+ */
48
+ class Selector {
49
+ static parse(selectorText) {
50
+ return new Parser(selectorText).parse();
51
+ }
52
+
53
+ /**
54
+ * Return an array of the nodes that matched or null if no match.
55
+ * This is the base class so we just throw an exception. All Selector
56
+ * subclasses must provide an implementation of this method.
57
+ */
58
+ match(state) {
59
+ throw new perseusError.PerseusError("Selector subclasses must implement match()", perseusError.Errors.NotAllowed);
60
+ }
61
+
62
+ /**
63
+ * Selector subclasses all define a toString() method primarily
64
+ * because it makes it easy to write parser tests.
65
+ */
66
+ toString() {
67
+ return "Unknown selector class";
68
+ }
69
+ }
70
+
71
+ /**
72
+ * This class implements a parser for the selector grammar. Pass the source
73
+ * text to the Parser() constructor, and then call the parse() method to
74
+ * obtain a corresponding Selector object. parse() throws an exception
75
+ * if there are syntax errors in the selector.
76
+ *
77
+ * This class is not exported, and you don't need to use it directly.
78
+ * Instead call the static Selector.parse() method.
79
+ */
80
+ class Parser {
81
+ // We do lexing with a simple regular expression
82
+ // The array of tokens
83
+ // Which token in the array we're looking at now
84
+
85
+ constructor(s) {
86
+ _defineProperty(this, "tokens", void 0);
87
+ _defineProperty(this, "tokenIndex", void 0);
88
+ // Normalize whitespace:
89
+ // - remove leading and trailing whitespace
90
+ // - replace runs of whitespace with single space characters
91
+ s = s.trim().replace(/\s+/g, " ");
92
+ // Convert the string to an array of tokens. Note that the TOKENS
93
+ // pattern ignores spaces that do not appear before identifiers
94
+ // or the * wildcard.
95
+ this.tokens = s.match(Parser.TOKENS) || [];
96
+ this.tokenIndex = 0;
97
+ }
98
+
99
+ // Return the next token or the empty string if there are no more
100
+ nextToken() {
101
+ return this.tokens[this.tokenIndex] || "";
102
+ }
103
+
104
+ // Increment the token index to "consume" the token we were looking at
105
+ // and move on to the next one.
106
+ consume() {
107
+ this.tokenIndex++;
108
+ }
109
+
110
+ // Return true if the current token is an identifier or false otherwise
111
+ isIdentifier() {
112
+ // The Parser.TOKENS regexp ensures that we only have to check
113
+ // the first character of a token to know what kind of token it is.
114
+ const c = this.tokens[this.tokenIndex][0];
115
+ return c >= "a" && c <= "z" || c >= "A" && c <= "Z";
116
+ }
117
+
118
+ // Consume space tokens until the next token is not a space.
119
+ skipSpace() {
120
+ while (this.nextToken() === " ") {
121
+ this.consume();
122
+ }
123
+ }
124
+
125
+ // Parse a comma-separated sequence of tree selectors. This is the
126
+ // entry point for the Parser class and the only method that clients
127
+ // ever need to call.
128
+ parse() {
129
+ // We expect at least one tree selector
130
+ const ts = this.parseTreeSelector();
131
+
132
+ // Now see what's next
133
+ let token = this.nextToken();
134
+
135
+ // If there is no next token then we're done parsing and can return
136
+ // the tree selector object we got above
137
+ if (!token) {
138
+ return ts;
139
+ }
140
+
141
+ // Otherwise, there is more go come and we're going to need a
142
+ // list of tree selectors
143
+ const treeSelectors = [ts];
144
+ while (token) {
145
+ // The only character we allow after a tree selector is a comma
146
+ if (token === ",") {
147
+ this.consume();
148
+ } else {
149
+ throw new ParseError("Expected comma");
150
+ }
151
+
152
+ // And if we saw a comma, then it must be followed by another
153
+ // tree selector
154
+ treeSelectors.push(this.parseTreeSelector());
155
+ token = this.nextToken();
156
+ }
157
+
158
+ // If we parsed more than one tree selector, return them in a
159
+ // SelectorList object.
160
+ return new SelectorList(treeSelectors);
161
+ }
162
+
163
+ // Parse a sequence of node selectors linked together with
164
+ // hierarchy combinators: space, >, + and ~.
165
+ parseTreeSelector() {
166
+ this.skipSpace(); // Ignore space after a comma, for example
167
+
168
+ // A tree selector must begin with a node selector
169
+ let ns = this.parseNodeSelector();
170
+ for (;;) {
171
+ // Now check the next token. If there is none, or if it is a
172
+ // comma, then we're done with the treeSelector. Otherwise
173
+ // we expect a combinator followed by another node selector.
174
+ // If we don't see a combinator, we throw an error. If we
175
+ // do see a combinator and another node selector then we
176
+ // combine the current node selector with the new node selector
177
+ // using a Selector subclass that depends on the combinator.
178
+ const token = this.nextToken();
179
+ if (!token || token === ",") {
180
+ break;
181
+ } else if (token === " ") {
182
+ this.consume();
183
+ ns = new AncestorCombinator(ns, this.parseNodeSelector());
184
+ } else if (token === ">") {
185
+ this.consume();
186
+ ns = new ParentCombinator(ns, this.parseNodeSelector());
187
+ } else if (token === "+") {
188
+ this.consume();
189
+ ns = new PreviousCombinator(ns, this.parseNodeSelector());
190
+ } else if (token === "~") {
191
+ this.consume();
192
+ ns = new SiblingCombinator(ns, this.parseNodeSelector());
193
+ } else {
194
+ throw new ParseError("Unexpected token: " + token);
195
+ }
196
+ }
197
+ return ns;
198
+ }
199
+
200
+ // Parse a single node selector.
201
+ // For now, this is just a node type or a wildcard.
202
+ //
203
+ // TODO(davidflanagan): we may need to extend this with attribute
204
+ // selectors like 'heading[level=3]', or with pseudo-classes like
205
+ // paragraph:first-child
206
+ parseNodeSelector() {
207
+ // First, skip any whitespace
208
+ this.skipSpace();
209
+ const t = this.nextToken();
210
+ if (t === "*") {
211
+ this.consume();
212
+ return new AnyNode();
213
+ }
214
+ if (this.isIdentifier()) {
215
+ this.consume();
216
+ return new TypeSelector(t);
217
+ }
218
+ throw new ParseError("Expected node type");
219
+ }
220
+ }
221
+
222
+ // We break the input string into tokens with this regexp. Token types
223
+ // are identifiers, integers, punctuation and spaces. Note that spaces
224
+ // tokens are only returned when they appear before an identifier or
225
+ // wildcard token and are otherwise omitted.
226
+ _defineProperty(Parser, "TOKENS", void 0);
227
+ Parser.TOKENS = /([a-zA-Z][\w-]*)|(\d+)|[^\s]|(\s(?=[a-zA-Z\*]))/g;
228
+
229
+ /**
230
+ * This is a trivial Error subclass that the Parser uses to signal parse errors
231
+ */
232
+ class ParseError extends Error {
233
+ constructor(message) {
234
+ super(message);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * This Selector subclass is a list of selectors. It matches a node if any of
240
+ * the selectors on the list matches the node. It considers the selectors in
241
+ * order, and returns the array of nodes returned by whichever one matches
242
+ * first.
243
+ */
244
+ class SelectorList extends Selector {
245
+ constructor(selectors) {
246
+ super();
247
+ _defineProperty(this, "selectors", void 0);
248
+ this.selectors = selectors;
249
+ }
250
+ match(state) {
251
+ for (let i = 0; i < this.selectors.length; i++) {
252
+ const s = this.selectors[i];
253
+ const result = s.match(state);
254
+ if (result) {
255
+ return result;
256
+ }
257
+ }
258
+ return null;
259
+ }
260
+ toString() {
261
+ let result = "";
262
+ for (let i = 0; i < this.selectors.length; i++) {
263
+ result += i > 0 ? ", " : "";
264
+ result += this.selectors[i].toString();
265
+ }
266
+ return result;
267
+ }
268
+ }
269
+
270
+ /**
271
+ * This trivial Selector subclass implements the '*' wildcard and
272
+ * matches any node.
273
+ */
274
+ class AnyNode extends Selector {
275
+ match(state) {
276
+ return [state.currentNode()];
277
+ }
278
+ toString() {
279
+ return "*";
280
+ }
281
+ }
282
+
283
+ /**
284
+ * This selector subclass implements the <IDENTIFIER> part of the grammar.
285
+ * it matches any node whose `type` property is a specified string
286
+ */
287
+ class TypeSelector extends Selector {
288
+ constructor(type) {
289
+ super();
290
+ _defineProperty(this, "type", void 0);
291
+ this.type = type;
292
+ }
293
+ match(state) {
294
+ const node = state.currentNode();
295
+ if (node.type === this.type) {
296
+ return [node];
297
+ }
298
+ return null;
299
+ }
300
+ toString() {
301
+ return this.type;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * This selector subclass is the superclass of the classes that implement
307
+ * matching for the four combinators. It defines left and right properties for
308
+ * the two selectors that are to be combined, but does not define a match
309
+ * method.
310
+ */
311
+ class SelectorCombinator extends Selector {
312
+ constructor(left, right) {
313
+ super();
314
+ _defineProperty(this, "left", void 0);
315
+ _defineProperty(this, "right", void 0);
316
+ this.left = left;
317
+ this.right = right;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * This Selector subclass implements the space combinator. It matches if the
323
+ * right selector matches the current node and the left selector matches some
324
+ * ancestor of the current node.
325
+ */
326
+ class AncestorCombinator extends SelectorCombinator {
327
+ constructor(left, right) {
328
+ super(left, right);
329
+ }
330
+ match(state) {
331
+ const rightResult = this.right.match(state);
332
+ if (rightResult) {
333
+ state = state.clone();
334
+ while (state.hasParent()) {
335
+ state.goToParent();
336
+ const leftResult = this.left.match(state);
337
+ if (leftResult) {
338
+ return leftResult.concat(rightResult);
339
+ }
340
+ }
341
+ }
342
+ return null;
343
+ }
344
+ toString() {
345
+ return this.left.toString() + " " + this.right.toString();
346
+ }
347
+ }
348
+
349
+ /**
350
+ * This Selector subclass implements the > combinator. It matches if the
351
+ * right selector matches the current node and the left selector matches
352
+ * the parent of the current node.
353
+ */
354
+ class ParentCombinator extends SelectorCombinator {
355
+ constructor(left, right) {
356
+ super(left, right);
357
+ }
358
+ match(state) {
359
+ const rightResult = this.right.match(state);
360
+ if (rightResult) {
361
+ if (state.hasParent()) {
362
+ state = state.clone();
363
+ state.goToParent();
364
+ const leftResult = this.left.match(state);
365
+ if (leftResult) {
366
+ return leftResult.concat(rightResult);
367
+ }
368
+ }
369
+ }
370
+ return null;
371
+ }
372
+ toString() {
373
+ return this.left.toString() + " > " + this.right.toString();
374
+ }
375
+ }
376
+
377
+ /**
378
+ * This Selector subclass implements the + combinator. It matches if the
379
+ * right selector matches the current node and the left selector matches
380
+ * the immediate previous sibling of the current node.
381
+ */
382
+ class PreviousCombinator extends SelectorCombinator {
383
+ constructor(left, right) {
384
+ super(left, right);
385
+ }
386
+ match(state) {
387
+ const rightResult = this.right.match(state);
388
+ if (rightResult) {
389
+ if (state.hasPreviousSibling()) {
390
+ state = state.clone();
391
+ state.goToPreviousSibling();
392
+ const leftResult = this.left.match(state);
393
+ if (leftResult) {
394
+ return leftResult.concat(rightResult);
395
+ }
396
+ }
397
+ }
398
+ return null;
399
+ }
400
+ toString() {
401
+ return this.left.toString() + " + " + this.right.toString();
402
+ }
403
+ }
404
+
405
+ /**
406
+ * This Selector subclass implements the ~ combinator. It matches if the
407
+ * right selector matches the current node and the left selector matches
408
+ * any previous sibling of the current node.
409
+ */
410
+ class SiblingCombinator extends SelectorCombinator {
411
+ constructor(left, right) {
412
+ super(left, right);
413
+ }
414
+ match(state) {
415
+ const rightResult = this.right.match(state);
416
+ if (rightResult) {
417
+ state = state.clone();
418
+ while (state.hasPreviousSibling()) {
419
+ state.goToPreviousSibling();
420
+ const leftResult = this.left.match(state);
421
+ if (leftResult) {
422
+ return leftResult.concat(rightResult);
423
+ }
424
+ }
425
+ }
426
+ return null;
427
+ }
428
+ toString() {
429
+ return this.left.toString() + " ~ " + this.right.toString();
430
+ }
431
+ }
432
+
433
+ /**
434
+ * A Rule object describes a Perseus lint rule. See the comment at the top of
435
+ * this file for detailed description.
436
+ */
437
+ class Rule {
438
+ // The name of the rule
439
+ // The severity of the rule
440
+ // The specified selector or the DEFAULT_SELECTOR
441
+ // A regular expression if one was specified
442
+ // The lint-testing function or a default
443
+ // Checks to see if we should apply a rule or not
444
+ // The error message for use with the default function
445
+
446
+ // The comment at the top of this file has detailed docs for
447
+ // this constructor and its arguments
448
+ constructor(name, severity, selector, pattern, lint, applies) {
449
+ var _this = this;
450
+ _defineProperty(this, "name", void 0);
451
+ _defineProperty(this, "severity", void 0);
452
+ _defineProperty(this, "selector", void 0);
453
+ _defineProperty(this, "pattern", void 0);
454
+ _defineProperty(this, "lint", void 0);
455
+ _defineProperty(this, "applies", void 0);
456
+ _defineProperty(this, "message", void 0);
457
+ if (!selector && !pattern) {
458
+ throw new perseusError.PerseusError("Lint rules must have a selector or pattern", perseusError.Errors.InvalidInput, {
459
+ metadata: {
460
+ name
461
+ }
462
+ });
463
+ }
464
+ this.name = name || "unnamed rule";
465
+ this.severity = severity || Rule.Severity.BULK_WARNING;
466
+ this.selector = selector || Rule.DEFAULT_SELECTOR;
467
+ this.pattern = pattern || null;
468
+
469
+ // If we're called with an error message instead of a function then
470
+ // use a default function that will return the message.
471
+ if (typeof lint === "function") {
472
+ this.lint = lint;
473
+ this.message = null;
474
+ } else {
475
+ this.lint = function () {
476
+ return _this._defaultLintFunction(...arguments);
477
+ };
478
+ this.message = lint;
479
+ }
480
+ this.applies = applies || function () {
481
+ return true;
482
+ };
483
+ }
484
+
485
+ // A factory method for use with rules described in JSON files
486
+ // See the documentation at the start of this file for details.
487
+ static makeRule(options) {
488
+ return new Rule(options.name, options.severity, options.selector ? Selector.parse(options.selector) : null, Rule.makePattern(options.pattern), options.lint || options.message, options.applies);
489
+ }
490
+
491
+ // Check the node n to see if it violates this lint rule. A return value
492
+ // of false means there is no lint. A returned object indicates a lint
493
+ // error. See the documentation at the top of this file for details.
494
+ check(node, traversalState, content, context) {
495
+ // First, see if we match the selector.
496
+ // If no selector was passed to the constructor, we use a
497
+ // default selector that matches text nodes.
498
+ const selectorMatch = this.selector.match(traversalState);
499
+
500
+ // If the selector did not match, then we're done
501
+ if (!selectorMatch) {
502
+ return null;
503
+ }
504
+
505
+ // If the selector matched, then see if the pattern matches
506
+ let patternMatch;
507
+ if (this.pattern) {
508
+ patternMatch = content.match(this.pattern);
509
+ } else {
510
+ // If there is no pattern, then just match all of the content.
511
+ // Use a fake RegExp match object to represent this default match.
512
+ patternMatch = Rule.FakePatternMatch(content, content, 0);
513
+ }
514
+
515
+ // If there was a pattern and it didn't match, then we're done
516
+ if (!patternMatch) {
517
+ return null;
518
+ }
519
+ try {
520
+ // If we get here, then the selector and pattern have matched
521
+ // so now we call the lint function to see if there is lint.
522
+ const error = this.lint(traversalState, content, selectorMatch, patternMatch, context);
523
+ if (!error) {
524
+ return null; // No lint; we're done
525
+ }
526
+
527
+ if (typeof error === "string") {
528
+ // If the lint function returned a string we assume it
529
+ // applies to the entire content of the node and return it.
530
+ return {
531
+ rule: this.name,
532
+ severity: this.severity,
533
+ message: error,
534
+ start: 0,
535
+ end: content.length
536
+ };
537
+ }
538
+ // If the lint function returned an object, then we just
539
+ // add the rule name to the message, start and end.
540
+ return {
541
+ rule: this.name,
542
+ severity: this.severity,
543
+ message: error.message,
544
+ start: error.start,
545
+ end: error.end
546
+ };
547
+ } catch (e) {
548
+ // If the lint function threw an exception we handle that as
549
+ // a special type of lint. We want the user to see the lint
550
+ // warning in this case (even though it is out of their control)
551
+ // so that the bug gets reported. Otherwise we'd never know that
552
+ // a rule was failing.
553
+ return {
554
+ rule: "lint-rule-failure",
555
+ message: "Exception in rule ".concat(this.name, ": ").concat(e.message, "\nStack trace:\n").concat(e.stack),
556
+ start: 0,
557
+ end: content.length
558
+ };
559
+ }
560
+ }
561
+
562
+ // This internal method is the default lint function that we use when a
563
+ // rule is defined without a function. This is useful for rules where the
564
+ // selector and/or pattern match are enough to indicate lint. This
565
+ // function unconditionally returns the error message that was passed in
566
+ // place of a function, but also adds start and end properties that
567
+ // specify which particular portion of the node content matched the
568
+ // pattern.
569
+ _defaultLintFunction(state, content, selectorMatch, patternMatch, context) {
570
+ return {
571
+ message: this.message || "",
572
+ start: patternMatch.index,
573
+ end: patternMatch.index + patternMatch[0].length
574
+ };
575
+ }
576
+
577
+ // The makeRule() factory function uses this static method to turn its
578
+ // argument into a RegExp. If the argument is already a RegExp, we just
579
+ // return it. Otherwise, we compile it into a RegExp and return that.
580
+ // The reason this is necessary is that Rule.makeRule() is designed for
581
+ // use with data from JSON files and JSON files can't include RegExp
582
+ // literals. Strings passed to this function do not need to be delimited
583
+ // with / characters unless you want to include flags for the RegExp.
584
+ //
585
+ // Examples:
586
+ //
587
+ // input "" ==> output null
588
+ // input /foo/ ==> output /foo/
589
+ // input "foo" ==> output /foo/
590
+ // input "/foo/i" ==> output /foo/i
591
+ //
592
+ static makePattern(pattern) {
593
+ if (!pattern) {
594
+ return null;
595
+ }
596
+ if (pattern instanceof RegExp) {
597
+ return pattern;
598
+ }
599
+ if (pattern[0] === "/") {
600
+ const lastSlash = pattern.lastIndexOf("/");
601
+ const expression = pattern.substring(1, lastSlash);
602
+ const flags = pattern.substring(lastSlash + 1);
603
+ // @ts-expect-error [FEI-5003] - TS2713 - Cannot access 'RegExp.flags' because 'RegExp' is a type, but not a namespace. Did you mean to retrieve the type of the property 'flags' in 'RegExp' with 'RegExp["flags"]'?
604
+ return new RegExp(expression, flags);
605
+ }
606
+ return new RegExp(pattern);
607
+ }
608
+
609
+ // This static method returns an string array with index and input
610
+ // properties added, in order to simulate the return value of the
611
+ // String.match() method. We use it when a Rule has no pattern and we
612
+ // want to simulate a match on the entire content string.
613
+ static FakePatternMatch(input, match, index) {
614
+ const result = [match];
615
+ result.index = index;
616
+ result.input = input;
617
+ return result;
618
+ }
619
+ }
620
+ _defineProperty(Rule, "DEFAULT_SELECTOR", void 0);
621
+ _defineProperty(Rule, "Severity", {
622
+ ERROR: 1,
623
+ WARNING: 2,
624
+ GUIDELINE: 3,
625
+ BULK_WARNING: 4
626
+ });
627
+ Rule.DEFAULT_SELECTOR = Selector.parse("text");
628
+
629
+ /* eslint-disable no-useless-escape */
630
+ // Return the portion of a URL between // and /. This is the authority
631
+ // portion which is usually just the hostname, but may also include
632
+ // a username, password or port. We don't strip those things out because
633
+ // we typically want to reject any URL that includes them
634
+ const HOSTNAME = /\/\/([^\/]+)/;
635
+
636
+ // Return the hostname of the URL, with any "www." prefix removed.
637
+ // If this is a relative URL with no hostname, return an empty string.
638
+ function getHostname(url) {
639
+ if (!url) {
640
+ return "";
641
+ }
642
+ const match = url.match(HOSTNAME);
643
+ return match ? match[1] : "";
644
+ }
645
+
646
+ var AbsoluteUrl = Rule.makeRule({
647
+ name: "absolute-url",
648
+ severity: Rule.Severity.GUIDELINE,
649
+ selector: "link, image",
650
+ lint: function (state, content, nodes, match) {
651
+ const url = nodes[0].target;
652
+ const hostname = getHostname(url);
653
+ if (hostname === "khanacademy.org" || hostname.endsWith(".khanacademy.org")) {
654
+ return "Don't use absolute URLs:\nWhen linking to KA content or images, omit the\nhttps://www.khanacademy.org URL prefix.\nUse a relative URL beginning with / instead.";
655
+ }
656
+ }
657
+ });
658
+
659
+ var BlockquotedMath = Rule.makeRule({
660
+ name: "blockquoted-math",
661
+ severity: Rule.Severity.WARNING,
662
+ selector: "blockQuote math, blockQuote blockMath",
663
+ message: "Blockquoted math:\nmath should not be indented."
664
+ });
665
+
666
+ var BlockquotedWidget = Rule.makeRule({
667
+ name: "blockquoted-widget",
668
+ severity: Rule.Severity.WARNING,
669
+ selector: "blockQuote widget",
670
+ message: "Blockquoted widget:\nwidgets should not be indented."
671
+ });
672
+
673
+ /* eslint-disable no-useless-escape */
674
+ var DoubleSpacingAfterTerminal = Rule.makeRule({
675
+ name: "double-spacing-after-terminal",
676
+ severity: Rule.Severity.BULK_WARNING,
677
+ selector: "paragraph",
678
+ pattern: /[.!\?] {2}/i,
679
+ message: "Use a single space after a sentence-ending period, or\nany other kind of terminal punctuation."
680
+ });
681
+
682
+ var ExtraContentSpacing = Rule.makeRule({
683
+ name: "extra-content-spacing",
684
+ selector: "paragraph",
685
+ pattern: /\s+$/,
686
+ applies: function (context) {
687
+ return context.contentType === "article";
688
+ },
689
+ message: "No extra whitespace at the end of content blocks."
690
+ });
691
+
692
+ var HeadingLevel1 = Rule.makeRule({
693
+ name: "heading-level-1",
694
+ severity: Rule.Severity.WARNING,
695
+ selector: "heading",
696
+ lint: function (state, content, nodes, match) {
697
+ if (nodes[0].level === 1) {
698
+ return "Don't use level-1 headings:\nBegin headings with two or more # characters.";
699
+ }
700
+ }
701
+ });
702
+
703
+ var HeadingLevelSkip = Rule.makeRule({
704
+ name: "heading-level-skip",
705
+ severity: Rule.Severity.WARNING,
706
+ selector: "heading ~ heading",
707
+ lint: function (state, content, nodes, match) {
708
+ const currentHeading = nodes[1];
709
+ const previousHeading = nodes[0];
710
+ // A heading can have a level less than, the same as
711
+ // or one more than the previous heading. But going up
712
+ // by 2 or more levels is not right
713
+ if (currentHeading.level > previousHeading.level + 1) {
714
+ return "Skipped heading level:\nthis heading is level ".concat(currentHeading.level, " but\nthe previous heading was level ").concat(previousHeading.level);
715
+ }
716
+ }
717
+ });
718
+
719
+ var HeadingSentenceCase = Rule.makeRule({
720
+ name: "heading-sentence-case",
721
+ severity: Rule.Severity.GUIDELINE,
722
+ selector: "heading",
723
+ pattern: /^\W*[a-z]/,
724
+ // first letter is lowercase
725
+ message: "First letter is lowercase:\nthe first letter of a heading should be capitalized."
726
+ });
727
+
728
+ // These are 3-letter and longer words that we would not expect to be
729
+ // capitalized even in a title-case heading. See
730
+ // http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html
731
+ const littleWords = {
732
+ and: true,
733
+ nor: true,
734
+ but: true,
735
+ the: true,
736
+ for: true
737
+ };
738
+ function isCapitalized(word) {
739
+ const c = word[0];
740
+ return c === c.toUpperCase();
741
+ }
742
+ var HeadingTitleCase = Rule.makeRule({
743
+ name: "heading-title-case",
744
+ severity: Rule.Severity.GUIDELINE,
745
+ selector: "heading",
746
+ pattern: /[^\s:]\s+[A-Z]+[a-z]/,
747
+ locale: "en",
748
+ lint: function (state, content, nodes, match) {
749
+ // We want to assert that heading text is in sentence case, not
750
+ // title case. The pattern above requires a capital letter at the
751
+ // start of the heading and allows them after a colon, or in
752
+ // acronyms that are all capitalized.
753
+ //
754
+ // But we can't warn just because the pattern matched because
755
+ // proper nouns are also allowed bo be capitalized. We're not
756
+ // going to do dictionary lookup to check for proper nouns, so
757
+ // we try a heuristic: if the title is more than 3 words long
758
+ // and if all the words are capitalized or are on the list of
759
+ // words that don't get capitalized, then we'll assume that
760
+ // the heading is incorrectly in title case and will warn.
761
+ // But if there is at least one non-capitalized long word then
762
+ // we're not in title case and we should not warn.
763
+ //
764
+ // TODO(davidflanagan): if this rule causes a lot of false
765
+ // positives, we should tweak it or remove it. Note that it will
766
+ // fail for headings like "World War II in Russia"
767
+ //
768
+ // TODO(davidflanagan): This rule is specific to English.
769
+ // It is marked with a locale property above, but that is NYI
770
+ //
771
+ // for APA style rules for title case
772
+
773
+ const heading = content.trim();
774
+ let words = heading.split(/\s+/);
775
+
776
+ // Remove the first word and the little words
777
+ words.shift();
778
+ words = words.filter(
779
+ // eslint-disable-next-line no-prototype-builtins
780
+ w => w.length > 2 && !littleWords.hasOwnProperty(w));
781
+
782
+ // If there are at least 3 remaining words and all
783
+ // are capitalized, then the heading is in title case.
784
+ if (words.length >= 3 && words.every(w => isCapitalized(w))) {
785
+ return "Title-case heading:\nThis heading appears to be in title-case, but should be sentence-case.\nOnly capitalize the first letter and proper nouns.";
786
+ }
787
+ }
788
+ });
789
+
790
+ var ImageAltText = Rule.makeRule({
791
+ name: "image-alt-text",
792
+ severity: Rule.Severity.WARNING,
793
+ selector: "image",
794
+ lint: function (state, content, nodes, match) {
795
+ const image = nodes[0];
796
+ if (!image.alt || !image.alt.trim()) {
797
+ return "Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.";
798
+ }
799
+ if (image.alt.length < 8) {
800
+ return "Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ".concat(image.alt.length, " characters long.");
801
+ }
802
+ }
803
+ });
804
+
805
+ var ImageInTable = Rule.makeRule({
806
+ name: "image-in-table",
807
+ severity: Rule.Severity.BULK_WARNING,
808
+ selector: "table image",
809
+ message: "Image in table:\ndo not put images inside of tables."
810
+ });
811
+
812
+ var ImageSpacesAroundUrls = Rule.makeRule({
813
+ name: "image-spaces-around-urls",
814
+ severity: Rule.Severity.ERROR,
815
+ selector: "image",
816
+ lint: function (state, content, nodes, match, context) {
817
+ const image = nodes[0];
818
+ const url = image.target;
819
+
820
+ // The markdown parser strips leading and trailing spaces for us,
821
+ // but they're still a problem for our translation process, so
822
+ // we need to go check for them in the unparsed source string
823
+ // if we have it.
824
+ if (context && context.content) {
825
+ // Find the url in the original content and make sure that the
826
+ // character before is '(' and the character after is ')'
827
+ const index = context.content.indexOf(url);
828
+ if (index === -1) {
829
+ // It is not an error if we didn't find it.
830
+ return;
831
+ }
832
+ if (context.content[index - 1] !== "(" || context.content[index + url.length] !== ")") {
833
+ return "Whitespace before or after image url:\nFor images, don't include any space or newlines after '(' or before ')'.\nWhitespace in image URLs causes translation difficulties.";
834
+ }
835
+ }
836
+ }
837
+ });
838
+
839
+ // Normally we have one rule per file. But since our selector class
840
+ // can't match specific widget types directly, this rule implements
841
+ // a number of image widget related rules in one place. This should
842
+ // slightly increase efficiency, but it means that if there is more
843
+ // than one problem with an image widget, the user will only see one
844
+ // problem at a time.
845
+ var ImageWidget = Rule.makeRule({
846
+ name: "image-widget",
847
+ severity: Rule.Severity.WARNING,
848
+ selector: "widget",
849
+ lint: function (state, content, nodes, match, context) {
850
+ // This rule only looks at image widgets
851
+ if (state.currentNode().widgetType !== "image") {
852
+ return;
853
+ }
854
+
855
+ // If it can't find a definition for the widget it does nothing
856
+ const widget = context && context.widgets && context.widgets[state.currentNode().id];
857
+ if (!widget) {
858
+ return;
859
+ }
860
+
861
+ // Make sure there is alt text
862
+ const alt = widget.options.alt;
863
+ if (!alt) {
864
+ return "Images should have alt text:\nfor accessibility, all images should have a text description.\nAdd a description in the \"Alt Text\" box of the image widget.";
865
+ }
866
+
867
+ // Make sure the alt text it is not trivial
868
+ if (alt.trim().length < 8) {
869
+ return "Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ".concat(alt.trim().length, " characters long.");
870
+ }
871
+
872
+ // Make sure there is no math in the caption
873
+ if (widget.options.caption && widget.options.caption.match(/[^\\]\$/)) {
874
+ return "No math in image captions:\nDon't include math expressions in image captions.";
875
+ }
876
+ }
877
+ });
878
+
879
+ var LinkClickHere = Rule.makeRule({
880
+ name: "link-click-here",
881
+ severity: Rule.Severity.WARNING,
882
+ selector: "link",
883
+ pattern: /click here/i,
884
+ message: "Inappropriate link text:\nDo not use the words \"click here\" in links."
885
+ });
886
+
887
+ var LongParagraph = Rule.makeRule({
888
+ name: "long-paragraph",
889
+ severity: Rule.Severity.GUIDELINE,
890
+ selector: "paragraph",
891
+ pattern: /^.{501,}/,
892
+ lint: function (state, content, nodes, match) {
893
+ return "Paragraph too long:\nThis paragraph is ".concat(content.length, " characters long.\nShorten it to 500 characters or fewer.");
894
+ }
895
+ });
896
+
897
+ var MathAdjacent = Rule.makeRule({
898
+ name: "math-adjacent",
899
+ severity: Rule.Severity.WARNING,
900
+ selector: "blockMath+blockMath",
901
+ message: "Adjacent math blocks:\ncombine the blocks between \\begin{align} and \\end{align}"
902
+ });
903
+
904
+ var MathAlignExtraBreak = Rule.makeRule({
905
+ name: "math-align-extra-break",
906
+ severity: Rule.Severity.WARNING,
907
+ selector: "blockMath",
908
+ pattern: /(\\{2,})\s*\\end{align}/,
909
+ message: "Extra space at end of block:\nDon't end an align block with backslashes"
910
+ });
911
+
912
+ var MathAlignLinebreaks = Rule.makeRule({
913
+ name: "math-align-linebreaks",
914
+ severity: Rule.Severity.WARNING,
915
+ selector: "blockMath",
916
+ // Match any align block with double backslashes in it
917
+ // Use [\s\S]* instead of .* so we match newlines as well.
918
+ pattern: /\\begin{align}[\s\S]*\\\\[\s\S]+\\end{align}/,
919
+ // Look for double backslashes and ensure that they are
920
+ // followed by optional space and another pair of backslashes.
921
+ // Note that this rule can't know where line breaks belong so
922
+ // it can't tell whether backslashes are completely missing. It just
923
+ // enforces that you don't have the wrong number of pairs of backslashes.
924
+ lint: function (state, content, nodes, match) {
925
+ let text = match[0];
926
+ while (text.length) {
927
+ const index = text.indexOf("\\\\");
928
+ if (index === -1) {
929
+ // No more backslash pairs, so we found no lint
930
+ return null;
931
+ }
932
+ text = text.substring(index + 2);
933
+
934
+ // Now we expect to find optional spaces, another pair of
935
+ // backslashes, and more optional spaces not followed immediately
936
+ // by another pair of backslashes.
937
+ const nextpair = text.match(/^\s*\\\\\s*(?!\\\\)/);
938
+
939
+ // If that does not match then we either have too few or too
940
+ // many pairs of backslashes.
941
+ if (!nextpair) {
942
+ return "Use four backslashes between lines of an align block";
943
+ }
944
+
945
+ // If it did match, then, shorten the string and continue looping
946
+ // (because a single align block may have multiple lines that
947
+ // all must be separated by two sets of double backslashes).
948
+ text = text.substring(nextpair[0].length);
949
+ }
950
+ }
951
+ });
952
+
953
+ var MathEmpty = Rule.makeRule({
954
+ name: "math-empty",
955
+ severity: Rule.Severity.WARNING,
956
+ selector: "math, blockMath",
957
+ pattern: /^$/,
958
+ message: "Empty math: don't use $$ in your markdown."
959
+ });
960
+
961
+ var MathFontSize = Rule.makeRule({
962
+ name: "math-font-size",
963
+ severity: Rule.Severity.GUIDELINE,
964
+ selector: "math, blockMath",
965
+ pattern: /\\(tiny|Tiny|small|large|Large|LARGE|huge|Huge|scriptsize|normalsize)\s*{/,
966
+ message: "Math font size:\nDon't change the default font size with \\Large{} or similar commands"
967
+ });
968
+
969
+ var MathFrac = Rule.makeRule({
970
+ name: "math-frac",
971
+ severity: Rule.Severity.GUIDELINE,
972
+ selector: "math, blockMath",
973
+ pattern: /\\frac[ {]/,
974
+ message: "Use \\dfrac instead of \\frac in your math expressions."
975
+ });
976
+
977
+ var MathNested = Rule.makeRule({
978
+ name: "math-nested",
979
+ severity: Rule.Severity.ERROR,
980
+ selector: "math, blockMath",
981
+ pattern: /\\text{[^$}]*\$[^$}]*\$[^}]*}/,
982
+ message: "Nested math:\nDon't nest math expressions inside \\text{} blocks"
983
+ });
984
+
985
+ var MathStartsWithSpace = Rule.makeRule({
986
+ name: "math-starts-with-space",
987
+ severity: Rule.Severity.GUIDELINE,
988
+ selector: "math, blockMath",
989
+ pattern: /^\s*(~|\\qquad|\\quad|\\,|\\;|\\:|\\ |\\!|\\enspace|\\phantom)/,
990
+ message: "Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\;, \\quad, or \\phantom"
991
+ });
992
+
993
+ var MathTextEmpty = Rule.makeRule({
994
+ name: "math-text-empty",
995
+ severity: Rule.Severity.WARNING,
996
+ selector: "math, blockMath",
997
+ pattern: /\\text{\s*}/,
998
+ message: "Empty \\text{} block in math expression"
999
+ });
1000
+
1001
+ // Because no selector is specified, this rule only applies to text nodes.
1002
+ // Math and code hold their content directly and do not have text nodes
1003
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1004
+ // apply inside $$ or ``.
1005
+ var MathWithoutDollars = Rule.makeRule({
1006
+ name: "math-without-dollars",
1007
+ severity: Rule.Severity.GUIDELINE,
1008
+ pattern: /\\\w+{[^}]*}|{|}/,
1009
+ message: "This looks like LaTeX:\ndid you mean to put it inside dollar signs?"
1010
+ });
1011
+
1012
+ var NestedLists = Rule.makeRule({
1013
+ name: "nested-lists",
1014
+ severity: Rule.Severity.WARNING,
1015
+ selector: "list list",
1016
+ message: "Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation."
1017
+ });
1018
+
1019
+ var Profanity = Rule.makeRule({
1020
+ name: "profanity",
1021
+ // This list could obviously be expanded a lot, but I figured we
1022
+ // could start with https://en.wikipedia.org/wiki/Seven_dirty_words
1023
+ pattern: /\b(shit|piss|fuck|cunt|cocksucker|motherfucker|tits)\b/i,
1024
+ message: "Avoid profanity"
1025
+ });
1026
+
1027
+ var TableMissingCells = Rule.makeRule({
1028
+ name: "table-missing-cells",
1029
+ severity: Rule.Severity.WARNING,
1030
+ selector: "table",
1031
+ lint: function (state, content, nodes, match) {
1032
+ const table = nodes[0];
1033
+ const headerLength = table.header.length;
1034
+ const rowLengths = table.cells.map(r => r.length);
1035
+ for (let r = 0; r < rowLengths.length; r++) {
1036
+ if (rowLengths[r] !== headerLength) {
1037
+ return "Table rows don't match header:\nThe table header has ".concat(headerLength, " cells, but\nRow ").concat(r + 1, " has ").concat(rowLengths[r], " cells.");
1038
+ }
1039
+ }
1040
+ }
1041
+ });
1042
+
1043
+ // Because no selector is specified, this rule only applies to text nodes.
1044
+ // Math and code hold their content directly and do not have text nodes
1045
+ // beneath them (unlike the HTML DOM) so this rule automatically does not
1046
+ // apply inside $$ or ``.
1047
+ var UnbalancedCodeDelimiters = Rule.makeRule({
1048
+ name: "unbalanced-code-delimiters",
1049
+ severity: Rule.Severity.ERROR,
1050
+ pattern: /[`~]+/,
1051
+ message: "Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters"
1052
+ });
1053
+
1054
+ var UnescapedDollar = Rule.makeRule({
1055
+ name: "unescaped-dollar",
1056
+ severity: Rule.Severity.ERROR,
1057
+ selector: "unescapedDollar",
1058
+ message: "Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\$"
1059
+ });
1060
+
1061
+ var WidgetInTable = Rule.makeRule({
1062
+ name: "widget-in-table",
1063
+ severity: Rule.Severity.BULK_WARNING,
1064
+ selector: "table widget",
1065
+ message: "Widget in table:\ndo not put widgets inside of tables."
1066
+ });
1067
+
1068
+ // TODO(davidflanagan):
1069
+ var AllRules = [AbsoluteUrl, BlockquotedMath, BlockquotedWidget, DoubleSpacingAfterTerminal, ExtraContentSpacing, HeadingLevel1, HeadingLevelSkip, HeadingSentenceCase, HeadingTitleCase, ImageAltText, ImageInTable, LinkClickHere, LongParagraph, MathAdjacent, MathAlignExtraBreak, MathAlignLinebreaks, MathEmpty, MathFontSize, MathFrac, MathNested, MathStartsWithSpace, MathTextEmpty, NestedLists, TableMissingCells, UnescapedDollar, WidgetInTable, Profanity, MathWithoutDollars, UnbalancedCodeDelimiters, ImageSpacesAroundUrls, ImageWidget];
1070
+
1071
+ // TreeNode is the type of a node in a parse tree. The only real requirement is
1072
+ // that every node has a string-valued `type` property
1073
+
1074
+ // This is the TreeTransformer class described in detail at the
1075
+ // top of this file.
1076
+ class TreeTransformer {
1077
+ // To create a tree transformer, just pass the root node of the tree
1078
+ constructor(root) {
1079
+ _defineProperty(this, "root", void 0);
1080
+ this.root = root;
1081
+ }
1082
+
1083
+ // A utility function for determing whether an arbitrary value is a node
1084
+ static isNode(n) {
1085
+ return n && typeof n === "object" && typeof n.type === "string";
1086
+ }
1087
+
1088
+ // Determines whether a value is a node with type "text" and has
1089
+ // a text-valued `content` property.
1090
+ static isTextNode(n) {
1091
+ return TreeTransformer.isNode(n) && n.type === "text" && typeof n.content === "string";
1092
+ }
1093
+
1094
+ // This is the main entry point for the traverse() method. See the comment
1095
+ // at the top of this file for a detailed description. Note that this
1096
+ // method just creates a new TraversalState object to use for this
1097
+ // traversal and then invokes the internal _traverse() method to begin the
1098
+ // recursion.
1099
+ traverse(f) {
1100
+ this._traverse(this.root, new TraversalState(this.root), f);
1101
+ }
1102
+
1103
+ // Do a post-order traversal of node and its descendants, invoking the
1104
+ // callback function f() once for each node and returning the concatenated
1105
+ // text content of the node and its descendants. f() is passed three
1106
+ // arguments: the current node, a TraversalState object representing the
1107
+ // current state of the traversal, and a string that holds the
1108
+ // concatenated text of the node and its descendants.
1109
+ //
1110
+ // This private method holds all the traversal logic and implementation
1111
+ // details. Note that this method uses the TraversalState object to store
1112
+ // information about the structure of the tree.
1113
+ _traverse(n, state, f) {
1114
+ let content = "";
1115
+ if (TreeTransformer.isNode(n)) {
1116
+ // If we were called on a node object, then we handle it
1117
+ // this way.
1118
+ const node = n; // safe cast; we just tested
1119
+
1120
+ // Put the node on the stack before recursing on its children
1121
+ state._containers.push(node);
1122
+ state._ancestors.push(node);
1123
+
1124
+ // Record the node's text content if it has any.
1125
+ // Usually this is for nodes with a type property of "text",
1126
+ // but other nodes types like "math" may also have content.
1127
+ // TODO(mdr): We found a new Flow error when upgrading:
1128
+ // "node.content (property `content` is missing in `TreeNode` [1].)"
1129
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1130
+ if (typeof node.content === "string") {
1131
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1132
+ content = node.content;
1133
+ }
1134
+
1135
+ // Recurse on the node. If there was content above, then there
1136
+ // probably won't be any children to recurse on, but we check
1137
+ // anyway.
1138
+ //
1139
+ // If we wanted to make the traversal completely specific to the
1140
+ // actual Perseus parse trees that we'll be dealing with we could
1141
+ // put a switch statement here to dispatch on the node type
1142
+ // property with specific recursion steps for each known type of
1143
+ // node.
1144
+ const keys = Object.keys(node);
1145
+ keys.forEach(key => {
1146
+ // Never recurse on the type property
1147
+ if (key === "type") {
1148
+ return;
1149
+ }
1150
+ // Ignore properties that are null or primitive and only
1151
+ // recurse on objects and arrays. Note that we don't do a
1152
+ // isNode() check here. That is done in the recursive call to
1153
+ // _traverse(). Note that the recursive call on each child
1154
+ // returns the text content of the child and we add that
1155
+ // content to the content for this node. Also note that we
1156
+ // push the name of the property we're recursing over onto a
1157
+ // TraversalState stack.
1158
+ const value = node[key];
1159
+ if (value && typeof value === "object") {
1160
+ state._indexes.push(key);
1161
+ content += this._traverse(value, state, f);
1162
+ state._indexes.pop();
1163
+ }
1164
+ });
1165
+
1166
+ // Restore the stacks after recursing on the children
1167
+ state._currentNode = state._ancestors.pop();
1168
+ state._containers.pop();
1169
+
1170
+ // And finally call the traversal callback for this node. Note
1171
+ // that this is post-order traversal. We call the callback on the
1172
+ // way back up the tree, not on the way down. That way we already
1173
+ // know all the content contained within the node.
1174
+ f(node, state, content);
1175
+ } else if (Array.isArray(n)) {
1176
+ // If we were called on an array instead of a node, then
1177
+ // this is the code we use to recurse.
1178
+ const nodes = n;
1179
+
1180
+ // Push the array onto the stack. This will allow the
1181
+ // TraversalState object to locate siblings of this node.
1182
+ state._containers.push(nodes);
1183
+
1184
+ // Now loop through this array and recurse on each element in it.
1185
+ // Before recursing on an element, we push its array index on a
1186
+ // TraversalState stack so that the TraversalState sibling methods
1187
+ // can work. Note that TraversalState methods can alter the length
1188
+ // of the array, and change the index of the current node, so we
1189
+ // are careful here to test the array length on each iteration and
1190
+ // to reset the index when we pop the stack. Also note that we
1191
+ // concatentate the text content of the children.
1192
+ let index = 0;
1193
+ while (index < nodes.length) {
1194
+ state._indexes.push(index);
1195
+ content += this._traverse(nodes[index], state, f);
1196
+ // Casting to convince Flow that this is a number
1197
+ index = state._indexes.pop() + 1;
1198
+ }
1199
+
1200
+ // Pop the array off the stack. Note, however, that we do not call
1201
+ // the traversal callback on the array. That function is only
1202
+ // called for nodes, not arrays of nodes.
1203
+ state._containers.pop();
1204
+ }
1205
+
1206
+ // The _traverse() method always returns the text content of
1207
+ // this node and its children. This is the one piece of state that
1208
+ // is not tracked in the TraversalState object.
1209
+ return content;
1210
+ }
1211
+ }
1212
+
1213
+ // An instance of this class is passed to the callback function for
1214
+ // each node traversed. The class itself is not exported, but its
1215
+ // methods define the API available to the traversal callback.
1216
+
1217
+ /**
1218
+ * This class represents the state of a tree traversal. An instance is created
1219
+ * by the traverse() method of the TreeTransformer class to maintain the state
1220
+ * for that traversal, and the instance is passed to the traversal callback
1221
+ * function for each node that is traversed. This class is not intended to be
1222
+ * instantiated directly, but is exported so that its type can be used for
1223
+ * Flow annotaions.
1224
+ **/
1225
+ class TraversalState {
1226
+ // The root node of the tree being traversed
1227
+
1228
+ // These are internal state properties. Use the accessor methods defined
1229
+ // below instead of using these properties directly. Note that the
1230
+ // _containers and _indexes stacks can have two different types of
1231
+ // elements, depending on whether we just recursed on an array or on a
1232
+ // node. This is hard for Flow to deal with, so you'll see a number of
1233
+ // Flow casts through the any type when working with these two properties.
1234
+
1235
+ // The constructor just stores the root node and creates empty stacks.
1236
+ constructor(root) {
1237
+ _defineProperty(this, "root", void 0);
1238
+ _defineProperty(this, "_currentNode", void 0);
1239
+ _defineProperty(this, "_containers", void 0);
1240
+ _defineProperty(this, "_indexes", void 0);
1241
+ _defineProperty(this, "_ancestors", void 0);
1242
+ this.root = root;
1243
+
1244
+ // When the callback is called, this property will hold the
1245
+ // node that is currently being traversed.
1246
+ this._currentNode = null;
1247
+
1248
+ // This is a stack of the objects and arrays that we've
1249
+ // traversed through before reaching the currentNode.
1250
+ // It is different than the ancestors array.
1251
+ this._containers = new Stack();
1252
+
1253
+ // This stack has the same number of elements as the _containers
1254
+ // stack. The last element of this._indexes[] is the index of
1255
+ // the current node in the object or array that is the last element
1256
+ // of this._containers[]. If the last element of this._containers[] is
1257
+ // an array, then the last element of this stack will be a number.
1258
+ // Otherwise if the last container is an object, then the last index
1259
+ // will be a string property name.
1260
+ this._indexes = new Stack();
1261
+
1262
+ // This is a stack of the ancestor nodes of the current one.
1263
+ // It is different than the containers[] stack because it only
1264
+ // includes nodes, not arrays.
1265
+ this._ancestors = new Stack();
1266
+ }
1267
+
1268
+ /**
1269
+ * Return the current node in the traversal. Any time the traversal
1270
+ * callback is called, this method will return the name value as the
1271
+ * first argument to the callback.
1272
+ */
1273
+ currentNode() {
1274
+ return this._currentNode || this.root;
1275
+ }
1276
+
1277
+ /**
1278
+ * Return the parent of the current node, if there is one, or null.
1279
+ */
1280
+ parent() {
1281
+ return this._ancestors.top();
1282
+ }
1283
+
1284
+ /**
1285
+ * Return an array of ancestor nodes. The first element of this array is
1286
+ * the same as this.parent() and the last element is the root node. If we
1287
+ * are currently at the root node, the the returned array will be empty.
1288
+ * This method makes a copy of the internal state, so modifications to the
1289
+ * returned array have no effect on the traversal.
1290
+ */
1291
+ ancestors() {
1292
+ return this._ancestors.values();
1293
+ }
1294
+
1295
+ /**
1296
+ * Return the next sibling of this node, if it has one, or null otherwise.
1297
+ */
1298
+ nextSibling() {
1299
+ const siblings = this._containers.top();
1300
+
1301
+ // If we're at the root of the tree or if the parent is an
1302
+ // object instead of an array, then there are no siblings.
1303
+ if (!siblings || !Array.isArray(siblings)) {
1304
+ return null;
1305
+ }
1306
+
1307
+ // The top index is a number because the top container is an array
1308
+ const index = this._indexes.top();
1309
+ if (siblings.length > index + 1) {
1310
+ return siblings[index + 1];
1311
+ }
1312
+ return null; // There is no next sibling
1313
+ }
1314
+
1315
+ /**
1316
+ * Return the previous sibling of this node, if it has one, or null
1317
+ * otherwise.
1318
+ */
1319
+ previousSibling() {
1320
+ const siblings = this._containers.top();
1321
+
1322
+ // If we're at the root of the tree or if the parent is an
1323
+ // object instead of an array, then there are no siblings.
1324
+ if (!siblings || !Array.isArray(siblings)) {
1325
+ return null;
1326
+ }
1327
+
1328
+ // The top index is a number because the top container is an array
1329
+ const index = this._indexes.top();
1330
+ if (index > 0) {
1331
+ return siblings[index - 1];
1332
+ }
1333
+ return null; // There is no previous sibling
1334
+ }
1335
+
1336
+ /**
1337
+ * Remove the next sibling node (if there is one) from the tree. Returns
1338
+ * the removed sibling or null. This method makes it easy to traverse a
1339
+ * tree and concatenate adjacent text nodes into a single node.
1340
+ */
1341
+ removeNextSibling() {
1342
+ const siblings = this._containers.top();
1343
+ if (siblings && Array.isArray(siblings)) {
1344
+ // top index is a number because top container is an array
1345
+ const index = this._indexes.top();
1346
+ if (siblings.length > index + 1) {
1347
+ return siblings.splice(index + 1, 1)[0];
1348
+ }
1349
+ }
1350
+ return null;
1351
+ }
1352
+
1353
+ /**
1354
+ * Replace the current node in the tree with the specified nodes. If no
1355
+ * nodes are passed, this is a node deletion. If one node (or array) is
1356
+ * passed, this is a 1-for-1 replacement. If more than one node is passed
1357
+ * then this is a combination of deletion and insertion. The new node or
1358
+ * nodes will not be traversed, so this method can safely be used to
1359
+ * reparent the current node node beneath a new parent.
1360
+ *
1361
+ * This method throws an error if you attempt to replace the root node of
1362
+ * the tree.
1363
+ */
1364
+ replace() {
1365
+ const parent = this._containers.top();
1366
+ if (!parent) {
1367
+ throw new perseusError.PerseusError("Can't replace the root of the tree", perseusError.Errors.Internal);
1368
+ }
1369
+
1370
+ // The top of the container stack is either an array or an object
1371
+ // and the top of the indexes stack is a corresponding array index
1372
+ // or object property. This is hard for Flow, so we have to do some
1373
+ // unsafe casting and be careful when we use which cast version
1374
+ for (var _len = arguments.length, replacements = new Array(_len), _key = 0; _key < _len; _key++) {
1375
+ replacements[_key] = arguments[_key];
1376
+ }
1377
+ if (Array.isArray(parent)) {
1378
+ const index = this._indexes.top();
1379
+ // For an array parent we just splice the new nodes in
1380
+ parent.splice(index, 1, ...replacements);
1381
+ // Adjust the index to account for the changed array length.
1382
+ // We don't want to traverse any of the newly inserted nodes.
1383
+ this._indexes.pop();
1384
+ this._indexes.push(index + replacements.length - 1);
1385
+ } else {
1386
+ const property = this._indexes.top();
1387
+ // For an object parent we care how many new nodes there are
1388
+ if (replacements.length === 0) {
1389
+ // Deletion
1390
+ delete parent[property];
1391
+ } else if (replacements.length === 1) {
1392
+ // Replacement
1393
+ parent[property] = replacements[0];
1394
+ } else {
1395
+ // Replace one node with an array of nodes
1396
+ parent[property] = replacements;
1397
+ }
1398
+ }
1399
+ }
1400
+
1401
+ /**
1402
+ * Returns true if the current node has a previous sibling and false
1403
+ * otherwise. If this method returns false, then previousSibling() will
1404
+ * return null, and goToPreviousSibling() will throw an error.
1405
+ */
1406
+ hasPreviousSibling() {
1407
+ return Array.isArray(this._containers.top()) && this._indexes.top() > 0;
1408
+ }
1409
+
1410
+ /**
1411
+ * Modify this traversal state object to have the state it would have had
1412
+ * when visiting the previous sibling. Note that you may want to use
1413
+ * clone() to make a copy before modifying the state object like this.
1414
+ * This mutator method is not typically used during ordinary tree
1415
+ * traversals, but is used by the Selector class for matching multi-node
1416
+ * selectors.
1417
+ */
1418
+ goToPreviousSibling() {
1419
+ if (!this.hasPreviousSibling()) {
1420
+ throw new perseusError.PerseusError("goToPreviousSibling(): node has no previous sibling", perseusError.Errors.Internal);
1421
+ }
1422
+ this._currentNode = this.previousSibling();
1423
+ // Since we know that we have a previous sibling, we know that
1424
+ // the value on top of the stack is a number, but we have to do
1425
+ // this unsafe cast because Flow doesn't know that.
1426
+ const index = this._indexes.pop();
1427
+ this._indexes.push(index - 1);
1428
+ }
1429
+
1430
+ /**
1431
+ * Returns true if the current node has an ancestor and false otherwise.
1432
+ * If this method returns false, then the parent() method will return
1433
+ * null and goToParent() will throw an error
1434
+ */
1435
+ hasParent() {
1436
+ return this._ancestors.size() !== 0;
1437
+ }
1438
+
1439
+ /**
1440
+ * Modify this object to look like it will look when we (later) visit the
1441
+ * parent node of this node. You should not modify the instance passed to
1442
+ * the tree traversal callback. Instead, make a copy with the clone()
1443
+ * method and modify that. This mutator method is not typically used
1444
+ * during ordinary tree traversals, but is used by the Selector class for
1445
+ * matching multi-node selectors that involve parent and ancestor
1446
+ * selectors.
1447
+ */
1448
+ goToParent() {
1449
+ if (!this.hasParent()) {
1450
+ throw new perseusError.PerseusError("goToParent(): node has no ancestor", perseusError.Errors.NotAllowed);
1451
+ }
1452
+ this._currentNode = this._ancestors.pop();
1453
+
1454
+ // We need to pop the containers and indexes stacks at least once
1455
+ // and more as needed until we restore the invariant that
1456
+ // this._containers.top()[this.indexes.top()] === this._currentNode
1457
+ //
1458
+ while (this._containers.size() &&
1459
+ // This is safe, but easier to just disable flow than do casts
1460
+ // $FlowFixMe[incompatible-use]
1461
+ this._containers.top()[this._indexes.top()] !== this._currentNode) {
1462
+ this._containers.pop();
1463
+ this._indexes.pop();
1464
+ }
1465
+ }
1466
+
1467
+ /**
1468
+ * Return a new TraversalState object that is a copy of this one.
1469
+ * This method is useful in conjunction with the mutating methods
1470
+ * goToParent() and goToPreviousSibling().
1471
+ */
1472
+ clone() {
1473
+ const clone = new TraversalState(this.root);
1474
+ clone._currentNode = this._currentNode;
1475
+ clone._containers = this._containers.clone();
1476
+ clone._indexes = this._indexes.clone();
1477
+ clone._ancestors = this._ancestors.clone();
1478
+ return clone;
1479
+ }
1480
+
1481
+ /**
1482
+ * Returns true if this TraversalState object is equal to that
1483
+ * TraversalState object, or false otherwise. This method exists
1484
+ * primarily for use by our unit tests.
1485
+ */
1486
+ equals(that) {
1487
+ return this.root === that.root && this._currentNode === that._currentNode && this._containers.equals(that._containers) && this._indexes.equals(that._indexes) && this._ancestors.equals(that._ancestors);
1488
+ }
1489
+ }
1490
+
1491
+ /**
1492
+ * This class is an internal utility that just treats an array as a stack
1493
+ * and gives us a top() method so we don't have to write expressions like
1494
+ * `ancestors[ancestors.length-1]`. The values() method automatically
1495
+ * copies the internal array so we don't have to worry about client code
1496
+ * modifying our internal stacks. The use of this Stack abstraction makes
1497
+ * the TraversalState class simpler in a number of places.
1498
+ */
1499
+ class Stack {
1500
+ constructor(array) {
1501
+ _defineProperty(this, "stack", void 0);
1502
+ this.stack = array ? array.slice(0) : [];
1503
+ }
1504
+
1505
+ /** Push a value onto the stack. */
1506
+ push(v) {
1507
+ this.stack.push(v);
1508
+ }
1509
+
1510
+ /** Pop a value off of the stack. */
1511
+ pop() {
1512
+ // @ts-expect-error [FEI-5003] - TS2322 - Type 'T | undefined' is not assignable to type 'T'.
1513
+ return this.stack.pop();
1514
+ }
1515
+
1516
+ /** Return the top value of the stack without popping it. */
1517
+ top() {
1518
+ return this.stack[this.stack.length - 1];
1519
+ }
1520
+
1521
+ /** Return a copy of the stack as an array */
1522
+ values() {
1523
+ return this.stack.slice(0);
1524
+ }
1525
+
1526
+ /** Return the number of elements in the stack */
1527
+ size() {
1528
+ return this.stack.length;
1529
+ }
1530
+
1531
+ /** Return a string representation of the stack */
1532
+ toString() {
1533
+ return this.stack.toString();
1534
+ }
1535
+
1536
+ /** Return a shallow copy of the stack */
1537
+ clone() {
1538
+ return new Stack(this.stack);
1539
+ }
1540
+
1541
+ /**
1542
+ * Compare this stack to another and return true if the contents of
1543
+ * the two arrays are the same.
1544
+ */
1545
+ equals(that) {
1546
+ if (!that || !that.stack || that.stack.length !== this.stack.length) {
1547
+ return false;
1548
+ }
1549
+ for (let i = 0; i < this.stack.length; i++) {
1550
+ if (this.stack[i] !== that.stack[i]) {
1551
+ return false;
1552
+ }
1553
+ }
1554
+ return true;
1555
+ }
1556
+ }
1557
+
1558
+ // Define the shape of the linter context object that is passed through the
1559
+ const linterContextProps = PropTypes__default["default"].shape({
1560
+ contentType: PropTypes__default["default"].string,
1561
+ highlightLint: PropTypes__default["default"].bool,
1562
+ paths: PropTypes__default["default"].arrayOf(PropTypes__default["default"].string),
1563
+ stack: PropTypes__default["default"].arrayOf(PropTypes__default["default"].string)
1564
+ });
1565
+ const linterContextDefault = {
1566
+ contentType: "",
1567
+ highlightLint: false,
1568
+ paths: [],
1569
+ stack: []
1570
+ };
1571
+
1572
+ const allLintRules = AllRules.filter(r => r.severity < Rule.Severity.BULK_WARNING);
1573
+
1574
+ //
1575
+ // Run the Perseus linter over the specified markdown parse tree,
1576
+ // with the specified context object, and
1577
+ // return a (possibly empty) array of lint warning objects. If the
1578
+ // highlight argument is true, this function also modifies the parse
1579
+ // tree to add "lint" nodes that can be visually rendered,
1580
+ // highlighting the problems for the user. The optional rules argument
1581
+ // is an array of Rule objects specifying which lint rules should be
1582
+ // applied to this parse tree. When omitted, a default set of rules is used.
1583
+ //
1584
+ // The context object may have additional properties that some lint
1585
+ // rules require:
1586
+ //
1587
+ // context.content is the source content string that was parsed to create
1588
+ // the parse tree.
1589
+ //
1590
+ // context.widgets is the widgets object associated
1591
+ // with the content string
1592
+ //
1593
+ // TODO: to make this even more general, allow the first argument to be
1594
+ // a string and run the parser over it in that case? (but ignore highlight
1595
+ // in that case). This would allow the one function to be used for both
1596
+ // online linting and batch linting.
1597
+ //
1598
+ function runLinter(tree, context, highlight) {
1599
+ let rules = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : allLintRules;
1600
+ const warnings = [];
1601
+ const tt = new TreeTransformer(tree);
1602
+
1603
+ // The markdown parser often outputs adjacent text nodes. We
1604
+ // coalesce them before linting for efficiency and accuracy.
1605
+ tt.traverse((node, state, content) => {
1606
+ if (TreeTransformer.isTextNode(node)) {
1607
+ let next = state.nextSibling();
1608
+ while (TreeTransformer.isTextNode(next)) {
1609
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'. | TS2533 - Object is possibly 'null' or 'undefined'. | TS2339 - Property 'content' does not exist on type 'TreeNode'.
1610
+ node.content += next.content;
1611
+ state.removeNextSibling();
1612
+ next = state.nextSibling();
1613
+ }
1614
+ }
1615
+ });
1616
+
1617
+ // HTML tables are complicated, and the CSS we use in
1618
+ // ../components/lint.jsx to display lint does not work to
1619
+ // correctly position the lint indicators in the margin when the
1620
+ // lint is inside a table. So as a workaround we keep track of all
1621
+ // the lint that appears within a table and move it up to the
1622
+ // table element itself.
1623
+ //
1624
+ // It is not ideal to have to do this here,
1625
+ // but it is cleaner here than fixing up the lint during rendering
1626
+ // in perseus-markdown.jsx. If our lint display was simpler and
1627
+ // did not require indicators in the margin, this wouldn't be a
1628
+ // problem. Or, if we modified the lint display stuff so that
1629
+ // indicator positioning and tooltip display were both handled
1630
+ // with JavaScript (instead of pure CSS), then we could avoid this
1631
+ // issue too. But using JavaScript has its own downsides: there is
1632
+ // risk that the linter JavaScript would interfere with
1633
+ // widget-related Javascript.
1634
+ let tableWarnings = [];
1635
+ let insideTable = false;
1636
+
1637
+ // Traverse through the nodes of the parse tree. At each node, loop
1638
+ // through the array of lint rules and check whether there is a
1639
+ // lint violation at that node.
1640
+ tt.traverse((node, state, content) => {
1641
+ const nodeWarnings = [];
1642
+
1643
+ // If our rule is only designed to be tested against a particular
1644
+ // content type and we're not in that content type, we don't need to
1645
+ // consider that rule.
1646
+ const applicableRules = rules.filter(r => r.applies(context));
1647
+
1648
+ // Generate a stack so we can identify our position in the tree in
1649
+ // lint rules
1650
+ const stack = [...context.stack];
1651
+ stack.push(node.type);
1652
+ const nodeContext = {
1653
+ ...context,
1654
+ stack: stack.join(".")
1655
+ };
1656
+ applicableRules.forEach(rule => {
1657
+ const warning = rule.check(node, state, content, nodeContext);
1658
+ if (warning) {
1659
+ // The start and end locations are relative to this
1660
+ // particular node, and so are not generally very useful.
1661
+ // TODO: When the markdown parser saves the node
1662
+ // locations in the source string then we can add
1663
+ // these numbers to that one and get and absolute
1664
+ // character range that will be useful
1665
+ if (warning.start || warning.end) {
1666
+ warning.target = content.substring(warning.start, warning.end);
1667
+ }
1668
+
1669
+ // Add the warning to the list of all lint we've found
1670
+ warnings.push(warning);
1671
+
1672
+ // If we're going to be highlighting lint, then we also
1673
+ // need to keep track of warnings specific to this node.
1674
+ if (highlight) {
1675
+ nodeWarnings.push(warning);
1676
+ }
1677
+ }
1678
+ });
1679
+
1680
+ // If we're not highlighting lint in the tree, then we're done
1681
+ // traversing this node.
1682
+ if (!highlight) {
1683
+ return;
1684
+ }
1685
+
1686
+ // If the node we are currently at is a table, and there was lint
1687
+ // inside the table, then we want to add that lint here
1688
+ if (node.type === "table") {
1689
+ if (tableWarnings.length) {
1690
+ nodeWarnings.push(...tableWarnings);
1691
+ }
1692
+
1693
+ // We're not in a table anymore, and don't have to remember
1694
+ // the warnings for the table
1695
+ insideTable = false;
1696
+ tableWarnings = [];
1697
+ } else if (!insideTable) {
1698
+ // Otherwise, if we are not already inside a table, check
1699
+ // to see if we've entered one. Because this is a post-order
1700
+ // traversal we'll see the table contents before the table itself.
1701
+ // Note that once we're inside the table, we don't have to
1702
+ // do this check each time... We can just wait until we ascend
1703
+ // up to the table, then we'll know we're out of it.
1704
+ insideTable = state.ancestors().some(n => n.type === "table");
1705
+ }
1706
+
1707
+ // If we are inside a table and there were any warnings on
1708
+ // this node, then we need to save the warnings for display
1709
+ // on the table itself
1710
+ if (insideTable && nodeWarnings.length) {
1711
+ // @ts-expect-error [FEI-5003] - TS2345 - Argument of type 'any' is not assignable to parameter of type 'never'.
1712
+ tableWarnings.push(...nodeWarnings);
1713
+ }
1714
+
1715
+ // If there were any warnings on this node, and if we're highlighting
1716
+ // lint, then reparent the node so we can highlight it. Note that
1717
+ // a single node can have multiple warnings. If this happends we
1718
+ // concatenate the warnings and newline separate them. (The lint.jsx
1719
+ // component that displays the warnings may want to convert the
1720
+ // newlines into <br> tags.) We also provide a lint rule name
1721
+ // so that lint.jsx can link to a document that provides more details
1722
+ // on that particular lint rule. If there is more than one warning
1723
+ // we only link to the first rule, however.
1724
+ //
1725
+ // Note that even if we're inside a table, we still reparent the
1726
+ // linty node so that it can be highlighted. We just make a note
1727
+ // of whether this lint is inside a table or not.
1728
+ if (nodeWarnings.length) {
1729
+ nodeWarnings.sort((a, b) => {
1730
+ return a.severity - b.severity;
1731
+ });
1732
+ if (node.type !== "text" || nodeWarnings.length > 1) {
1733
+ // If the linty node is not a text node, or if there is more
1734
+ // than one warning on a text node, then reparent the entire
1735
+ // node under a new lint node and put the warnings there.
1736
+ state.replace({
1737
+ type: "lint",
1738
+ // @ts-expect-error [FEI-5003] - TS2345 - Argument of type '{ type: string; content: TreeNode; message: string; ruleName: any; blockHighlight: any; insideTable: boolean; severity: any; }' is not assignable to parameter of type 'TreeNode'.
1739
+ content: node,
1740
+ message: nodeWarnings.map(w => w.message).join("\n\n"),
1741
+ ruleName: nodeWarnings[0].rule,
1742
+ blockHighlight: nodeContext.blockHighlight,
1743
+ insideTable: insideTable,
1744
+ severity: nodeWarnings[0].severity
1745
+ });
1746
+ } else {
1747
+ //
1748
+ // Otherwise, it is a single warning on a text node, and we
1749
+ // only want to highlight the actual linty part of that string
1750
+ // of text. So we want to replace the text node with (in the
1751
+ // general case) three nodes:
1752
+ //
1753
+ // 1) A new text node that holds the non-linty prefix
1754
+ //
1755
+ // 2) A lint node that is the parent of a new text node
1756
+ // that holds the linty part
1757
+ //
1758
+ // 3) A new text node that holds the non-linty suffix
1759
+ //
1760
+ // If the lint begins and/or ends at the boundaries of the
1761
+ // original text node, then nodes 1 and/or 3 won't exist, of
1762
+ // course.
1763
+ //
1764
+ // Note that we could generalize this to work with multple
1765
+ // warnings on a text node as long as the warnings are
1766
+ // non-overlapping. Hopefully, though, multiple warnings in a
1767
+ // single text node will be rare in practice. Also, we don't
1768
+ // have a good way to display multiple lint indicators on a
1769
+ // single line, so keeping them combined in that case might
1770
+ // be the best thing, anyway.
1771
+ //
1772
+ // @ts-expect-error [FEI-5003] - TS2339 - Property 'content' does not exist on type 'TreeNode'.
1773
+ const content = node.content; // Text nodes have content
1774
+ const warning = nodeWarnings[0]; // There is only one warning.
1775
+ // These are the lint boundaries within the content
1776
+ const start = warning.start || 0;
1777
+ const end = warning.end || content.length;
1778
+ const prefix = content.substring(0, start);
1779
+ const lint = content.substring(start, end);
1780
+ const suffix = content.substring(end);
1781
+ // TODO(FEI-5003): Give this a real type.
1782
+ const replacements = []; // What we'll replace the node with
1783
+
1784
+ // The prefix text node, if there is one
1785
+ if (prefix) {
1786
+ replacements.push({
1787
+ type: "text",
1788
+ content: prefix
1789
+ });
1790
+ }
1791
+
1792
+ // The lint node wrapped around the linty text
1793
+ replacements.push({
1794
+ type: "lint",
1795
+ content: {
1796
+ type: "text",
1797
+ content: lint
1798
+ },
1799
+ message: warning.message,
1800
+ ruleName: warning.rule,
1801
+ insideTable: insideTable,
1802
+ severity: warning.severity
1803
+ });
1804
+
1805
+ // The suffix node, if there is one
1806
+ if (suffix) {
1807
+ replacements.push({
1808
+ type: "text",
1809
+ content: suffix
1810
+ });
1811
+ }
1812
+
1813
+ // Now replace the lint text node with the one to three
1814
+ // nodes in the replacement array
1815
+ state.replace(...replacements);
1816
+ }
1817
+ }
1818
+ });
1819
+ return warnings;
1820
+ }
1821
+ function pushContextStack(context, name) {
1822
+ const stack = context.stack || [];
1823
+ return {
1824
+ ...context,
1825
+ stack: stack.concat(name)
1826
+ };
1827
+ }
1828
+
1829
+ exports.Rule = Rule;
1830
+ exports.linterContextDefault = linterContextDefault;
1831
+ exports.linterContextProps = linterContextProps;
1832
+ exports.pushContextStack = pushContextStack;
1833
+ exports.rules = allLintRules;
1834
+ exports.runLinter = runLinter;
1835
+ //# sourceMappingURL=index.js.map