@khanacademy/perseus-linter 1.3.7 → 2.0.0

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