@khanacademy/perseus-linter 8.0.0 → 8.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { parse as o, traverseContent as s } from "@khanacademy/pure-markdown";
|
|
|
4
4
|
import * as c from "@khanacademy/kas";
|
|
5
5
|
import { vector as l } from "@khanacademy/kmath";
|
|
6
6
|
//#region \0rolldown/runtime.js
|
|
7
|
-
var u = "@khanacademy/perseus-linter", d = "8.0.
|
|
7
|
+
var u = "@khanacademy/perseus-linter", d = "8.0.1";
|
|
8
8
|
e(u, d);
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region packages/perseus-linter/src/proptypes.ts
|
|
@@ -809,8 +809,8 @@ Shorten it to 500 characters or fewer.`);
|
|
|
809
809
|
widgetType: "numeric-input",
|
|
810
810
|
lint(e) {
|
|
811
811
|
let t = [], n = e.options.answers;
|
|
812
|
-
return n.some((e) => e.value == null) && t.push("One or more answers is empty"), n.forEach((e, n) => {
|
|
813
|
-
e.strict && (!e.answerForms || e.answerForms.length === 0) && t.push(`Answer ${n + 1} requires a format, but no format was selected`);
|
|
812
|
+
return n.some((e) => e.value == null) && t.push(linterError("One or more answers is empty")), n.forEach((e, n) => {
|
|
813
|
+
e.strict && (!e.answerForms || e.answerForms.length === 0) && t.push(linterError(`Answer ${n + 1} requires a format, but no format was selected`));
|
|
814
814
|
}), t;
|
|
815
815
|
}
|
|
816
816
|
}), he = h.makeWidgetRule({
|
|
@@ -873,13 +873,17 @@ function getTextContent(e) {
|
|
|
873
873
|
function getTitleText(e) {
|
|
874
874
|
return getTextContent(e?.title).trim();
|
|
875
875
|
}
|
|
876
|
+
function hasEmptyHeaders(e) {
|
|
877
|
+
return e.header.every((e) => getTextContent(e).trim() === "");
|
|
878
|
+
}
|
|
876
879
|
var Z = h.makeRule({
|
|
877
880
|
name: "table-missing-caption",
|
|
878
881
|
selector: "table",
|
|
879
|
-
lint: function(e) {
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
if (
|
|
882
|
+
lint: function(e, t, n) {
|
|
883
|
+
if (hasEmptyHeaders(n[0])) return;
|
|
884
|
+
let r = e.parent();
|
|
885
|
+
if (r?.type !== "titledTable") return linterGuideline(xe);
|
|
886
|
+
if (getTitleText(r) === "") return linterGuideline(Se);
|
|
883
887
|
}
|
|
884
888
|
}), Ce = h.makeRule({
|
|
885
889
|
name: "table-missing-cells",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["kvector","AbsoluteUrl","FreeResponseWidgetError","HeadingLevel1","HeadingLevelSkip","HeadingSentenceCase","HeadingTitleCase","ImageAltText","ImageMarkdown","ImageSpacesAroundUrls","ImageUrlEmpty","ImageWidgetAltText","ImageWidgetEmptySize","InaccessibleWidget","InteractiveGraphLockedFigureOob","InteractiveGraphWidgetError","LabelImageWidgetError","LegacyGifUrl","LinkClickHere","LongParagraph","MatcherWidgetError","MathAdjacent","MathAlignExtraBreak","MathAlignLinebreaks","MathEmpty","MathFrac","MathNested","MathStartsWithSpace","MathTextEmpty","MathWithoutDollars","NestedLists","NumericInputMissingLabel","NumericInputWidgetError","PhetSimulationWidgetError","PythonProgramWidgetError","RadioWidgetError","SorterWidgetError","SorterWidgetWarning","StaticWidgetInQuestionStem","TableMissingCaption","TableMissingCells","UnbalancedCodeDelimiters","UnescapedDollar","KAS","libName","libVersion","addLibraryVersionToPerseusDebug","linterContextDefault","Severity","options","Parser","selectorText","PerseusError","Errors","s","c","ts","token","treeSelectors","ns","t","message","selectors","i","result","state","type","node","left","right","rightResult","leftResult","_Rule","Rule","selector","pattern","name","lint","widgetId","widgetInfo","context","content","error","location","rawLintOutput","selectorMatch","traversalState","patternMatch","lastSlash","expression","flags","match","index","input","HOSTNAME","url","absolute_url_default","nodes","hostname","parsedPerseusItem","hint","parsedPerseusArticle","section","parse","parsedPerseusRenderer","ExplanationWidgetRule","widget","widgets","instructions","ExplanationInGradedGroup","ExplanationInGradedGroupSet","groupNumbers","group","groupNumber","set","stringToButtonSet","ExpressionWidgetButtons","answers","buttons","answer","str","ExpressionWidgetCorrectAnswer","answerForms","form","ExpressionWidgetAnswerForms","issues","ix","issue","FillInTheBlankRule","rWidgetRule","free_response_widget_error_default","question","contentType","hintIssues","GradedGroupWidgetRule","GradedGroupSetWidgetRule","gradedGroup","n","GroupWidgetRule","heading_level_1_default","heading_level_skip_default","currentHeading","previousHeading","heading_sentence_case_default","littleWords","word","heading_title_case_default","words","w","image_alt_text_default","image","image_markdown_default","parsedMarkdown","hasInlineImageNode","traverseContent","image_spaces_around_urls_default","image_url_empty_default","image_widget_alt_text_default","alt","image_widget_empty_size_default","width","height","inaccessible_widget_default","widgetType","CoreWidgetRegistry","interactive_graph_locked_figure_oob_default","warnings","figure","lockedFigures","range","figureType","isSinglePoint","warning","x","y","xMin","xMax","yMin","yMax","point","cx","cy","rx","ry","interactive_graph_widget_error_default","vector","correct","graph","asymptoteY","asymptote","minY","coords","maxY","g","labels","l","expected","label_image_widget_error_default","choices","imageUrl","imageAlt","markers","numNoAnswers","numNoLabels","marker","LEGACY_HOSTNAME","legacy_gif_url_default","link_click_here_default","long_paragraph_default","matcher_widget_error_default","math_adjacent_default","math_align_extra_break_default","math_align_linebreaks_default","text","nextpair","math_empty_default","math_frac_default","math_nested_default","math_starts_with_space_default","math_text_empty_default","math_without_dollars_default","nested_lists_default","numeric_input_missing_label_default","numeric_input_widget_error_default","phet_simulation_widget_error_default","makeSafeUrl","python_program_widget_error_default","errors","radio_widget_error_default","choice","correctChoices","minCards","contentNodes","card","sorter_widget_error_default","sorter_widget_warning_default","SORTER_MAX_CARDS","layout","static_widget_in_question_stem_default","nodeId","MISSING_CAPTION_MESSAGE","EMPTY_CAPTION_MESSAGE","titledTable","table_missing_caption_default","parent","table_missing_cells_default","table","headerLength","rowLengths","r","unbalanced_code_delimiters_default","unescaped_dollar_default","TreeTransformer","root","TraversalState","f","key","value","Stack","siblings","replacements","property","clone","that","array","v","tt","tree","next","tableIssues","insideTable","nodeIssues","stack","nodeContext","ruleIssues","rule","highlight","a","b","start","end","prefix","suffix"],"sources":["../src/version.ts","../src/proptypes.ts","../src/lint.ts","../src/selector.ts","../src/rule.ts","../src/rules/lint-utils.ts","../src/rules/absolute-url.ts","../src/lint-content.ts","../src/rules/explanation.ts","../src/rules/explanation-in-graded-group.ts","../src/rules/expression-widget.ts","../src/rules/fill-in-the-blank.ts","../src/rules/free-response-widget-error.ts","../src/rules/lint-graded-group.ts","../src/rules/graded-group.ts","../src/rules/graded-group-set.ts","../src/rules/group.ts","../src/rules/heading-level-1.ts","../src/rules/heading-level-skip.ts","../src/rules/heading-sentence-case.ts","../src/rules/heading-title-case.ts","../src/rules/image-alt-text.ts","../src/rules/image-markdown.ts","../src/rules/image-spaces-around-urls.ts","../src/rules/image-url-empty.ts","../src/rules/image-widget-alt-text.ts","../src/rules/image-widget-empty-size.ts","../src/rules/inaccessible-widget.ts","../src/rules/interactive-graph-locked-figure-oob.ts","../src/rules/interactive-graph-widget-error.ts","../src/rules/label-image-widget-error.ts","../src/rules/legacy-gif-url.ts","../src/rules/link-click-here.ts","../src/rules/long-paragraph.ts","../src/rules/matcher-widget-error.ts","../src/rules/math-adjacent.ts","../src/rules/math-align-extra-break.ts","../src/rules/math-align-linebreaks.ts","../src/rules/math-empty.ts","../src/rules/math-frac.ts","../src/rules/math-nested.ts","../src/rules/math-starts-with-space.ts","../src/rules/math-text-empty.ts","../src/rules/math-without-dollars.ts","../src/rules/nested-lists.ts","../src/rules/numeric-input-missing-label.ts","../src/rules/numeric-input-widget-error.ts","../src/rules/phet-simulation-widget-error.ts","../src/rules/python-program-widget-error.ts","../src/rules/radio-widget-error.ts","../src/rules/sorter-widget-error.ts","../src/rules/sorter-widget-warning.ts","../src/rules/static-widget-in-question-stem.ts","../src/rules/table-missing-caption.ts","../src/rules/table-missing-cells.ts","../src/rules/unbalanced-code-delimiters.ts","../src/rules/unescaped-dollar.ts","../src/rules/all-rules.ts","../src/tree-transformer.ts","../src/run-linter.ts","../src/index.ts"],"sourcesContent":["// This file is processed by the Vite build to inject the production version\n// number during the release build.\n// In dev, you'll never see the version number.\n\nimport {addLibraryVersionToPerseusDebug} from \"@khanacademy/perseus-utils\";\n\nconst libName = \"@khanacademy/perseus-linter\";\nexport const libVersion = \"__lib_version__\";\n\naddLibraryVersionToPerseusDebug(libName, libVersion);\n","import type {LinterContextProps} from \"./types\";\n\nexport const linterContextDefault: LinterContextProps = {\n contentType: \"\",\n highlightLint: false,\n stack: [],\n};\n","export interface LintOptions {\n /** Indices into the content string where the issue occurs */\n location?: {start: number; end: number};\n metadata?: Record<string, any>;\n}\n\nexport const Severity = {\n ERROR: 1,\n WARNING: 2,\n GUIDELINE: 3,\n};\n\n/**\n * The type returned by the lint detection function passed to the Rule\n * constructor.\n */\nexport interface Lint extends LintOptions {\n message: string;\n severity: number;\n}\n\nexport function linterWarning(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.WARNING,\n ...options,\n };\n}\n\nexport function linterError(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.ERROR,\n ...options,\n };\n}\n\nexport function linterGuideline(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.GUIDELINE,\n ...options,\n };\n}\n","/**\n * The Selector class implements a CSS-like system for matching nodes in a\n * parse tree based on the structure of the tree. Create a Selector object by\n * calling the static Selector.parse() method on a string that describes the\n * tree structure you want to match. For example, if you want to find text\n * nodes that are direct children of paragraph nodes that immediately follow\n * heading nodes, you could create an appropriate selector like this:\n *\n * selector = Selector.parse(\"heading + paragraph > text\");\n *\n * Recall from the TreeTransformer class, that we consider any object with a\n * string-valued `type` property to be a tree node. The words \"heading\",\n * \"paragraph\" and \"text\" in the selector string above specify node types and\n * will match nodes in a parse tree that have `type` properties with those\n * values.\n *\n * Selectors are designed for use during tree traversals done with the\n * TreeTransformer traverse() method. To test whether the node currently being\n * traversed matches a selector, simply pass the TraversalState object to the\n * match() method of the Selector object. If the node does not match the\n * selector, match() returns null. If it does match, then match() returns an\n * array of nodes that match the selector. In the example above the first\n * element of the array would be the node the heading node, the second would\n * be the paragraph node that follows it, and the third would be the text node\n * that is a child of the paragraph. The last element of a returned array of\n * nodes is always equal to the current node of the tree traversal.\n *\n * Code that uses a selector might look like this:\n *\n * matchingNodes = selector.match(state);\n * if (matchingNodes) {\n * let heading = matchingNodes[0];\n * let text = matchingNodes[2];\n * // do something with those nodes\n * }\n *\n * The Selector.parse() method recognizes a grammar that is similar to CSS\n * selectors:\n *\n * selector := treeSelector (, treeSelector)*\n *\n * A selector is one or more comma-separated treeSelectors. A node matches\n * the selector if it matches any of the treeSelectors.\n *\n * treeSelector := (treeSelector combinator)? nodeSelector\n *\n * A treeSelector is a nodeSelector optionally preceeded by a combinator\n * and another tree selector. The tree selector matches if the current node\n * matches the node selector and a sibling or ancestor (depending on the\n * combinator) of the current node matches the optional treeSelector.\n *\n * combinator := ' ' | '>' | '+' | '~' // standard CSS3 combinators\n *\n * A combinator is a space or punctuation character that specifies the\n * relationship between two nodeSelectors. A space between two\n * nodeSelectors means that the first selector much match an ancestor of\n * the node that matches the second selector. A '>' character means that\n * the first selector must match the parent of the node matched by the\n * second. The '~' combinator means that the first selector must match a\n * previous sibling of the node matched by the second. And the '+' selector\n * means that first selector must match the immediate previous sibling of\n * the node that matched the second.\n *\n * nodeSelector := <IDENTIFIER> | '*'\n *\n * A nodeSelector is simply an identifier (a letter followed by any number\n * of letters, digits, hypens, and underscores) or the wildcard asterisk\n * character. A wildcard node selector matches any node. An identifier\n * selector matches any node that has a `type` property whose value matches\n * the identifier.\n *\n * If you call Selector.parse() on a string that does not match this grammar,\n * it will throw an exception\n *\n * Implementation Note: this file exports a very simple Selector class but all\n * the actual work is done in various internal classes. The Parser class\n * parses the string representation of a selector into a parse tree that\n * consists of instances of various subclasses of the Selector class. It is\n * these subclasses that implement the selector matching logic, often\n * depending on features of the TraversalState object from the TreeTransformer\n * traversal.\n */\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\nimport type {TreeNode, TraversalState} from \"./tree-transformer\";\n\n/**\n * This is the base class for all Selector types. The key method that all\n * selector subclasses must implement is match(). It takes a TraversalState\n * object (from a TreeTransformer traversal) and tests whether the selector\n * matches at the current node. See the comment at the start of this file for\n * more details on the match() method.\n */\nexport default class Selector {\n static parse(selectorText: string): Selector {\n return new Parser(selectorText).parse();\n }\n\n /**\n * Return an array of the nodes that matched or null if no match.\n * This is the base class so we just throw an exception. All Selector\n * subclasses must provide an implementation of this method.\n */\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n throw new PerseusError(\n \"Selector subclasses must implement match()\",\n Errors.NotAllowed,\n );\n }\n\n /**\n * Selector subclasses all define a toString() method primarily\n * because it makes it easy to write parser tests.\n */\n toString(): string {\n return \"Unknown selector class\";\n }\n}\n\n/**\n * This class implements a parser for the selector grammar. Pass the source\n * text to the Parser() constructor, and then call the parse() method to\n * obtain a corresponding Selector object. parse() throws an exception\n * if there are syntax errors in the selector.\n *\n * This class is not exported, and you don't need to use it directly.\n * Instead call the static Selector.parse() method.\n */\nclass Parser {\n static TOKENS: RegExp; // We do lexing with a simple regular expression\n tokens: ReadonlyArray<string>; // The array of tokens\n tokenIndex: number; // Which token in the array we're looking at now\n\n constructor(s: string) {\n // Normalize whitespace:\n // - remove leading and trailing whitespace\n // - replace runs of whitespace with single space characters\n s = s.trim().replace(/\\s+/g, \" \");\n // Convert the string to an array of tokens. Note that the TOKENS\n // pattern ignores spaces that do not appear before identifiers\n // or the * wildcard.\n this.tokens = s.match(Parser.TOKENS) || [];\n this.tokenIndex = 0;\n }\n\n // Return the next token or the empty string if there are no more\n nextToken(): string {\n return this.tokens[this.tokenIndex] || \"\";\n }\n\n // Increment the token index to \"consume\" the token we were looking at\n // and move on to the next one.\n consume(): void {\n this.tokenIndex++;\n }\n\n // Return true if the current token is an identifier or false otherwise\n isIdentifier(): boolean {\n // The Parser.TOKENS regexp ensures that we only have to check\n // the first character of a token to know what kind of token it is.\n const c = this.tokens[this.tokenIndex][0];\n return (c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\");\n }\n\n // Consume space tokens until the next token is not a space.\n skipSpace(): void {\n while (this.nextToken() === \" \") {\n this.consume();\n }\n }\n\n // Parse a comma-separated sequence of tree selectors. This is the\n // entry point for the Parser class and the only method that clients\n // ever need to call.\n parse(): Selector {\n // We expect at least one tree selector\n const ts = this.parseTreeSelector();\n\n // Now see what's next\n let token = this.nextToken();\n\n // If there is no next token then we're done parsing and can return\n // the tree selector object we got above\n if (!token) {\n return ts;\n }\n\n // Otherwise, there is more go come and we're going to need a\n // list of tree selectors\n const treeSelectors = [ts];\n while (token) {\n // The only character we allow after a tree selector is a comma\n if (token === \",\") {\n this.consume();\n } else {\n throw new ParseError(\"Expected comma\");\n }\n\n // And if we saw a comma, then it must be followed by another\n // tree selector\n treeSelectors.push(this.parseTreeSelector());\n token = this.nextToken();\n }\n\n // If we parsed more than one tree selector, return them in a\n // SelectorList object.\n return new SelectorList(treeSelectors);\n }\n\n // Parse a sequence of node selectors linked together with\n // hierarchy combinators: space, >, + and ~.\n parseTreeSelector(): Selector {\n this.skipSpace(); // Ignore space after a comma, for example\n\n // A tree selector must begin with a node selector\n let ns: Selector = this.parseNodeSelector();\n\n for (;;) {\n // Now check the next token. If there is none, or if it is a\n // comma, then we're done with the treeSelector. Otherwise\n // we expect a combinator followed by another node selector.\n // If we don't see a combinator, we throw an error. If we\n // do see a combinator and another node selector then we\n // combine the current node selector with the new node selector\n // using a Selector subclass that depends on the combinator.\n const token = this.nextToken();\n\n if (!token || token === \",\") {\n break;\n } else if (token === \" \") {\n this.consume();\n ns = new AncestorCombinator(ns, this.parseNodeSelector());\n } else if (token === \">\") {\n this.consume();\n ns = new ParentCombinator(ns, this.parseNodeSelector());\n } else if (token === \"+\") {\n this.consume();\n ns = new PreviousCombinator(ns, this.parseNodeSelector());\n } else if (token === \"~\") {\n this.consume();\n ns = new SiblingCombinator(ns, this.parseNodeSelector());\n } else {\n throw new ParseError(\"Unexpected token: \" + token);\n }\n }\n\n return ns;\n }\n\n // Parse a single node selector.\n // For now, this is just a node type or a wildcard.\n parseNodeSelector(): Selector {\n // First, skip any whitespace\n this.skipSpace();\n\n const t = this.nextToken();\n if (t === \"*\") {\n this.consume();\n return new AnyNode();\n }\n if (this.isIdentifier()) {\n this.consume();\n return new TypeSelector(t);\n }\n\n throw new ParseError(\"Expected node type\");\n }\n}\n\n// We break the input string into tokens with this regexp. Token types\n// are identifiers, integers, punctuation and spaces. Note that spaces\n// tokens are only returned when they appear before an identifier or\n// wildcard token and are otherwise omitted.\nParser.TOKENS = /([a-zA-Z][\\w-]*)|(\\d+)|[^\\s]|(\\s(?=[a-zA-Z*]))/g;\n\n/**\n * This is a trivial Error subclass that the Parser uses to signal parse errors\n */\nclass ParseError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * This Selector subclass is a list of selectors. It matches a node if any of\n * the selectors on the list matches the node. It considers the selectors in\n * order, and returns the array of nodes returned by whichever one matches\n * first.\n */\nclass SelectorList extends Selector {\n selectors: ReadonlyArray<Selector>;\n\n constructor(selectors: ReadonlyArray<Selector>) {\n super();\n this.selectors = selectors;\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n for (let i = 0; i < this.selectors.length; i++) {\n const s = this.selectors[i];\n const result = s.match(state);\n if (result) {\n return result;\n }\n }\n return null;\n }\n\n toString(): string {\n let result = \"\";\n for (let i = 0; i < this.selectors.length; i++) {\n result += i > 0 ? \", \" : \"\";\n result += this.selectors[i].toString();\n }\n return result;\n }\n}\n\n/**\n * This trivial Selector subclass implements the '*' wildcard and\n * matches any node.\n */\nclass AnyNode extends Selector {\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n return [state.currentNode()];\n }\n\n toString(): string {\n return \"*\";\n }\n}\n\n/**\n * This selector subclass implements the <IDENTIFIER> part of the grammar.\n * it matches any node whose `type` property is a specified string\n */\nclass TypeSelector extends Selector {\n type: string;\n\n constructor(type: string) {\n super();\n this.type = type;\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const node = state.currentNode();\n if (node.type === this.type) {\n return [node];\n }\n return null;\n }\n\n toString(): string {\n return this.type;\n }\n}\n\n/**\n * This selector subclass is the superclass of the classes that implement\n * matching for the four combinators. It defines left and right properties for\n * the two selectors that are to be combined, but does not define a match\n * method.\n */\nclass SelectorCombinator extends Selector {\n left: Selector;\n right: Selector;\n\n constructor(left: Selector, right: Selector) {\n super();\n this.left = left;\n this.right = right;\n }\n}\n\n/**\n * This Selector subclass implements the space combinator. It matches if the\n * right selector matches the current node and the left selector matches some\n * ancestor of the current node.\n */\nclass AncestorCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n state = state.clone();\n while (state.hasParent()) {\n state.goToParent();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the > combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * the parent of the current node.\n */\nclass ParentCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n if (state.hasParent()) {\n state = state.clone();\n state.goToParent();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" > \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the + combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * the immediate previous sibling of the current node.\n */\nclass PreviousCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n if (state.hasPreviousSibling()) {\n state = state.clone();\n state.goToPreviousSibling();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" + \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the ~ combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * any previous sibling of the current node.\n */\nclass SiblingCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n state = state.clone();\n while (state.hasPreviousSibling()) {\n state.goToPreviousSibling();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" ~ \" + this.right.toString();\n }\n}\n","/**\n * The Rule class represents a Perseus lint rule. A Rule instance has a check()\n * method that takes the same (node, state, content) arguments that a\n * TreeTransformer traversal callback function does. Call the check() method\n * during a tree traversal to determine whether the current node of the tree\n * violates the rule. If there is a violation, check() returns an array of\n * issues. Each issue is an object that includes the name of the rule,\n * an error message, and the start and end positions of the lint within the\n * node's content string. If there are no violations of the rule, check()\n * returns an empty array.\n *\n * A Rule is typically defined in terms of a name, a selector, a pattern\n * (RegExp) and a linting function. Use the `Rule.makeRule()` or\n * `Rule.makeWidgetRule()` static methods to create rules.\n *\n * Rules only apply to nodes matching both the selector and the RegExp pattern.\n * If check() is called with a non-matching node, then the linting function is\n * not called, and check() returns an empty array.\n *\n * Certain advanced lint rules need additional information about the content\n * being linted in order to detect lint. For example, a rule to check for\n * whitespace at the start and end of the URL for an image can't use the\n * information in the node or content arguments because the markdown parser\n * strips leading and trailing whitespace when parsing. (Nevertheless, these\n * spaces have been a practical problem for our content translation process so\n * in order to check for them, a lint rule needs access to the original\n * unparsed source text. Similarly, there are various lint rules that check\n * widget usage. For example, it is easy to write a lint rule to ensure that\n * images have alt text for images encoded in markdown. But when images are\n * added to our content via an image widget we also want to be able to check\n * for alt text. In order to do this, the lint rule needs to be able to look\n * widgets up by name in the widgets object associated with the parse tree.\n *\n * In order to support advanced linting rules like these, the check() method\n * takes a context object as its optional fourth argument, and passes this\n * object on to the lint function of each rule. Rules that require extra\n * context should not assume that they will always get it, and should verify\n * that the necessary context has been supplied before using it. Currently the\n * \"content\" property of the context object is the unparsed source text if\n * available, and the \"widgets\" property of the context object is the widget\n * object associated with that content string in the JSON object that defines\n * the Perseus article or exercise that is being linted.\n */\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\nimport {Severity} from \"./lint\";\nimport Selector from \"./selector\";\n\nimport type {Lint} from \"./lint\";\nimport type {TraversalState, TreeNode} from \"./tree-transformer\";\nimport type {PerseusWidgetTypes} from \"@khanacademy/perseus-core\";\n\nexport type MakeRuleOptions = {\n name: string;\n pattern?: RegExp;\n selector?: string;\n locale?: string;\n lint: LintTester;\n};\n\nexport type MakeWidgetRuleOptions<\n TWidgetType extends keyof PerseusWidgetTypes,\n> = {\n name: string;\n widgetType: TWidgetType;\n lint: (\n widgetInfo: PerseusWidgetTypes[TWidgetType],\n // TODO(benchristel): type context properly, here and everywhere it's\n // used in the perseus-linter package.\n context: any,\n ) => undefined | Lint | Lint[];\n};\n\nexport type MakeLintFunctionOptions = {\n message: string;\n severity: number;\n};\n\n// This represents the type returned by String.match(). It is an\n// array of strings, but also has index:number and input:string properties.\n// TypeScript doesn't handle it well, so we punt and just use any.\ntype PatternMatchType = any;\n\nexport type LinterIssue = {\n rule: string;\n message: string;\n start: number;\n end: number;\n target?: string;\n severity: number;\n metadata?: Record<string, any>;\n};\n\ntype LintRuleContextObject =\n | {\n content: string;\n contentType: \"article\" | \"exercise\";\n stack: string[];\n widgets: any[];\n }\n | null\n | undefined;\n\n// This is the type of the lint detection function that the Rule() constructor\n// expects as its fourth argument. It is passed the TraversalState object and\n// content string that were passed to check(), and is also passed the array of\n// nodes returned by the selector match and the array of strings returned by\n// the pattern match. It should return null if no lint is detected or an\n// error message or an object contining an error message.\ntype LintTester = (\n state: TraversalState,\n content: string,\n selectorMatch: ReadonlyArray<TreeNode>,\n patternMatch: PatternMatchType,\n context: LintRuleContextObject,\n) => Lint | Lint[] | undefined;\n\n/**\n * A Rule object describes a Perseus lint rule. See the comment at the top of\n * this file for detailed description.\n */\nexport default class Rule {\n name: string; // The name of the rule\n selector: Selector; // The specified selector or the DEFAULT_SELECTOR\n pattern: RegExp | null | undefined; // A regular expression if one was specified\n lint: LintTester; // The lint-testing function or a default\n static DEFAULT_SELECTOR: Selector;\n\n // The comment at the top of this file has detailed docs for\n // this constructor and its arguments\n constructor(\n name: string | null | undefined,\n selector: Selector | null | undefined,\n pattern: RegExp | null | undefined,\n lint: LintTester,\n ) {\n if (!selector && !pattern) {\n throw new PerseusError(\n \"Lint rules must have a selector or pattern\",\n Errors.InvalidInput,\n {metadata: {name}},\n );\n }\n\n this.name = name || \"unnamed rule\";\n this.selector = selector || Rule.DEFAULT_SELECTOR;\n this.pattern = pattern || null;\n this.lint = lint;\n }\n\n // A factory method for use with rules described in JSON files\n // See the documentation at the start of this file for details.\n static makeRule(options: MakeRuleOptions): Rule {\n return new Rule(\n options.name,\n options.selector ? Selector.parse(options.selector) : null,\n Rule.makePattern(options.pattern),\n options.lint,\n );\n }\n\n static makeWidgetRule<TWidgetType extends keyof PerseusWidgetTypes>(\n options: MakeWidgetRuleOptions<TWidgetType>,\n ): Rule {\n return new Rule(\n options.name,\n Selector.parse(\"widget\"),\n null,\n (state, content, nodes, match, context) => {\n // Only apply widget rules if the widget has the correct type.\n if (state.currentNode().widgetType !== options.widgetType) {\n return;\n }\n\n const widgetId = state.currentNode().id;\n if (!widgetId) {\n return;\n }\n\n const widgetInfo = context?.widgets?.[widgetId];\n if (!widgetInfo) {\n return;\n }\n\n return [options.lint(widgetInfo, context) ?? []]\n .flat()\n .map((lint) => ({\n ...lint,\n message: `${widgetId}: ${lint.message}`,\n }));\n },\n );\n }\n\n // Check the node n to see if it violates this lint rule. A return value\n // of false means there is no lint. A returned object indicates a lint\n // error. See the documentation at the top of this file for details.\n check(\n node: TreeNode,\n traversalState: TraversalState,\n content: string,\n context: LintRuleContextObject,\n ): LinterIssue[] {\n // Define some helper functions. These have to be inside the check\n // method because they need to close over both the `content` parameter\n // and the `this` binding.\n const toLinterIssue = (error: Lint): LinterIssue => {\n // If the error has no location data, we default the location to\n // the entire content string.\n const {location = {start: 0, end: content.length}} = error;\n return {\n rule: this.name,\n severity: error.severity,\n message: error.message,\n metadata: error.metadata,\n ...location,\n };\n };\n\n const toLinterIssues = (\n rawLintOutput: undefined | Lint | Lint[],\n ): LinterIssue[] => {\n if (rawLintOutput == null) {\n return [];\n }\n if (Array.isArray(rawLintOutput)) {\n return rawLintOutput.map(toLinterIssue);\n }\n return [toLinterIssue(rawLintOutput)];\n };\n\n // First, see if we match the selector.\n // If no selector was passed to the constructor, we use a\n // default selector that matches text nodes.\n const selectorMatch = this.selector.match(traversalState);\n\n // If the selector did not match, then we're done\n if (!selectorMatch) {\n return [];\n }\n\n // If the selector matched, then see if the pattern matches\n let patternMatch;\n if (this.pattern) {\n patternMatch = content.match(this.pattern);\n } else {\n // If there is no pattern, then just match all of the content.\n // Use a fake RegExp match object to represent this default match.\n patternMatch = Rule.FakePatternMatch(content, content, 0);\n }\n\n // If there was a pattern and it didn't match, then we're done\n if (!patternMatch) {\n return [];\n }\n\n try {\n // If we get here, then the selector and pattern have matched\n // so now we call the lint function to see if there is lint.\n return toLinterIssues(\n this.lint(\n traversalState,\n content,\n selectorMatch,\n patternMatch,\n context,\n ),\n );\n } catch (e: any) {\n // If the lint function threw an exception we handle that as\n // a special type of lint. We want the user to see the lint\n // warning in this case (even though it is out of their control)\n // so that the bug gets reported. Otherwise we'd never know that\n // a rule was failing.\n return [\n {\n rule: \"lint-rule-failure\",\n severity: Rule.Severity.ERROR,\n message: `Exception in rule ${this.name}: ${e.message}\nStack trace:\n${e.stack}`,\n start: 0,\n end: content.length,\n },\n ];\n }\n }\n\n /**\n * Create a linter function from a message.\n */\n static makeLintFunction({\n message,\n severity,\n }: MakeLintFunctionOptions): LintTester {\n return (\n state: TraversalState,\n content: string,\n selectorMatch: ReadonlyArray<TreeNode>,\n patternMatch: PatternMatchType,\n context: LintRuleContextObject,\n ) => {\n return {\n message,\n severity,\n location: {\n start: patternMatch.index,\n end: patternMatch.index + patternMatch[0].length,\n },\n };\n };\n }\n\n // The makeRule() factory function uses this static method to turn its\n // argument into a RegExp. If the argument is already a RegExp, we just\n // return it. Otherwise, we compile it into a RegExp and return that.\n // The reason this is necessary is that Rule.makeRule() is designed for\n // use with data from JSON files and JSON files can't include RegExp\n // literals. Strings passed to this function do not need to be delimited\n // with / characters unless you want to include flags for the RegExp.\n //\n // Examples:\n //\n // input \"\" ==> output null\n // input /foo/ ==> output /foo/\n // input \"foo\" ==> output /foo/\n // input \"/foo/i\" ==> output /foo/i\n //\n static makePattern(\n pattern?: RegExp | string | null,\n ): RegExp | null | undefined {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!pattern) {\n return null;\n }\n if (pattern instanceof RegExp) {\n return pattern;\n }\n if (pattern[0] === \"/\") {\n const lastSlash = pattern.lastIndexOf(\"/\");\n const expression = pattern.substring(1, lastSlash);\n const flags = pattern.substring(lastSlash + 1);\n // @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\"]'?\n // eslint-disable-next-line no-restricted-syntax\n return new RegExp(expression, flags as RegExp.flags);\n }\n return new RegExp(pattern);\n }\n\n // This static method returns an string array with index and input\n // properties added, in order to simulate the return value of the\n // String.match() method. We use it when a Rule has no pattern and we\n // want to simulate a match on the entire content string.\n static FakePatternMatch(\n input: string,\n match: string | null | undefined,\n index: number,\n ): PatternMatchType {\n const result: any = [match];\n result.index = index;\n result.input = input;\n return result;\n }\n\n static Severity: {\n ERROR: number;\n GUIDELINE: number;\n WARNING: number;\n } = Severity;\n}\n\nRule.DEFAULT_SELECTOR = Selector.parse(\"text\");\n","// Return the portion of a URL between // and /. This is the authority\n// portion which is usually just the hostname, but may also include\n// a username, password or port. We don't strip those things out because\n// we typically want to reject any URL that includes them\nconst HOSTNAME = /\\/\\/([^/]+)/;\n\n// Return the hostname of the URL, with any \"www.\" prefix removed.\n// If this is a relative URL with no hostname, return an empty string.\nexport function getHostname(url: string): string {\n if (!url) {\n return \"\";\n }\n const match = url.match(HOSTNAME);\n return match ? match[1] : \"\";\n}\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport {getHostname} from \"./lint-utils\";\n\nexport default Rule.makeRule({\n name: \"absolute-url\",\n selector: \"link, image\",\n lint: function (state, content, nodes, match) {\n const linkOrImage: any = nodes[0];\n const url = linkOrImage.target;\n const hostname = getHostname(url);\n\n if (\n hostname === \"khanacademy.org\" ||\n hostname.endsWith(\".khanacademy.org\")\n ) {\n return linterGuideline(`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.`);\n }\n },\n});\n","import {parse} from \"@khanacademy/pure-markdown\";\n\nimport {runLinter} from \"./run-linter\";\n\nimport type {LinterIssue} from \"./rule\";\nimport type {\n PerseusItem,\n PerseusArticle,\n PerseusRenderer,\n} from \"@khanacademy/perseus-core\";\n\nexport type ItemLinterIssues = {\n question: LinterIssue[];\n hints: LinterIssue[][];\n};\n/**\n * Lint a full Perseus item, including the question and all hints.\n *\n * @param parsedPerseusItem - A parsed PerseusItem, typically the output of\n * `parseAndMigratePerseusItem`.\n * @returns Question issues plus per-hint issue arrays.\n */\nexport function lintPerseusItem(\n parsedPerseusItem: PerseusItem,\n): ItemLinterIssues {\n const questionLint = lintPerseusRenderer(\n parsedPerseusItem.question,\n \"exercise\",\n );\n const hintLint = parsedPerseusItem.hints.map((hint) =>\n lintPerseusRenderer(hint, \"exercise\"),\n );\n\n return {\n question: questionLint,\n hints: hintLint,\n };\n}\n\n/**\n * Lint a Perseus article.\n *\n * @remarks A single `PerseusRenderer` is treated as one section, so the outer array\n * has length 1.\n * @param parsedPerseusArticle - A parsed PerseusArticle, typically the output\n * of `parseAndMigratePerseusArticle`.\n * @returns A nested array with one array of linter issues per article section\n */\nexport function lintPerseusArticle(\n parsedPerseusArticle: PerseusArticle,\n): LinterIssue[][] {\n const articleSections = Array.isArray(parsedPerseusArticle)\n ? parsedPerseusArticle\n : [parsedPerseusArticle];\n\n return articleSections.map((section) =>\n lintPerseusRenderer(section, \"article\"),\n );\n}\n\n/**\n * Lint a single Perseus renderer block by parsing its markdown content and\n * running the standard lint rules against it.\n *\n * @param parsedPerseusRenderer - Parsed renderer (content and widgets).\n * @param contentType - Lint context: article, exercise, or renderer-only.\n * @returns An array of lint issues found in the content.\n */\nexport function lintPerseusRenderer(\n parsedPerseusRenderer: PerseusRenderer,\n contentType: \"article\" | \"exercise\" | \"renderer\",\n): LinterIssue[] {\n const tree = parse(parsedPerseusRenderer.content);\n const context = {\n content: parsedPerseusRenderer.content,\n widgets: parsedPerseusRenderer.widgets,\n stack: [],\n contentType,\n };\n\n return [...runLinter(tree, context, false)];\n}\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nimport type {PerseusRenderer} from \"@khanacademy/perseus-core\";\n\nexport const ExplanationWidgetRule = Rule.makeWidgetRule({\n name: \"explanation\",\n widgetType: \"explanation\",\n lint(widget, context) {\n const renderer: PerseusRenderer = {\n content: widget.options.explanation,\n widgets: widget.options.widgets,\n images: {},\n };\n return lintPerseusRenderer(renderer, context);\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {PerseusWidgetsMap} from \"@khanacademy/perseus-core\";\n\nfunction hasExplanation(widgets: PerseusWidgetsMap): boolean {\n return Object.values(widgets).some(\n (widget) => widget.type === \"explanation\",\n );\n}\n\nconst instructions = `Don't use explanation widgets in graded groups. Use the Graded Group Hint instead.`;\n\n// Graded groups render their own \"Explain\" button, so an Explanation widget\n// inside one shows learners two differently-styled \"Explain\" buttons.\nexport const ExplanationInGradedGroup = Rule.makeWidgetRule({\n name: \"explanation-in-graded-group\",\n widgetType: \"graded-group\",\n lint: function (widget) {\n if (hasExplanation(widget.options.widgets)) {\n return linterWarning(\n `Contains explanation widget. ${instructions}`,\n );\n }\n },\n});\n\nexport const ExplanationInGradedGroupSet = Rule.makeWidgetRule({\n name: \"explanation-in-graded-group-set\",\n widgetType: \"graded-group-set\",\n lint: function (widget) {\n const groupNumbers = widget.options.gradedGroups\n .map((group, i) => (hasExplanation(group.widgets) ? i + 1 : 0))\n .filter((groupNumber) => groupNumber > 0);\n if (groupNumbers.length > 0) {\n return linterWarning(\n `Explanation widget in group ${groupNumbers.join(\" and \")}. ${instructions}`,\n );\n }\n },\n});\n","import * as KAS from \"@khanacademy/kas\";\n\nimport {linterError, linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nfunction buttonNotInButtonSet(name: string, set: string): string {\n return `Answer requires a button not found in the button sets: ${name} (in ${set})`;\n}\n\nconst stringToButtonSet = {\n \"\\\\sqrt\": \"prealgebra\",\n \"^\": \"prealgebra\",\n \"\\\\sin\": \"trig\",\n \"\\\\cos\": \"trig\",\n \"\\\\tan\": \"trig\",\n \"\\\\log\": \"logarithms\",\n \"\\\\ln\": \"logarithms\",\n};\n\n/**\n * Rule to make sure that Expression questions that require\n * a specific math symbol to answer have that math symbol\n * available in the keypad (desktop learners can use a keyboard,\n * but mobile learners must use the MathInput keypad)\n */\nexport const ExpressionWidgetButtons = Rule.makeWidgetRule({\n name: \"expression-widget-buttons\",\n widgetType: \"expression\",\n lint(widget) {\n const answers = widget.options.answerForms;\n const buttons: string[] = widget.options.buttonSets;\n for (const answer of answers) {\n for (const [str, set] of Object.entries(stringToButtonSet)) {\n if (answer.value.includes(str) && !buttons.includes(set)) {\n return linterWarning(buttonNotInButtonSet(str, set));\n }\n }\n }\n },\n});\n\n/**\n * Checks that expression widgets have a correct answer.\n */\nexport const ExpressionWidgetCorrectAnswer = Rule.makeWidgetRule({\n name: \"expression-widget-correct-answer\",\n widgetType: \"expression\",\n lint(widget) {\n const {answerForms} = widget.options;\n\n if (answerForms.length === 0) {\n return linterError(\"No answers specified.\");\n }\n\n const hasCorrect = answerForms.some((form) => {\n return form.considered === \"correct\";\n });\n if (!hasCorrect) {\n return linterError(\"No correct answer specified.\");\n }\n },\n});\n\n/**\n * Checks that each of an expression widget's answers is a parseable\n * expression, and is simplified if the answer requires simplification.\n */\nexport const ExpressionWidgetAnswerForms = Rule.makeWidgetRule({\n name: \"expression-widget-answer-forms\",\n widgetType: \"expression\",\n lint(widget) {\n const {answerForms, functions} = widget.options;\n const issues: string[] = [];\n\n answerForms.forEach((form, ix) => {\n if (form.value === \"\") {\n issues.push(`Answer ${ix + 1} is empty.`);\n return;\n }\n const expression = KAS.parse(form.value, {functions});\n if (!expression.parsed) {\n issues.push(`Couldn't parse ${form.value}.`);\n return;\n }\n if (form.simplify && !expression.expr.isSimplified()) {\n issues.push(\n `${form.value} isn't simplified, but is required to be.`,\n );\n }\n });\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nexport const FillInTheBlankRule = Rule.makeWidgetRule({\n name: \"fill-in-the-blank\",\n widgetType: \"fill-in-the-blank\",\n lint(widget, context) {\n const renderer = {\n content: widget.options.content,\n widgets: widget.options.widgets,\n images: {},\n };\n return lintPerseusRenderer(renderer, context);\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Taken from packages/perseus/src/util.ts\n// I can't import it directly because of circular dependencies.\n//\n// Removed the `^` at the beginning of the origial rWidgetRule from\n// Utils because it was only identifying widgets at the beginning of the\n// string, but we want to match widgets anywhere in the string.\n//\n// Note: We can't use PerseusMarkdown here because perseus is a\n// restricted dependency of perseus-linter (circular dependency).\nconst rWidgetRule = /\\[\\[\\u2603 (([a-z-]+) ([0-9]+))\\]\\]/;\n\nexport default Rule.makeWidgetRule({\n name: \"free-response-widget-error\",\n widgetType: \"free-response\",\n lint(widget) {\n const question = widget.options.question;\n if (!question) {\n return linterError(\"The question is empty\");\n }\n\n if (question.match(rWidgetRule) != null) {\n return linterError(\"The question contains a widget\");\n }\n },\n});\n","import {lintPerseusRenderer} from \"../lint-content\";\n\nimport type {Lint} from \"../lint\";\nimport type {PerseusGradedGroupWidgetOptions} from \"@khanacademy/perseus-core\";\n\ninterface Context {\n contentType: \"exercise\" | \"article\" | \"renderer\";\n}\n\nexport function lintGradedGroup(\n options: PerseusGradedGroupWidgetOptions,\n {contentType}: Context,\n): Lint[] {\n const {hint} = options;\n\n const issues = [...lintPerseusRenderer(options, contentType)];\n\n if (hint) {\n const hintIssues = lintPerseusRenderer(hint, contentType).map(\n (lint) => ({...lint, message: `(in hint) ${lint.message}`}),\n );\n issues.push(...hintIssues);\n }\n\n return issues;\n}\n","import Rule from \"../rule\";\n\nimport {lintGradedGroup} from \"./lint-graded-group\";\n\nexport const GradedGroupWidgetRule = Rule.makeWidgetRule({\n name: \"graded-group\",\n widgetType: \"graded-group\",\n lint: (widget, context) => lintGradedGroup(widget.options, context),\n});\n","import Rule from \"../rule\";\n\nimport {lintGradedGroup} from \"./lint-graded-group\";\n\nimport type {Lint} from \"../lint\";\n\nexport const GradedGroupSetWidgetRule = Rule.makeWidgetRule({\n name: \"graded-group-set\",\n widgetType: \"graded-group-set\",\n lint: (widget, context) => {\n return widget.options.gradedGroups.flatMap((gradedGroup, i) =>\n lintGradedGroup(gradedGroup, context).map(prefixGroupNumber(i + 1)),\n );\n },\n});\n\nfunction prefixGroupNumber(n: number): (lint: Lint) => Lint {\n return (lint) => ({...lint, message: `group ${n}: ${lint.message}`});\n}\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nexport const GroupWidgetRule = Rule.makeWidgetRule({\n name: \"group\",\n widgetType: \"group\",\n lint(widget, context) {\n return lintPerseusRenderer(widget.options, context);\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-level-1\",\n selector: \"heading\",\n lint: function (state, content, nodes, match) {\n const heading: any = nodes[0];\n if (heading.level === 1) {\n return linterWarning(`Don't use level-1 headings:\nBegin headings with two or more # characters.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-level-skip\",\n selector: \"heading ~ heading\",\n lint: function (state, content, nodes, match) {\n const currentHeading: any = nodes[1];\n const previousHeading: any = nodes[0];\n // A heading can have a level less than, the same as\n // or one more than the previous heading. But going up\n // by 2 or more levels is not right\n if (currentHeading.level > previousHeading.level + 1) {\n return linterWarning(`Skipped heading level:\nthis heading is level ${currentHeading.level} but\nthe previous heading was level ${previousHeading.level}`);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-sentence-case\",\n selector: \"heading\",\n pattern: /^\\W*[a-z]/, // first letter is lowercase\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `First letter is lowercase:\nthe first letter of a heading should be capitalized.`,\n }),\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\n// These are 3-letter and longer words that we would not expect to be\n// capitalized even in a title-case heading. See\n// http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html\nconst littleWords = {\n and: true,\n nor: true,\n but: true,\n the: true,\n for: true,\n} as const;\n\nfunction isCapitalized(word: any) {\n const c = word[0];\n return c === c.toUpperCase();\n}\n\nexport default Rule.makeRule({\n name: \"heading-title-case\",\n selector: \"heading\",\n pattern: /[^\\s:]\\s+[A-Z]+[a-z]/,\n locale: \"en\",\n lint: function (state, content, nodes, match) {\n // We want to assert that heading text is in sentence case, not\n // title case. The pattern above requires a capital letter at the\n // start of the heading and allows them after a colon, or in\n // acronyms that are all capitalized.\n //\n // But we can't warn just because the pattern matched because\n // proper nouns are also allowed bo be capitalized. We're not\n // going to do dictionary lookup to check for proper nouns, so\n // we try a heuristic: if the title is more than 3 words long\n // and if all the words are capitalized or are on the list of\n // words that don't get capitalized, then we'll assume that\n // the heading is incorrectly in title case and will warn.\n // But if there is at least one non-capitalized long word then\n // we're not in title case and we should not warn.\n\n const heading = content.trim();\n let words = heading.split(/\\s+/);\n\n // Remove the first word and the little words\n words.shift();\n words = words.filter(\n // eslint-disable-next-line no-prototype-builtins\n (w) => w.length > 2 && !littleWords.hasOwnProperty(w),\n );\n\n // If there are at least 3 remaining words and all\n // are capitalized, then the heading is in title case.\n if (words.length >= 3 && words.every((w) => isCapitalized(w))) {\n return linterGuideline(`Title-case heading:\nThis heading appears to be in title-case, but should be sentence-case.\nOnly capitalize the first letter and proper nouns.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-alt-text\",\n selector: \"image\",\n lint: function (state, content, nodes, match) {\n const image: any = nodes[0];\n if (!image.alt || !image.alt.trim()) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.`);\n }\n if (image.alt.length < 8) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ${image.alt.length} characters long.`);\n }\n },\n});\n","import {parse, traverseContent} from \"@khanacademy/pure-markdown\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n/**\n * This rule warns when it sees Markdown images used in the\n * top-level content. We are migrating to use the `image`\n * widget exclusively for images and this helps us to alert\n * content authors of this policy change. This rule ignores\n * markdown images found within other widgets for now.\n */\nexport default Rule.makeRule({\n name: \"image-markdown\",\n selector: \"image\",\n lint: function (state, content, nodes, match, context) {\n // Check if we're inside a widget - if so, allow markdown images.\n if (context?.stack && context.stack.includes(\"widget\")) {\n return;\n }\n\n // Discourage using markdown images in main content\n const parsedMarkdown = parse(context?.content || \"\", {});\n let hasInlineImageNode = false;\n\n traverseContent(parsedMarkdown, (node: any) => {\n if (node.type === \"image\") {\n hasInlineImageNode = true;\n }\n });\n\n if (hasInlineImageNode) {\n return linterWarning(`[Inline markdown image]:\nMarkdown images are not recommended - these are images that use the\n format. Please use the Image widget instead.`);\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-spaces-around-urls\",\n selector: \"image\",\n lint: function (state, content, nodes, match, context) {\n const image: any = nodes[0];\n const url: string = image.target;\n\n // The markdown parser strips leading and trailing spaces for us,\n // but they're still a problem for our translation process, so\n // we need to go check for them in the unparsed source string\n // if we have it.\n if (context && context.content) {\n // Find the url in the original content and make sure that the\n // character before is '(' and the character after is ')'\n const index = context.content.indexOf(url);\n if (index === -1) {\n // It is not an error if we didn't find it.\n return;\n }\n\n if (\n context.content[index - 1] !== \"(\" ||\n context.content[index + url.length] !== \")\"\n ) {\n return linterError(`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.`);\n }\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-url-empty\",\n selector: \"image\",\n lint: function (state, content, nodes) {\n const image: any = nodes[0];\n const url = image.target;\n\n // If no URL is provided, an infinite spinner will be shown in articles\n // overlaying the page where the image should be. This prevents the page\n // from fully loading. As a result, we check for URLS with all images.\n if (!url || !url.trim()) {\n return linterError(\"Images should have a URL\");\n }\n\n // NOTE(TB): Ideally there would be a check to confirm the URL works\n // and leads to a valid resource, but fetching the URL would require\n // linting to be able to handle async functions, which it currently\n // cannot do.\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Normally we have one rule per file. But since our selector class\n// can't match specific widget types directly, this rule implements\n// a number of image widget related rules in one place. This should\n// slightly increase efficiency, but it means that if there is more\n// than one problem with an image widget, the user will only see one\n// problem at a time.\nexport default Rule.makeWidgetRule({\n name: \"image-widget-alt-text\",\n widgetType: \"image\",\n lint(widget) {\n // Decorative images don't need alt text validation\n if (widget.options.decorative) {\n return;\n }\n\n const alt = widget.options.alt;\n\n // Non-decorative images must have alt text\n if (!alt) {\n return linterWarning(`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.`);\n }\n\n // Alt text must be descriptive (at least 8 characters)\n if (alt.trim().length < 8) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ${alt.trim().length} characters long.`);\n }\n\n // Make sure the alt text is not too long to be navigable\n if (alt.trim().length > 125) {\n return linterWarning(`Images should have alt text:\nfor accessibility, image alt text should not exceed 125 characters.\nThis image's alt text is ${alt.trim().length} characters long.\nPlease pair your alt with a long description below if you need significantly\nmore text to sufficiently describe the image.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Normally we have one rule per file. But since our selector class\n// can't match specific widget types directly, this rule implements\n// a number of image widget related rules in one place. This should\n// slightly increase efficiency, but it means that if there is more\n// than one problem with an image widget, the user will only see one\n// problem at a time.\nexport default Rule.makeWidgetRule({\n name: \"image-widget-empty-size\",\n widgetType: \"image\",\n lint(widget) {\n if (!widget.options.backgroundImage.url) {\n return;\n }\n\n const {width, height} = widget.options.backgroundImage;\n\n if (!width || !height) {\n return linterWarning(`Images should have a non-zero size.\nThis image has a width of ${width} and a height of ${height}.\nPlease use the \"Reset to original size\" button to set the size of the image.`);\n }\n },\n});\n","import {CoreWidgetRegistry} from \"@khanacademy/perseus-core\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"inaccessible-widget\",\n selector: \"widget\",\n lint: function (state, content, nodes, match, context) {\n const node = state.currentNode();\n const widgetType = node.widgetType;\n const widgetId = node.id;\n\n if (!widgetType || !widgetId) {\n return;\n }\n\n const widgetInfo = context?.widgets?.[widgetId];\n if (!widgetInfo) {\n return;\n }\n\n const accessible = CoreWidgetRegistry.isAccessible(\n widgetType,\n widgetInfo.options,\n );\n if (!accessible) {\n return linterWarning(\n `The \"${widgetType}\" widget is not accessible.`,\n {\n location: {start: 0, end: content.length},\n metadata: {\n widgetType: widgetType,\n widgetId: widgetId,\n },\n },\n );\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {\n Coord,\n GraphRange,\n LockedFigure,\n LockedFunctionType,\n PerseusInteractiveGraphWidgetOptions,\n} from \"@khanacademy/perseus-core\";\n\nexport default Rule.makeWidgetRule({\n name: \"interactive-graph-locked-figure-oob\",\n widgetType: \"interactive-graph\",\n lint(widget) {\n const {range, lockedFigures}: PerseusInteractiveGraphWidgetOptions =\n widget.options;\n\n const warnings: string[] = [];\n\n for (const figure of lockedFigures ?? []) {\n if (!hasPointInRange(figure, range)) {\n const figureType = getPreciseFigureType(figure);\n const isSinglePoint =\n figure.type === \"point\" || figure.type === \"label\";\n warnings.push(\n isSinglePoint\n ? `Locked ${figureType} is outside the graph bounds.`\n : `All defining points for locked ${figureType} are outside the graph bounds.`,\n );\n }\n }\n\n return warnings.map((warning) => linterWarning(warning));\n },\n});\n\nfunction getPreciseFigureType(figure: LockedFigure): string {\n switch (figure.type) {\n case \"line\":\n // Line, Segment, or Ray\n return figure.kind;\n case \"ellipse\":\n return figure.radius[0] === figure.radius[1] ? \"circle\" : \"ellipse\";\n default:\n return figure.type;\n }\n}\n\nfunction isInRange([x, y]: Coord, range: GraphRange): boolean {\n const [[xMin, xMax], [yMin, yMax]] = range;\n return x >= xMin && x <= xMax && y >= yMin && y <= yMax;\n}\n\n// Figures are only flagged when every point that defines them is off the\n// graph. Figures with a subset of points inside the graph are not flagged.\nfunction hasPointInRange(figure: LockedFigure, range: GraphRange): boolean {\n // Locked functions aren't checked.\n if (figure.type === \"function\") {\n return true;\n }\n\n return definingPoints(figure).some((point) => isInRange(point, range));\n}\n\nfunction definingPoints(\n figure: Exclude<LockedFigure, LockedFunctionType>,\n): Coord[] {\n switch (figure.type) {\n case \"point\":\n case \"label\":\n return [figure.coord];\n case \"line\":\n return figure.points.map((point) => point.coord);\n case \"vector\":\n case \"polygon\":\n return figure.points;\n case \"ellipse\": {\n // The center plus the four vertices at the ends of each axis.\n // The rotation is ignored for this simple implementation.\n const [cx, cy] = figure.center;\n const [rx, ry] = figure.radius;\n return [\n [cx, cy],\n [cx + rx, cy],\n [cx - rx, cy],\n [cx, cy + ry],\n [cx, cy - ry],\n ];\n }\n }\n}\n","import {vector as kvector} from \"@khanacademy/kmath\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"interactive-graph-widget-error\",\n widgetType: \"interactive-graph\",\n lint(widget) {\n const issues: string[] = [];\n const {correct, graph, lockedFigures} = widget.options;\n\n for (const figure of lockedFigures ?? []) {\n // A locked line on the graph cannot have length 0.\n if (\n figure.type === \"line\" &&\n kvector.equal(figure.points[0].coord, figure.points[1].coord)\n ) {\n issues.push(\"Locked line cannot have length 0.\");\n }\n\n // A locked polygon can't have all coordinates be the same.\n if (figure.type === \"polygon\") {\n if (\n // If every point is the same as the first point,\n // then all the points are the same.\n figure.points.every((point) =>\n kvector.equal(point, figure.points[0]),\n )\n ) {\n issues.push(\n \"Locked polygon cannot have all coordinates be the same.\",\n );\n }\n }\n\n // A locked ellipse must have positive radius.\n if (figure.type === \"ellipse\") {\n if (figure.radius[0] <= 0 || figure.radius[1] <= 0) {\n issues.push(\n \"Locked ellipse must have positive radius values.\",\n );\n }\n }\n }\n\n // Do not save a unlimited polygon that is open (coords is null).\n if (\n correct?.type === \"polygon\" &&\n correct.numSides === \"unlimited\" &&\n correct.coords == null\n ) {\n issues.push(\"Polygon must be closed.\");\n }\n\n // Exponential: the start asymptote must not fall between or on the\n // curve's start points — that makes the coefficient formula undefined.\n if (graph?.type === \"exponential\" && graph.startCoords != null) {\n const {coords, asymptote} = graph.startCoords;\n const asymptoteY = asymptote;\n const minY = Math.min(coords[0][1], coords[1][1]);\n const maxY = Math.max(coords[0][1], coords[1][1]);\n if (asymptoteY >= minY && asymptoteY <= maxY) {\n issues.push(\n \"The exponential start asymptote must not fall between or on the curve's start points.\",\n );\n }\n }\n\n checkShowPointLabelsHasLabels(graph, issues);\n checkShowPointLabelsHasLabels(correct, issues);\n\n return issues.map((issue) => linterError(issue));\n },\n});\n\n// Fields checked in addition to `type`, `showPointLabels`, and `pointLabels`\n// so we can compute the expected label count for graph types whose number\n// of labelable points depends on runtime configuration.\ntype ShowPointLabelsShape = {\n type: string;\n showPointLabels?: boolean;\n pointLabels?: readonly string[];\n numPoints?: number | \"unlimited\";\n numSides?: number | \"unlimited\";\n numSegments?: number;\n};\n\nfunction checkShowPointLabelsHasLabels(\n g: ShowPointLabelsShape | undefined,\n issues: Array<string>,\n) {\n if (g == null || g.type === \"none\" || g.type === \"vector\") {\n return;\n }\n if (g.showPointLabels !== true) {\n return;\n }\n const labels = g.pointLabels;\n if (labels === undefined || labels.every((l) => l == null || l === \"\")) {\n issues.push(\n \"showPointLabels is true but pointLabels has no labels. Provide a label for at least one point.\",\n );\n return;\n }\n const expected = expectedLabelCount(g);\n if (expected !== undefined && labels.length !== expected) {\n issues.push(\n `pointLabels has ${labels.length} entries but this graph type expects ${expected}. Use empty strings (\"\") to skip labels for specific points, e.g. [\"A\", \"\", \"C\"].`,\n );\n }\n}\n\n// Returns the number of labelable points on `g`, or `undefined` when the\n// count depends on runtime state that isn't authored (e.g. `numPoints:\n// \"unlimited\"`) and therefore can't be validated at lint time.\nfunction expectedLabelCount(g: ShowPointLabelsShape): number | undefined {\n switch (g.type) {\n case \"angle\":\n case \"quadratic\":\n return 3;\n case \"linear\":\n case \"ray\":\n case \"sinusoid\":\n case \"absolute-value\":\n case \"exponential\":\n case \"logarithm\":\n case \"tangent\":\n return 2;\n case \"circle\":\n return 1;\n case \"linear-system\":\n // Two lines, two endpoints each, flat-indexed.\n return 4;\n case \"segment\":\n // Two endpoints per segment, flat-indexed. Default to one\n // segment if `numSegments` isn't set (matches the widget's\n // default).\n return (g.numSegments ?? 1) * 2;\n case \"point\":\n if (g.numPoints === \"unlimited\" || g.numPoints == null) {\n return undefined;\n }\n return g.numPoints;\n case \"polygon\":\n if (g.numSides === \"unlimited\" || g.numSides == null) {\n return undefined;\n }\n return g.numSides;\n default:\n return undefined;\n }\n}\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"label-image-widget-error\",\n widgetType: \"label-image\",\n lint(widget) {\n const issues: string[] = [];\n const {choices, imageAlt, imageUrl, markers} = widget.options;\n\n if (choices.length < 2) {\n issues.push(\n \"label-image widget must have at least two answer choices\",\n );\n }\n\n if (!imageUrl) {\n issues.push(\"No image url provided\");\n } else if (!imageAlt) {\n issues.push(\"No image alt text provided\");\n }\n\n if (markers.length === 0) {\n issues.push(\"label-image widget requires at least one marker\");\n } else {\n let numNoAnswers = 0;\n let numNoLabels = 0;\n\n for (const marker of markers) {\n if (marker.answers.length === 0) {\n numNoAnswers++;\n }\n\n if (!marker.label) {\n numNoLabels++;\n }\n }\n\n if (numNoAnswers > 0) {\n issues.push(\n `label-image widget has ${numNoAnswers} markers with no answers selected`,\n );\n }\n\n if (numNoLabels > 0) {\n issues.push(\n `label-image widget has ${numNoLabels} markers with no ARIA label`,\n );\n }\n }\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport {getHostname} from \"./lint-utils\";\n\nconst LEGACY_HOSTNAME = \"ka-perseus-images.s3.amazonaws.com\";\n\nexport default Rule.makeWidgetRule({\n name: \"legacy-gif-url\",\n widgetType: \"image\",\n lint(widget) {\n const url = widget.options?.backgroundImage?.url;\n if (!url) {\n return;\n }\n\n // Legacy gifs hosted on the old S3 bucket don't render in the editor\n // iframe, so we encourage content creators to use the CDN URL instead\n // or confirm that the image displays correctly in the published content.\n if (\n getHostname(url) === LEGACY_HOSTNAME &&\n url.toLowerCase().endsWith(\".gif\")\n ) {\n return linterGuideline(`Legacy gif URL:\ngifs hosted at ${LEGACY_HOSTNAME} might not appear in the editor preview,\nbut can still be viewed in the published content. Please use a\ncdn.kastatic.org/ka-perseus-images/ URL instead or confirm the\nimage displays correctly in the published content.`);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"link-click-here\",\n selector: \"link\",\n pattern: /click here/i,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Inappropriate link text:\nDo not use the words \"click here\" in links.`,\n }),\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"long-paragraph\",\n selector: \"paragraph\",\n pattern: /^.{501,}/,\n lint: function (state, content, nodes, match) {\n return linterGuideline(`Paragraph too long:\nThis paragraph is ${content.length} characters long.\nShorten it to 500 characters or fewer.`);\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"matcher-widget-error\",\n widgetType: \"matcher\",\n lint(widget) {\n if (widget.options.left.length !== widget.options.right.length) {\n return linterError(\n \"The two halves of the matcher have different numbers of cards.\",\n );\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-adjacent\",\n selector: \"blockMath+blockMath\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Adjacent math blocks:\ncombine the blocks between \\\\begin{align} and \\\\end{align}`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-align-extra-break\",\n selector: \"blockMath\",\n pattern: /(\\\\{2,})\\s*\\\\end{align}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Extra space at end of block:\nDon't end an align block with backslashes`,\n }),\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-align-linebreaks\",\n selector: \"blockMath\",\n // Match any align block with double backslashes in it\n // Use [\\s\\S]* instead of .* so we match newlines as well.\n pattern: /\\\\begin{align}[\\s\\S]*\\\\\\\\[\\s\\S]+\\\\end{align}/,\n // Look for double backslashes and ensure that they are\n // followed by optional space and another pair of backslashes.\n // Note that this rule can't know where line breaks belong so\n // it can't tell whether backslashes are completely missing. It just\n // enforces that you don't have the wrong number of pairs of backslashes.\n lint: function (state, content, nodes, match) {\n let text = match[0];\n while (text.length) {\n const index = text.indexOf(\"\\\\\\\\\");\n if (index === -1) {\n // No more backslash pairs, so we found no lint\n return;\n }\n text = text.substring(index + 2);\n\n // Now we expect to find optional spaces, another pair of\n // backslashes, and more optional spaces not followed immediately\n // by another pair of backslashes.\n const nextpair = text.match(/^\\s*\\\\\\\\\\s*(?!\\\\\\\\)/);\n\n // If that does not match then we either have too few or too\n // many pairs of backslashes.\n if (!nextpair) {\n return linterWarning(\n \"Use four backslashes between lines of an align block\",\n );\n }\n\n // If it did match, then, shorten the string and continue looping\n // (because a single align block may have multiple lines that\n // all must be separated by two sets of double backslashes).\n text = text.substring(nextpair[0].length);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-empty\",\n selector: \"math, blockMath\",\n pattern: /^$/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: \"Empty math: don't use $$ in your markdown.\",\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-frac\",\n selector: \"math, blockMath\",\n pattern: /\\\\frac[ {]/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: \"Use \\\\dfrac instead of \\\\frac in your math expressions.\",\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-nested\",\n selector: \"math, blockMath\",\n pattern: /\\\\text{[^$}]*\\$[^$}]*\\$[^}]*}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Nested math:\nDon't nest math expressions inside \\\\text{} blocks`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-starts-with-space\",\n selector: \"math, blockMath\",\n pattern: /^\\s*(~|\\\\qquad|\\\\quad|\\\\,|\\\\;|\\\\:|\\\\ |\\\\!|\\\\enspace|\\\\phantom)/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\\\;, \\\\quad, or \\\\phantom`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-text-empty\",\n selector: \"math, blockMath\",\n pattern: /\\\\text{\\s*}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: \"Empty \\\\text{} block in math expression\",\n }),\n});\n","import Rule from \"../rule\";\n\n// Because no selector is specified, this rule only applies to text nodes.\n// Math and code hold their content directly and do not have text nodes\n// beneath them (unlike the HTML DOM) so this rule automatically does not\n// apply inside $$ or ``.\nexport default Rule.makeRule({\n name: \"math-without-dollars\",\n pattern: /\\\\\\w+{[^}]*}|{|}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `This looks like LaTeX:\ndid you mean to put it inside dollar signs?`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"nested-lists\",\n selector: \"list list\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation.`,\n }),\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"numeric-input-missing-label\",\n widgetType: \"numeric-input\",\n lint(widget) {\n if (!widget.options.labelText) {\n return linterWarning(`Inputs should have an aria label:\nWhile screen readers will fallback to a default label of 'Your answer', a more descriptive label would improve accessibility.`);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"numeric-input-widget-error\",\n widgetType: \"numeric-input\",\n lint(widget) {\n const issues: Array<any | string> = [];\n const answers = widget.options.answers;\n if (answers.some((answer) => answer.value == null)) {\n issues.push(\"One or more answers is empty\");\n }\n\n answers.forEach((answer, i) => {\n const formatError =\n answer.strict &&\n (!answer.answerForms || answer.answerForms.length === 0);\n if (formatError) {\n issues.push(\n `Answer ${i + 1} requires a format, but no format was selected`,\n );\n }\n });\n\n return issues;\n },\n});\n","import {makeSafeUrl} from \"@khanacademy/perseus-core\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"phet-simulation-widget-error\",\n widgetType: \"phet-simulation\",\n lint(widget) {\n if (\n makeSafeUrl(\n widget.options.url,\n \"en\",\n \"https://phet.colorado.edu\",\n ) === null\n ) {\n return linterError(\"The URL is not from the PhET domain.\");\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"python-program-widget-error\",\n widgetType: \"python-program\",\n lint(widget) {\n const errors: Array<string> = [];\n const height = widget.options.height;\n const programID = widget.options.programID;\n\n if (programID === \"\") {\n errors.push(\"The program ID is required.\");\n }\n\n if (!Number.isInteger(height) || height < 1) {\n errors.push(\"The height must be a positive integer.\");\n }\n\n return errors.map((error) => linterError(error));\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"radio-widget-error\",\n widgetType: \"radio\",\n lint(widget) {\n const choices = widget.options.choices;\n\n // Error if no choice is marked as correct\n if (!choices.some((choice) => choice.correct)) {\n return linterError(\"No choice is marked as correct.\");\n }\n\n // Error if NOTA (none of the above) and another choice are both marked as correct\n const correctChoices = choices.filter((choice) => choice.correct);\n const hasNotaCorrect = correctChoices.some(\n (choice) => choice.isNoneOfTheAbove,\n );\n\n if (hasNotaCorrect && correctChoices.length > 1) {\n return linterError(\n \"Cannot mark both None of the Above and another choice as correct.\",\n );\n }\n\n return;\n },\n});\n","import {parse, traverseContent} from \"@khanacademy/pure-markdown\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\n// There's nothing to sort with fewer than two cards.\nconst minCards = 2;\n\n// A card holding an image must hold nothing else: an image next to text,\n// math, or another image is not allowed.\nfunction hasMixedContent(card: string): boolean {\n const contentNodes: any[] = [];\n\n traverseContent(parse(card.trim(), {}), (node: any) => {\n // Markdown always wraps a card in a paragraph, so that wrapper\n // doesn't count as content.\n if (node.type !== \"paragraph\") {\n contentNodes.push(node);\n }\n });\n\n return (\n contentNodes.length > 1 &&\n contentNodes.some((node) => node.type === \"image\")\n );\n}\n\nexport default Rule.makeWidgetRule({\n name: \"sorter-widget-error\",\n widgetType: \"sorter\",\n lint(widget) {\n const issues: string[] = [];\n const correct: string[] = widget.options.correct ?? [];\n\n if (correct.length < minCards) {\n issues.push(`Sorter requires at least ${minCards} cards.`);\n }\n\n if (correct.some((card) => card.trim() === \"\")) {\n issues.push(\"Sorter cards cannot be blank.\");\n }\n\n if (correct.some(hasMixedContent)) {\n issues.push(\"Sorter cards cannot mix images with other content.\");\n }\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {SORTER_MAX_CARDS} from \"@khanacademy/perseus-core\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {PerseusSorterWidgetOptions} from \"@khanacademy/perseus-core\";\n\n// Exported for tests\nexport const sorterMaxIdealCards = 5;\nexport const sorterMaxHorizontalCards = 5;\n\nexport default Rule.makeWidgetRule({\n name: \"sorter-widget-warning\",\n widgetType: \"sorter\",\n lint(widget) {\n const warnings: string[] = [];\n const options: PerseusSorterWidgetOptions = widget.options;\n const {layout, correct = []} = options;\n\n if (correct.length > SORTER_MAX_CARDS) {\n warnings.push(\n `Sorter cannot have more than ${SORTER_MAX_CARDS} cards.`,\n );\n }\n\n if (\n layout === \"horizontal\" &&\n correct.length > sorterMaxHorizontalCards\n ) {\n warnings.push(\n `Sorter cannot have more than ${sorterMaxHorizontalCards} cards in horizontal layout.`,\n );\n }\n\n if (correct.length > sorterMaxIdealCards) {\n warnings.push(\n `Having more than ${sorterMaxIdealCards} cards in Sorter is discouraged.`,\n );\n }\n\n return warnings.map((warning) => linterWarning(warning));\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"static-widget-in-question-stem\",\n selector: \"widget\",\n lint: (state, content, nodes, match, context) => {\n if (context?.contentType !== \"exercise\") {\n return;\n }\n\n if (context.stack.includes(\"hint\")) {\n return;\n }\n\n const nodeId = state.currentNode().id;\n if (!nodeId) {\n return;\n }\n\n const widget = context?.widgets?.[nodeId];\n if (!widget) {\n return;\n }\n\n if (widget.static) {\n return linterWarning(\n `Widget in question stem is static (non-interactive).`,\n );\n }\n },\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport const MISSING_CAPTION_MESSAGE = `Table is missing a caption:\nScreen reader users rely on a caption to understand what a table contains\nbefore navigating its cells. Add one by putting a line of the form:\n|| Your caption here || directly above the table or using our Titled Table\ntemplate below.`;\n\nexport const EMPTY_CAPTION_MESSAGE = `Table caption is empty:\nThis table has a caption line, but there is no text between the || markers,\nso screen reader users hear an empty caption. Please add the appropriate\ntitle for your table.`;\n\n/**\n * Recursively collect the text of a parsed inline markdown node (or array of\n * them). A titled table's title is the output of `parseInline`, so its text\n * may be nested inside emphasis, strong, math, etc. rather than being a flat\n * string.\n */\nfunction getTextContent(node: any): string {\n if (typeof node === \"string\") {\n return node;\n }\n if (Array.isArray(node)) {\n return node.map(getTextContent).join(\"\");\n }\n if (node && typeof node === \"object\") {\n return getTextContent(node.content);\n }\n return \"\";\n}\n\n// Returns the text of a `titledTable` node's title, with no leading or\n// trailing whitespace. An empty string means the caption has no text in it.\nfunction getTitleText(titledTable: any): string {\n return getTextContent(titledTable?.title).trim();\n}\n\nexport default Rule.makeRule({\n name: \"table-missing-caption\",\n // The selector grammar has no `:not()`, so we match every table and\n // inspect its parent in `lint()`. A captioned table is parsed as a\n // `titledTable` node whose `table` property holds the table itself, so\n // the table's parent tells us whether a caption was authored.\n selector: \"table\",\n lint: function (state) {\n const parent = state.parent();\n\n if (parent?.type !== \"titledTable\") {\n return linterGuideline(MISSING_CAPTION_MESSAGE);\n }\n\n // The table has a caption line, but an author can write one with no\n // text in it (for example \"|| ||\"), which renders an empty\n // <caption> element. That is no more useful than having no caption.\n if (getTitleText(parent) === \"\") {\n return linterGuideline(EMPTY_CAPTION_MESSAGE);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"table-missing-cells\",\n selector: \"table\",\n lint: function (state, content, nodes, match) {\n const table: any = nodes[0];\n const headerLength = table.header.length;\n const rowLengths = table.cells.map((r) => r.length);\n for (let r = 0; r < rowLengths.length; r++) {\n if (rowLengths[r] !== headerLength) {\n return linterWarning(`Table rows don't match header:\nThe table header has ${headerLength} cells, but\nRow ${r + 1} has ${rowLengths[r]} cells.`);\n }\n }\n },\n});\n","import Rule from \"../rule\";\n\n// Because no selector is specified, this rule only applies to text nodes.\n// Math and code hold their content directly and do not have text nodes\n// beneath them (unlike the HTML DOM) so this rule automatically does not\n// apply inside $$ or ``.\nexport default Rule.makeRule({\n name: \"unbalanced-code-delimiters\",\n pattern: /[`~]+/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"unescaped-dollar\",\n selector: \"unescapedDollar\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\\\$`,\n }),\n});\n","import AbsoluteUrl from \"./absolute-url\";\nimport {ExplanationWidgetRule} from \"./explanation\";\nimport {\n ExplanationInGradedGroup,\n ExplanationInGradedGroupSet,\n} from \"./explanation-in-graded-group\";\nimport {\n ExpressionWidgetAnswerForms,\n ExpressionWidgetButtons,\n ExpressionWidgetCorrectAnswer,\n} from \"./expression-widget\";\nimport {FillInTheBlankRule} from \"./fill-in-the-blank\";\nimport FreeResponseWidgetError from \"./free-response-widget-error\";\nimport {GradedGroupWidgetRule} from \"./graded-group\";\nimport {GradedGroupSetWidgetRule} from \"./graded-group-set\";\nimport {GroupWidgetRule} from \"./group\";\nimport HeadingLevel1 from \"./heading-level-1\";\nimport HeadingLevelSkip from \"./heading-level-skip\";\nimport HeadingSentenceCase from \"./heading-sentence-case\";\nimport HeadingTitleCase from \"./heading-title-case\";\nimport ImageAltText from \"./image-alt-text\";\nimport ImageMarkdown from \"./image-markdown\";\nimport ImageSpacesAroundUrls from \"./image-spaces-around-urls\";\nimport ImageUrlEmpty from \"./image-url-empty\";\nimport ImageWidgetAltText from \"./image-widget-alt-text\";\nimport ImageWidgetEmptySize from \"./image-widget-empty-size\";\nimport InaccessibleWidget from \"./inaccessible-widget\";\nimport InteractiveGraphLockedFigureOob from \"./interactive-graph-locked-figure-oob\";\nimport InteractiveGraphWidgetError from \"./interactive-graph-widget-error\";\nimport LabelImageWidgetError from \"./label-image-widget-error\";\nimport LegacyGifUrl from \"./legacy-gif-url\";\nimport LinkClickHere from \"./link-click-here\";\nimport LongParagraph from \"./long-paragraph\";\nimport MatcherWidgetError from \"./matcher-widget-error\";\nimport MathAdjacent from \"./math-adjacent\";\nimport MathAlignExtraBreak from \"./math-align-extra-break\";\nimport MathAlignLinebreaks from \"./math-align-linebreaks\";\nimport MathEmpty from \"./math-empty\";\nimport MathFrac from \"./math-frac\";\nimport MathNested from \"./math-nested\";\nimport MathStartsWithSpace from \"./math-starts-with-space\";\nimport MathTextEmpty from \"./math-text-empty\";\nimport MathWithoutDollars from \"./math-without-dollars\";\nimport NestedLists from \"./nested-lists\";\nimport NumericInputMissingLabel from \"./numeric-input-missing-label\";\nimport NumericInputWidgetError from \"./numeric-input-widget-error\";\nimport PhetSimulationWidgetError from \"./phet-simulation-widget-error\";\nimport PythonProgramWidgetError from \"./python-program-widget-error\";\nimport RadioWidgetError from \"./radio-widget-error\";\nimport SorterWidgetError from \"./sorter-widget-error\";\nimport SorterWidgetWarning from \"./sorter-widget-warning\";\nimport StaticWidgetInQuestionStem from \"./static-widget-in-question-stem\";\nimport TableMissingCaption from \"./table-missing-caption\";\nimport TableMissingCells from \"./table-missing-cells\";\nimport UnbalancedCodeDelimiters from \"./unbalanced-code-delimiters\";\nimport UnescapedDollar from \"./unescaped-dollar\";\n\nimport type Rule from \"../rule\";\n\nexport function allRules(): Rule[] {\n return [\n AbsoluteUrl,\n ExplanationInGradedGroup,\n ExplanationInGradedGroupSet,\n ExplanationWidgetRule,\n ExpressionWidgetAnswerForms,\n ExpressionWidgetButtons,\n ExpressionWidgetCorrectAnswer,\n FillInTheBlankRule,\n FreeResponseWidgetError,\n GradedGroupSetWidgetRule,\n GradedGroupWidgetRule,\n GroupWidgetRule,\n HeadingLevel1,\n HeadingLevelSkip,\n HeadingSentenceCase,\n HeadingTitleCase,\n ImageAltText,\n ImageMarkdown,\n ImageSpacesAroundUrls,\n ImageUrlEmpty,\n ImageWidgetAltText,\n ImageWidgetEmptySize,\n InaccessibleWidget,\n InteractiveGraphLockedFigureOob,\n InteractiveGraphWidgetError,\n LabelImageWidgetError,\n LegacyGifUrl,\n LinkClickHere,\n LongParagraph,\n MatcherWidgetError,\n MathAdjacent,\n MathAlignExtraBreak,\n MathAlignLinebreaks,\n MathEmpty,\n MathFrac,\n MathNested,\n MathStartsWithSpace,\n MathTextEmpty,\n MathWithoutDollars,\n NestedLists,\n NumericInputMissingLabel,\n NumericInputWidgetError,\n PhetSimulationWidgetError,\n PythonProgramWidgetError,\n RadioWidgetError,\n SorterWidgetError,\n SorterWidgetWarning,\n StaticWidgetInQuestionStem,\n TableMissingCaption,\n TableMissingCells,\n UnbalancedCodeDelimiters,\n UnescapedDollar,\n ];\n}\n","/**\n * TreeTransformer is a class for traversing and transforming trees. Create a\n * TreeTransformer by passing the root node of the tree to the\n * constructor. Then traverse that tree by calling the traverse() method. The\n * argument to traverse() is a callback function that will be called once for\n * each node in the tree. This is a post-order depth-first traversal: the\n * callback is not called on the a way down, but on the way back up. That is,\n * the children of a node are traversed before the node itself is.\n *\n * The traversal callback function is passed three arguments, the node being\n * traversed, a TraversalState object, and the concatentated text content of\n * the node and all of its descendants. The TraversalState object is the most\n * most interesting argument: it has methods for querying the ancestors and\n * siblings of the node, and for deleting or replacing the node. These\n * transformation methods are why this class is a tree transformer and not\n * just a tree traverser.\n *\n * A typical tree traversal looks like this:\n *\n * new TreeTransformer(root).traverse((node, state, content) => {\n * let parent = state.parent();\n * let previous = state.previousSibling();\n * // etc.\n * });\n *\n * The traverse() method descends through nodes and arrays of nodes and calls\n * the traverse callback on each node on the way back up to the root of the\n * tree. (Note that it only calls the callback on the nodes themselves, not\n * any arrays that contain nodes.) A node is loosely defined as any object\n * with a string-valued `type` property. Objects that do not have a type\n * property are assumed to not be part of the tree and are not traversed. When\n * traversing an array, all elements of the array are examined, and any that\n * are nodes or arrays are recursively traversed. When traversing a node, all\n * properties of the object are examined and any node or array values are\n * recursively traversed. In typical parse trees, the children of a node are\n * in a `children` or `content` array, but this class is designed to handle\n * more general trees. The Perseus markdown parser, for example, produces\n * nodes of type \"table\" that have children in the `header` and `cells`\n * properties.\n *\n * CAUTION: the traverse() method does not make any attempt to detect\n * cycles. If you call it on a cyclic graph instead of a tree, it will cause\n * infinite recursion (or, more likely, a stack overflow).\n *\n * If a node has a text-valued `content` property, it is taken to be the\n * plain-text content of the node. The traverse() method concatenates these\n * content strings and passes them to the traversal callback for each\n * node. This means that the callback has access the full text content of its\n * node and all of the nodes descendants.\n *\n * See the TraversalState class for more information on what information and\n * methods are available to the traversal callback.\n **/\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\n/**\n * TreeNode represents a node in a linted parse tree.\n */\nexport type TreeNode =\n | {\n type: string;\n content: string;\n id?: string;\n widgetType?: string;\n }\n | {\n type: \"lint\";\n content: TreeNode;\n message: string;\n ruleName: string;\n blockHighlight?: boolean;\n insideTable: boolean;\n severity: number;\n id?: undefined;\n widgetType?: undefined;\n };\n\n// TraversalCallback is the type of the callback function passed to the\n// traverse() method. It is invoked with node, state, and content arguments\n// and is expected to return nothing.\ntype TraversalCallback = (\n node: TreeNode,\n state: TraversalState,\n content: string,\n) => void;\n\n// This is the TreeTransformer class described in detail at the\n// top of this file.\nexport default class TreeTransformer {\n root: TreeNode;\n\n // To create a tree transformer, just pass the root node of the tree\n constructor(root: TreeNode) {\n this.root = root;\n }\n\n // A utility function for determing whether an arbitrary value is a node\n static isNode(n: any): boolean {\n return n && typeof n === \"object\" && typeof n.type === \"string\";\n }\n\n // Determines whether a value is a node with type \"text\" and has\n // a text-valued `content` property.\n static isTextNode(n: any): boolean {\n return (\n TreeTransformer.isNode(n) &&\n n.type === \"text\" &&\n typeof n.content === \"string\"\n );\n }\n\n // This is the main entry point for the traverse() method. See the comment\n // at the top of this file for a detailed description. Note that this\n // method just creates a new TraversalState object to use for this\n // traversal and then invokes the internal _traverse() method to begin the\n // recursion.\n traverse(f: TraversalCallback): void {\n this._traverse(this.root, new TraversalState(this.root), f);\n }\n\n // Do a post-order traversal of node and its descendants, invoking the\n // callback function f() once for each node and returning the concatenated\n // text content of the node and its descendants. f() is passed three\n // arguments: the current node, a TraversalState object representing the\n // current state of the traversal, and a string that holds the\n // concatenated text of the node and its descendants.\n //\n // This private method holds all the traversal logic and implementation\n // details. Note that this method uses the TraversalState object to store\n // information about the structure of the tree.\n _traverse(\n n: TreeNode | Array<TreeNode>,\n state: TraversalState,\n f: TraversalCallback,\n ): string {\n let content = \"\";\n if (TreeTransformer.isNode(n)) {\n // If we were called on a node object, then we handle it\n // this way.\n // eslint-disable-next-line no-restricted-syntax\n const node = n as TreeNode; // safe cast; we just tested\n\n // Put the node on the stack before recursing on its children\n state._containers.push(node);\n state._ancestors.push(node);\n\n // Record the node's text content if it has any.\n // Usually this is for nodes with a type property of \"text\",\n // but other nodes types like \"math\" may also have content.\n if (typeof node.content === \"string\") {\n content = node.content;\n }\n\n // Recurse on the node. If there was content above, then there\n // probably won't be any children to recurse on, but we check\n // anyway.\n //\n // If we wanted to make the traversal completely specific to the\n // actual Perseus parse trees that we'll be dealing with we could\n // put a switch statement here to dispatch on the node type\n // property with specific recursion steps for each known type of\n // node.\n const keys = Object.keys(node);\n keys.forEach((key) => {\n // Never recurse on the type property\n if (key === \"type\") {\n return;\n }\n // Ignore properties that are null or primitive and only\n // recurse on objects and arrays. Note that we don't do a\n // isNode() check here. That is done in the recursive call to\n // _traverse(). Note that the recursive call on each child\n // returns the text content of the child and we add that\n // content to the content for this node. Also note that we\n // push the name of the property we're recursing over onto a\n // TraversalState stack.\n const value = node[key];\n if (value && typeof value === \"object\") {\n state._indexes.push(key);\n content += this._traverse(value, state, f);\n state._indexes.pop();\n }\n });\n\n // Restore the stacks after recursing on the children\n state._currentNode = state._ancestors.pop();\n state._containers.pop();\n\n // And finally call the traversal callback for this node. Note\n // that this is post-order traversal. We call the callback on the\n // way back up the tree, not on the way down. That way we already\n // know all the content contained within the node.\n f(node, state, content);\n } else if (Array.isArray(n)) {\n // If we were called on an array instead of a node, then\n // this is the code we use to recurse.\n const nodes = n;\n\n // Push the array onto the stack. This will allow the\n // TraversalState object to locate siblings of this node.\n state._containers.push(nodes);\n\n // Now loop through this array and recurse on each element in it.\n // Before recursing on an element, we push its array index on a\n // TraversalState stack so that the TraversalState sibling methods\n // can work. Note that TraversalState methods can alter the length\n // of the array, and change the index of the current node, so we\n // are careful here to test the array length on each iteration and\n // to reset the index when we pop the stack. Also note that we\n // concatentate the text content of the children.\n let index = 0;\n while (index < nodes.length) {\n state._indexes.push(index);\n content += this._traverse(nodes[index], state, f);\n // Casting to convince TypeScript that this is a number\n // eslint-disable-next-line no-restricted-syntax\n index = (state._indexes.pop() as number) + 1;\n }\n\n // Pop the array off the stack. Note, however, that we do not call\n // the traversal callback on the array. That function is only\n // called for nodes, not arrays of nodes.\n state._containers.pop();\n }\n\n // The _traverse() method always returns the text content of\n // this node and its children. This is the one piece of state that\n // is not tracked in the TraversalState object.\n return content;\n }\n}\n\n// An instance of this class is passed to the callback function for\n// each node traversed. The class itself is not exported, but its\n// methods define the API available to the traversal callback.\n\n/**\n * This class represents the state of a tree traversal. An instance is created\n * by the traverse() method of the TreeTransformer class to maintain the state\n * for that traversal, and the instance is passed to the traversal callback\n * function for each node that is traversed. This class is not intended to be\n * instantiated directly, but is exported so that its type can be used for\n * type annotaions.\n **/\nexport class TraversalState {\n // The root node of the tree being traversed\n root: TreeNode;\n\n // These are internal state properties. Use the accessor methods defined\n // below instead of using these properties directly. Note that the\n // _containers and _indexes stacks can have two different types of\n // elements, depending on whether we just recursed on an array or on a\n // node. This is hard for TypeScript to deal with, so you'll see a number of\n // type casts through the any type when working with these two properties.\n _currentNode: TreeNode | null | undefined;\n _containers: Stack<TreeNode | Array<TreeNode>>;\n _indexes: Stack<string | number>;\n _ancestors: Stack<TreeNode>;\n\n // The constructor just stores the root node and creates empty stacks.\n constructor(root: TreeNode) {\n this.root = root;\n\n // When the callback is called, this property will hold the\n // node that is currently being traversed.\n this._currentNode = null;\n\n // This is a stack of the objects and arrays that we've\n // traversed through before reaching the currentNode.\n // It is different than the ancestors array.\n this._containers = new Stack();\n\n // This stack has the same number of elements as the _containers\n // stack. The last element of this._indexes[] is the index of\n // the current node in the object or array that is the last element\n // of this._containers[]. If the last element of this._containers[] is\n // an array, then the last element of this stack will be a number.\n // Otherwise if the last container is an object, then the last index\n // will be a string property name.\n this._indexes = new Stack();\n\n // This is a stack of the ancestor nodes of the current one.\n // It is different than the containers[] stack because it only\n // includes nodes, not arrays.\n this._ancestors = new Stack();\n }\n\n /**\n * Return the current node in the traversal. Any time the traversal\n * callback is called, this method will return the name value as the\n * first argument to the callback.\n */\n currentNode(): TreeNode {\n return this._currentNode || this.root;\n }\n\n /**\n * Return the parent of the current node, if there is one, or null.\n */\n parent(): TreeNode | null | undefined {\n return this._ancestors.top();\n }\n\n /**\n * Return an array of ancestor nodes. The first element of this array is\n * the same as this.parent() and the last element is the root node. If we\n * are currently at the root node, the the returned array will be empty.\n * This method makes a copy of the internal state, so modifications to the\n * returned array have no effect on the traversal.\n */\n ancestors(): ReadonlyArray<TreeNode> {\n return this._ancestors.values();\n }\n\n /**\n * Return the next sibling of this node, if it has one, or null otherwise.\n */\n nextSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n\n // If we're at the root of the tree or if the parent is an\n // object instead of an array, then there are no siblings.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!siblings || !Array.isArray(siblings)) {\n return null;\n }\n\n // The top index is a number because the top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (siblings.length > index + 1) {\n return siblings[index + 1];\n }\n return null; // There is no next sibling\n }\n\n /**\n * Return the previous sibling of this node, if it has one, or null\n * otherwise.\n */\n previousSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n\n // If we're at the root of the tree or if the parent is an\n // object instead of an array, then there are no siblings.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!siblings || !Array.isArray(siblings)) {\n return null;\n }\n\n // The top index is a number because the top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (index > 0) {\n return siblings[index - 1];\n }\n return null; // There is no previous sibling\n }\n\n /**\n * Remove the next sibling node (if there is one) from the tree. Returns\n * the removed sibling or null. This method makes it easy to traverse a\n * tree and concatenate adjacent text nodes into a single node.\n */\n removeNextSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (siblings && Array.isArray(siblings)) {\n // top index is a number because top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (siblings.length > index + 1) {\n return siblings.splice(index + 1, 1)[0];\n }\n }\n return null;\n }\n\n /**\n * Replace the current node in the tree with the specified nodes. If no\n * nodes are passed, this is a node deletion. If one node (or array) is\n * passed, this is a 1-for-1 replacement. If more than one node is passed\n * then this is a combination of deletion and insertion. The new node or\n * nodes will not be traversed, so this method can safely be used to\n * reparent the current node node beneath a new parent.\n *\n * This method throws an error if you attempt to replace the root node of\n * the tree.\n */\n replace(...replacements: ReadonlyArray<TreeNode>): void {\n const parent = this._containers.top();\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!parent) {\n throw new PerseusError(\n \"Can't replace the root of the tree\",\n Errors.Internal,\n );\n }\n\n // The top of the container stack is either an array or an object\n // and the top of the indexes stack is a corresponding array index\n // or object property. This is hard for TypeScript, so we have to do some\n // unsafe casting and be careful when we use which cast version\n if (Array.isArray(parent)) {\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n // For an array parent we just splice the new nodes in\n parent.splice(index, 1, ...replacements);\n // Adjust the index to account for the changed array length.\n // We don't want to traverse any of the newly inserted nodes.\n this._indexes.pop();\n this._indexes.push(index + replacements.length - 1);\n } else {\n // eslint-disable-next-line no-restricted-syntax\n const property = this._indexes.top() as string;\n // For an object parent we care how many new nodes there are\n if (replacements.length === 0) {\n // Deletion\n delete parent[property];\n } else if (replacements.length === 1) {\n // Replacement\n parent[property] = replacements[0];\n } else {\n // Replace one node with an array of nodes\n parent[property] = replacements;\n }\n }\n }\n\n /**\n * Returns true if the current node has a previous sibling and false\n * otherwise. If this method returns false, then previousSibling() will\n * return null, and goToPreviousSibling() will throw an error.\n */\n hasPreviousSibling(): boolean {\n return (\n Array.isArray(this._containers.top()) &&\n // eslint-disable-next-line no-restricted-syntax\n (this._indexes.top() as number) > 0\n );\n }\n\n /**\n * Modify this traversal state object to have the state it would have had\n * when visiting the previous sibling. Note that you may want to use\n * clone() to make a copy before modifying the state object like this.\n * This mutator method is not typically used during ordinary tree\n * traversals, but is used by the Selector class for matching multi-node\n * selectors.\n */\n goToPreviousSibling(): void {\n if (!this.hasPreviousSibling()) {\n throw new PerseusError(\n \"goToPreviousSibling(): node has no previous sibling\",\n Errors.Internal,\n );\n }\n\n this._currentNode = this.previousSibling();\n // Since we know that we have a previous sibling, we know that\n // the value on top of the stack is a number, but we have to do\n // this unsafe cast because TypeScript doesn't know that.\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.pop() as number;\n this._indexes.push(index - 1);\n }\n\n /**\n * Returns true if the current node has an ancestor and false otherwise.\n * If this method returns false, then the parent() method will return\n * null and goToParent() will throw an error\n */\n hasParent(): boolean {\n return this._ancestors.size() !== 0;\n }\n\n /**\n * Modify this object to look like it will look when we (later) visit the\n * parent node of this node. You should not modify the instance passed to\n * the tree traversal callback. Instead, make a copy with the clone()\n * method and modify that. This mutator method is not typically used\n * during ordinary tree traversals, but is used by the Selector class for\n * matching multi-node selectors that involve parent and ancestor\n * selectors.\n */\n goToParent(): void {\n if (!this.hasParent()) {\n throw new PerseusError(\n \"goToParent(): node has no ancestor\",\n Errors.NotAllowed,\n );\n }\n\n this._currentNode = this._ancestors.pop();\n\n // We need to pop the containers and indexes stacks at least once\n // and more as needed until we restore the invariant that\n // this._containers.top()[this.indexes.top()] === this._currentNode\n //\n while (\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n this._containers.size() &&\n this._containers.top()[this._indexes.top()] !== this._currentNode\n ) {\n this._containers.pop();\n this._indexes.pop();\n }\n }\n\n /**\n * Return a new TraversalState object that is a copy of this one.\n * This method is useful in conjunction with the mutating methods\n * goToParent() and goToPreviousSibling().\n */\n clone(): TraversalState {\n const clone = new TraversalState(this.root);\n clone._currentNode = this._currentNode;\n clone._containers = this._containers.clone();\n clone._indexes = this._indexes.clone();\n clone._ancestors = this._ancestors.clone();\n return clone;\n }\n\n /**\n * Returns true if this TraversalState object is equal to that\n * TraversalState object, or false otherwise. This method exists\n * primarily for use by our unit tests.\n */\n equals(that: TraversalState): boolean {\n return (\n this.root === that.root &&\n this._currentNode === that._currentNode &&\n this._containers.equals(that._containers) &&\n this._indexes.equals(that._indexes) &&\n this._ancestors.equals(that._ancestors)\n );\n }\n}\n\n/**\n * This class is an internal utility that just treats an array as a stack\n * and gives us a top() method so we don't have to write expressions like\n * `ancestors[ancestors.length-1]`. The values() method automatically\n * copies the internal array so we don't have to worry about client code\n * modifying our internal stacks. The use of this Stack abstraction makes\n * the TraversalState class simpler in a number of places.\n */\nclass Stack<T> {\n stack: Array<T>;\n\n constructor(array?: ReadonlyArray<T> | null) {\n this.stack = array ? array.slice(0) : [];\n }\n\n /** Push a value onto the stack. */\n push(v: T): void {\n this.stack.push(v);\n }\n\n /** Pop a value off of the stack. */\n pop(): T {\n // @ts-expect-error - TS2322 - Type 'T | undefined' is not assignable to type 'T'.\n return this.stack.pop();\n }\n\n /** Return the top value of the stack without popping it. */\n top(): T {\n return this.stack[this.stack.length - 1];\n }\n\n /** Return a copy of the stack as an array */\n values(): ReadonlyArray<T> {\n return this.stack.slice(0);\n }\n\n /** Return the number of elements in the stack */\n size(): number {\n return this.stack.length;\n }\n\n /** Return a string representation of the stack */\n toString(): string {\n return this.stack.toString();\n }\n\n /** Return a shallow copy of the stack */\n clone(): Stack<T> {\n return new Stack(this.stack);\n }\n\n /**\n * Compare this stack to another and return true if the contents of\n * the two arrays are the same.\n */\n equals(that: Stack<T>): boolean {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!that || !that.stack || that.stack.length !== this.stack.length) {\n return false;\n }\n for (let i = 0; i < this.stack.length; i++) {\n if (this.stack[i] !== that.stack[i]) {\n return false;\n }\n }\n return true;\n }\n}\n","import {allRules} from \"./rules/all-rules\";\nimport TreeTransformer from \"./tree-transformer\";\n\nimport type {LinterIssue} from \"./rule\";\nimport type {TreeNode} from \"./tree-transformer\";\n\n/**\n * Run the Perseus linter over the specified markdown parse tree, with the\n * specified context object, and return a (possibly empty) array of lint\n * warning objects. If the highlight argument is true, this function also\n * modifies the parse tree to add \"lint\" nodes that can be visually rendered,\n * highlighting the problems for the user. The optional rules argument is an\n * array of Rule objects specifying which lint rules should be applied to this\n * parse tree. When omitted, a default set of rules is used.\n *\n * The context object may have additional properties that some lint rules\n * require:\n *\n * context.content is the source content string that was parsed to create\n * the parse tree.\n *\n * context.widgets is the widgets object associated\n * with the content string\n */\nexport function runLinter(\n tree: any,\n context: any,\n highlight: boolean,\n): ReadonlyArray<LinterIssue> {\n const issues: Array<LinterIssue> = [];\n const tt = new TreeTransformer(tree);\n\n // The markdown parser often outputs adjacent text nodes. We\n // coalesce them before linting for efficiency and accuracy.\n tt.traverse((node, state, content) => {\n if (TreeTransformer.isTextNode(node)) {\n let next = state.nextSibling();\n while (TreeTransformer.isTextNode(next)) {\n // @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'.\n node.content += next.content;\n state.removeNextSibling();\n next = state.nextSibling();\n }\n }\n });\n\n // HTML tables are complicated, and the CSS we use in\n // ../components/lint.jsx to display lint does not work to\n // correctly position the lint indicators in the margin when the\n // lint is inside a table. So as a workaround we keep track of all\n // the lint that appears within a table and move it up to the\n // table element itself.\n //\n // It is not ideal to have to do this here,\n // but it is cleaner here than fixing up the lint during rendering\n // in perseus-markdown.jsx. If our lint display was simpler and\n // did not require indicators in the margin, this wouldn't be a\n // problem. Or, if we modified the lint display stuff so that\n // indicator positioning and tooltip display were both handled\n // with JavaScript (instead of pure CSS), then we could avoid this\n // issue too. But using JavaScript has its own downsides: there is\n // risk that the linter JavaScript would interfere with\n // widget-related Javascript.\n let tableIssues: LinterIssue[] = [];\n let insideTable = false;\n\n // Traverse through the nodes of the parse tree. At each node, loop\n // through the array of lint rules and check whether there is a\n // lint violation at that node.\n tt.traverse((node, state, content) => {\n const nodeIssues: LinterIssue[] = [];\n\n // Generate a stack so we can identify our position in the tree in\n // lint rules\n const stack = [...context.stack];\n stack.push(node.type);\n\n const nodeContext = {\n ...context,\n stack: stack.join(\".\"),\n } as const;\n\n allRules().forEach((rule) => {\n const ruleIssues = rule.check(node, state, content, nodeContext);\n for (const issue of ruleIssues) {\n // The start and end locations are relative to this\n // particular node, and so are not generally very useful.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (issue.start || issue.end) {\n issue.target = content.substring(issue.start, issue.end);\n }\n\n // Add the issue to the list of all lint we've found\n issues.push(issue);\n\n // If we're going to be highlighting lint, then we also\n // need to keep track of issues specific to this node.\n if (highlight) {\n nodeIssues.push(issue);\n }\n }\n });\n\n // If we're not highlighting lint in the tree, then we're done\n // traversing this node.\n if (!highlight) {\n return;\n }\n\n // If the node we are currently at is a table, and there was lint\n // inside the table, then we want to add that lint here\n if (node.type === \"table\") {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (tableIssues.length) {\n nodeIssues.push(...tableIssues);\n }\n\n // We're not in a table anymore, and don't have to remember\n // the issues for the table\n insideTable = false;\n tableIssues = [];\n } else if (!insideTable) {\n // Otherwise, if we are not already inside a table, check\n // to see if we've entered one. Because this is a post-order\n // traversal we'll see the table contents before the table itself.\n // Note that once we're inside the table, we don't have to\n // do this check each time... We can just wait until we ascend\n // up to the table, then we'll know we're out of it.\n insideTable = state.ancestors().some((n) => n.type === \"table\");\n }\n\n // If we are inside a table and there were any issues on\n // this node, then we need to save the issues for display\n // on the table itself\n if (insideTable && nodeIssues.length > 0) {\n tableIssues.push(...nodeIssues);\n }\n\n // If there were any issues on this node, and if we're highlighting\n // lint, then reparent the node so we can highlight it. Note that\n // a single node can have multiple issues. If this happends we\n // concatenate the issues and newline separate them. (The lint.jsx\n // component that displays the issues may want to convert the\n // newlines into <br> tags.) We also provide a lint rule name\n // so that lint.jsx can link to a document that provides more details\n // on that particular lint rule. If there is more than one issue\n // we only link to the first rule, however.\n //\n // Note that even if we're inside a table, we still reparent the\n // linty node so that it can be highlighted. We just make a note\n // of whether this lint is inside a table or not.\n if (nodeIssues.length > 0) {\n nodeIssues.sort((a, b) => {\n return a.severity - b.severity;\n });\n\n if (node.type !== \"text\" || nodeIssues.length > 1) {\n // If the linty node is not a text node, or if there is more\n // than one issue on a text node, then reparent the entire\n // node under a new lint node and put the issues there.\n state.replace({\n type: \"lint\",\n content: node,\n message: nodeIssues.map((w) => w.message).join(\"\\n\\n\"),\n ruleName: nodeIssues[0].rule,\n blockHighlight: nodeContext.blockHighlight,\n insideTable: insideTable,\n severity: nodeIssues[0].severity,\n });\n } else {\n //\n // Otherwise, it is a single issue on a text node, and we\n // only want to highlight the actual linty part of that string\n // of text. So we want to replace the text node with (in the\n // general case) three nodes:\n //\n // 1) A new text node that holds the non-linty prefix\n //\n // 2) A lint node that is the parent of a new text node\n // that holds the linty part\n //\n // 3) A new text node that holds the non-linty suffix\n //\n // If the lint begins and/or ends at the boundaries of the\n // original text node, then nodes 1 and/or 3 won't exist, of\n // course.\n //\n // Note that we could generalize this to work with multple\n // issues on a text node as long as the issues are\n // non-overlapping. Hopefully, though, multiple issues in a\n // single text node will be rare in practice. Also, we don't\n // have a good way to display multiple lint indicators on a\n // single line, so keeping them combined in that case might\n // be the best thing, anyway.\n //\n const content = node.content; // Text nodes have content\n const issue = nodeIssues[0]; // There is only one issue.\n // These are the lint boundaries within the content\n const start = issue.start;\n const end = issue.end;\n const prefix = content.substring(0, start);\n const lint = content.substring(start, end);\n const suffix = content.substring(end);\n const replacements: TreeNode[] = []; // What we'll replace the node with\n\n // The prefix text node, if there is one\n if (prefix) {\n replacements.push({\n type: \"text\",\n content: prefix,\n });\n }\n\n // The lint node wrapped around the linty text\n replacements.push({\n type: \"lint\",\n content: {\n type: \"text\",\n content: lint,\n },\n message: issue.message,\n ruleName: issue.rule,\n insideTable: insideTable,\n severity: issue.severity,\n });\n\n // The suffix node, if there is one\n if (suffix) {\n replacements.push({\n type: \"text\",\n content: suffix,\n });\n }\n\n // Now replace the lint text node with the one to three\n // nodes in the replacement array\n state.replace(...replacements);\n }\n }\n });\n\n return issues;\n}\n","export {libVersion} from \"./version\";\n\nexport {linterContextDefault} from \"./proptypes\";\n\nexport {default as Rule} from \"./rule\";\nexport {runLinter} from \"./run-linter\";\n\nexport type {LinterIssue} from \"./rule\";\nexport type {LinterContextProps} from \"./types\";\n\nexport function pushContextStack(context: any, name: string): any {\n const stack = context.stack || [];\n return {\n ...context,\n stack: stack.concat(name),\n };\n}\n\nexport {\n lintPerseusArticle,\n lintPerseusItem,\n lintPerseusRenderer,\n type ItemLinterIssues,\n} from \"./lint-content\";\n"],"mappings":";;;;;;IAMM4C,IAAU,+BACHC,IAAa;AAE1BC,EAAgCF,GAASC,CAAU;;;ACPnD,IAAaE,KAA2C;CACpD,aAAa;CACb,eAAe;CACf,OAAO,CAAC;AACZ,GCAaC,IAAW;CACpB,OAAO;CACP,SAAS;CACT,WAAW;AACf;AAWA,SAAgB,cAAc,GAAiB,GAA6B;CACxE,OAAO;EACH;EACA,UAAUA,EAAS;EACnB,GAAGC;CACP;AACJ;AAEA,SAAgB,YAAY,GAAiB,GAA6B;CACtE,OAAO;EACH;EACA,UAAUD,EAAS;EACnB,GAAGC;CACP;AACJ;AAEA,SAAgB,gBAAgB,GAAiB,GAA6B;CAC1E,OAAO;EACH;EACA,UAAUD,EAAS;EACnB,GAAGC;CACP;AACJ;;;ACmDA,IAAqB,WAArB,MAA8B;CAC1B,OAAO,MAAM,GAAgC;EACzC,OAAO,IAAIC,EAAOC,CAAY,CAAC,CAAC,MAAM;CAC1C;CAOA,MAAM,GAAmE;EACrE,MAAM,IAAIC,EACN,8CACAC,EAAO,UACX;CACJ;CAMA,WAAmB;EACf,OAAO;CACX;AACJ,GAWMH,IAAN,MAAM,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MAAM;IACN,SAAS5M;IACT,SAAS4M,EAAW,KAAK,MAAM3H,EAAE,OAAO,CAAC,CAAC,KAAK,MAAM;IACrD,UAAU2H,EAAW,EAAE,CAAC;IACxB,gBAAgBE,EAAY;IACf;IACb,UAAUF,EAAW,EAAE,CAAC;GAC5B,CAAC;QACE;IA0BH,IAAM9L,IAAUd,EAAK,SACf4D,IAAQgJ,EAAW,IAEnBQ,IAAQxJ,EAAM,OACdyJ,IAAMzJ,EAAM,KACZ0J,IAASxM,EAAQ,UAAU,GAAGsM,CAAK,GACnC1M,IAAOI,EAAQ,UAAUsM,GAAOC,CAAG,GACnCE,IAASzM,EAAQ,UAAUuM,CAAG,GAC9BpB,IAA2B,CAAC;IAiClC,AA9BIqB,KACArB,EAAa,KAAK;KACd,MAAM;KACN,SAASqB;IACb,CAAC,GAILrB,EAAa,KAAK;KACd,MAAM;KACN,SAAS;MACL,MAAM;MACN,SAASvL;KACb;KACA,SAASkD,EAAM;KACf,UAAUA,EAAM;KACH;KACb,UAAUA,EAAM;IACpB,CAAC,GAGG2J,KACAtB,EAAa,KAAK;KACd,MAAM;KACN,SAASsB;IACb,CAAC,GAKLzN,EAAM,QAAQ,GAAGmM,CAAY;GACjC;EACJ;CACJ,CAAC,GAEMvI;AACX;;;ACxOA,SAAgB,iBAAiB,GAAc,GAAmB;CAC9D,IAAMmJ,IAAQhM,EAAQ,SAAS,CAAC;CAChC,OAAO;EACH,GAAGA;EACH,OAAOgM,EAAM,OAAOpM,CAAI;CAC5B;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["kvector","AbsoluteUrl","FreeResponseWidgetError","HeadingLevel1","HeadingLevelSkip","HeadingSentenceCase","HeadingTitleCase","ImageAltText","ImageMarkdown","ImageSpacesAroundUrls","ImageUrlEmpty","ImageWidgetAltText","ImageWidgetEmptySize","InaccessibleWidget","InteractiveGraphLockedFigureOob","InteractiveGraphWidgetError","LabelImageWidgetError","LegacyGifUrl","LinkClickHere","LongParagraph","MatcherWidgetError","MathAdjacent","MathAlignExtraBreak","MathAlignLinebreaks","MathEmpty","MathFrac","MathNested","MathStartsWithSpace","MathTextEmpty","MathWithoutDollars","NestedLists","NumericInputMissingLabel","NumericInputWidgetError","PhetSimulationWidgetError","PythonProgramWidgetError","RadioWidgetError","SorterWidgetError","SorterWidgetWarning","StaticWidgetInQuestionStem","TableMissingCaption","TableMissingCells","UnbalancedCodeDelimiters","UnescapedDollar","KAS","libName","libVersion","addLibraryVersionToPerseusDebug","linterContextDefault","Severity","options","Parser","selectorText","PerseusError","Errors","s","c","ts","token","treeSelectors","ns","t","message","selectors","i","result","state","type","node","left","right","rightResult","leftResult","_Rule","Rule","selector","pattern","name","lint","widgetId","widgetInfo","context","content","error","location","rawLintOutput","selectorMatch","traversalState","patternMatch","lastSlash","expression","flags","match","index","input","HOSTNAME","url","absolute_url_default","nodes","hostname","parsedPerseusItem","hint","parsedPerseusArticle","section","parse","parsedPerseusRenderer","ExplanationWidgetRule","widget","widgets","instructions","ExplanationInGradedGroup","ExplanationInGradedGroupSet","groupNumbers","group","groupNumber","set","stringToButtonSet","ExpressionWidgetButtons","answers","buttons","answer","str","ExpressionWidgetCorrectAnswer","answerForms","form","ExpressionWidgetAnswerForms","issues","ix","issue","FillInTheBlankRule","rWidgetRule","free_response_widget_error_default","question","contentType","hintIssues","GradedGroupWidgetRule","GradedGroupSetWidgetRule","gradedGroup","n","GroupWidgetRule","heading_level_1_default","heading_level_skip_default","currentHeading","previousHeading","heading_sentence_case_default","littleWords","word","heading_title_case_default","words","w","image_alt_text_default","image","image_markdown_default","parsedMarkdown","hasInlineImageNode","traverseContent","image_spaces_around_urls_default","image_url_empty_default","image_widget_alt_text_default","alt","image_widget_empty_size_default","width","height","inaccessible_widget_default","widgetType","CoreWidgetRegistry","interactive_graph_locked_figure_oob_default","warnings","figure","lockedFigures","range","figureType","isSinglePoint","warning","x","y","xMin","xMax","yMin","yMax","point","cx","cy","rx","ry","interactive_graph_widget_error_default","vector","correct","graph","asymptoteY","asymptote","minY","coords","maxY","g","labels","l","expected","label_image_widget_error_default","choices","imageUrl","imageAlt","markers","numNoAnswers","numNoLabels","marker","LEGACY_HOSTNAME","legacy_gif_url_default","link_click_here_default","long_paragraph_default","matcher_widget_error_default","math_adjacent_default","math_align_extra_break_default","math_align_linebreaks_default","text","nextpair","math_empty_default","math_frac_default","math_nested_default","math_starts_with_space_default","math_text_empty_default","math_without_dollars_default","nested_lists_default","numeric_input_missing_label_default","numeric_input_widget_error_default","phet_simulation_widget_error_default","makeSafeUrl","python_program_widget_error_default","errors","radio_widget_error_default","choice","correctChoices","minCards","contentNodes","card","sorter_widget_error_default","sorter_widget_warning_default","SORTER_MAX_CARDS","layout","static_widget_in_question_stem_default","nodeId","MISSING_CAPTION_MESSAGE","EMPTY_CAPTION_MESSAGE","titledTable","table","cell","table_missing_caption_default","parent","table_missing_cells_default","headerLength","rowLengths","r","unbalanced_code_delimiters_default","unescaped_dollar_default","TreeTransformer","root","TraversalState","f","key","value","Stack","siblings","replacements","property","clone","that","array","v","tt","tree","next","tableIssues","insideTable","nodeIssues","stack","nodeContext","ruleIssues","rule","highlight","a","b","start","end","prefix","suffix"],"sources":["../src/version.ts","../src/proptypes.ts","../src/lint.ts","../src/selector.ts","../src/rule.ts","../src/rules/lint-utils.ts","../src/rules/absolute-url.ts","../src/lint-content.ts","../src/rules/explanation.ts","../src/rules/explanation-in-graded-group.ts","../src/rules/expression-widget.ts","../src/rules/fill-in-the-blank.ts","../src/rules/free-response-widget-error.ts","../src/rules/lint-graded-group.ts","../src/rules/graded-group.ts","../src/rules/graded-group-set.ts","../src/rules/group.ts","../src/rules/heading-level-1.ts","../src/rules/heading-level-skip.ts","../src/rules/heading-sentence-case.ts","../src/rules/heading-title-case.ts","../src/rules/image-alt-text.ts","../src/rules/image-markdown.ts","../src/rules/image-spaces-around-urls.ts","../src/rules/image-url-empty.ts","../src/rules/image-widget-alt-text.ts","../src/rules/image-widget-empty-size.ts","../src/rules/inaccessible-widget.ts","../src/rules/interactive-graph-locked-figure-oob.ts","../src/rules/interactive-graph-widget-error.ts","../src/rules/label-image-widget-error.ts","../src/rules/legacy-gif-url.ts","../src/rules/link-click-here.ts","../src/rules/long-paragraph.ts","../src/rules/matcher-widget-error.ts","../src/rules/math-adjacent.ts","../src/rules/math-align-extra-break.ts","../src/rules/math-align-linebreaks.ts","../src/rules/math-empty.ts","../src/rules/math-frac.ts","../src/rules/math-nested.ts","../src/rules/math-starts-with-space.ts","../src/rules/math-text-empty.ts","../src/rules/math-without-dollars.ts","../src/rules/nested-lists.ts","../src/rules/numeric-input-missing-label.ts","../src/rules/numeric-input-widget-error.ts","../src/rules/phet-simulation-widget-error.ts","../src/rules/python-program-widget-error.ts","../src/rules/radio-widget-error.ts","../src/rules/sorter-widget-error.ts","../src/rules/sorter-widget-warning.ts","../src/rules/static-widget-in-question-stem.ts","../src/rules/table-missing-caption.ts","../src/rules/table-missing-cells.ts","../src/rules/unbalanced-code-delimiters.ts","../src/rules/unescaped-dollar.ts","../src/rules/all-rules.ts","../src/tree-transformer.ts","../src/run-linter.ts","../src/index.ts"],"sourcesContent":["// This file is processed by the Vite build to inject the production version\n// number during the release build.\n// In dev, you'll never see the version number.\n\nimport {addLibraryVersionToPerseusDebug} from \"@khanacademy/perseus-utils\";\n\nconst libName = \"@khanacademy/perseus-linter\";\nexport const libVersion = \"__lib_version__\";\n\naddLibraryVersionToPerseusDebug(libName, libVersion);\n","import type {LinterContextProps} from \"./types\";\n\nexport const linterContextDefault: LinterContextProps = {\n contentType: \"\",\n highlightLint: false,\n stack: [],\n};\n","export interface LintOptions {\n /** Indices into the content string where the issue occurs */\n location?: {start: number; end: number};\n metadata?: Record<string, any>;\n}\n\nexport const Severity = {\n ERROR: 1,\n WARNING: 2,\n GUIDELINE: 3,\n};\n\n/**\n * The type returned by the lint detection function passed to the Rule\n * constructor.\n */\nexport interface Lint extends LintOptions {\n message: string;\n severity: number;\n}\n\nexport function linterWarning(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.WARNING,\n ...options,\n };\n}\n\nexport function linterError(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.ERROR,\n ...options,\n };\n}\n\nexport function linterGuideline(message: string, options?: LintOptions): Lint {\n return {\n message,\n severity: Severity.GUIDELINE,\n ...options,\n };\n}\n","/**\n * The Selector class implements a CSS-like system for matching nodes in a\n * parse tree based on the structure of the tree. Create a Selector object by\n * calling the static Selector.parse() method on a string that describes the\n * tree structure you want to match. For example, if you want to find text\n * nodes that are direct children of paragraph nodes that immediately follow\n * heading nodes, you could create an appropriate selector like this:\n *\n * selector = Selector.parse(\"heading + paragraph > text\");\n *\n * Recall from the TreeTransformer class, that we consider any object with a\n * string-valued `type` property to be a tree node. The words \"heading\",\n * \"paragraph\" and \"text\" in the selector string above specify node types and\n * will match nodes in a parse tree that have `type` properties with those\n * values.\n *\n * Selectors are designed for use during tree traversals done with the\n * TreeTransformer traverse() method. To test whether the node currently being\n * traversed matches a selector, simply pass the TraversalState object to the\n * match() method of the Selector object. If the node does not match the\n * selector, match() returns null. If it does match, then match() returns an\n * array of nodes that match the selector. In the example above the first\n * element of the array would be the node the heading node, the second would\n * be the paragraph node that follows it, and the third would be the text node\n * that is a child of the paragraph. The last element of a returned array of\n * nodes is always equal to the current node of the tree traversal.\n *\n * Code that uses a selector might look like this:\n *\n * matchingNodes = selector.match(state);\n * if (matchingNodes) {\n * let heading = matchingNodes[0];\n * let text = matchingNodes[2];\n * // do something with those nodes\n * }\n *\n * The Selector.parse() method recognizes a grammar that is similar to CSS\n * selectors:\n *\n * selector := treeSelector (, treeSelector)*\n *\n * A selector is one or more comma-separated treeSelectors. A node matches\n * the selector if it matches any of the treeSelectors.\n *\n * treeSelector := (treeSelector combinator)? nodeSelector\n *\n * A treeSelector is a nodeSelector optionally preceeded by a combinator\n * and another tree selector. The tree selector matches if the current node\n * matches the node selector and a sibling or ancestor (depending on the\n * combinator) of the current node matches the optional treeSelector.\n *\n * combinator := ' ' | '>' | '+' | '~' // standard CSS3 combinators\n *\n * A combinator is a space or punctuation character that specifies the\n * relationship between two nodeSelectors. A space between two\n * nodeSelectors means that the first selector much match an ancestor of\n * the node that matches the second selector. A '>' character means that\n * the first selector must match the parent of the node matched by the\n * second. The '~' combinator means that the first selector must match a\n * previous sibling of the node matched by the second. And the '+' selector\n * means that first selector must match the immediate previous sibling of\n * the node that matched the second.\n *\n * nodeSelector := <IDENTIFIER> | '*'\n *\n * A nodeSelector is simply an identifier (a letter followed by any number\n * of letters, digits, hypens, and underscores) or the wildcard asterisk\n * character. A wildcard node selector matches any node. An identifier\n * selector matches any node that has a `type` property whose value matches\n * the identifier.\n *\n * If you call Selector.parse() on a string that does not match this grammar,\n * it will throw an exception\n *\n * Implementation Note: this file exports a very simple Selector class but all\n * the actual work is done in various internal classes. The Parser class\n * parses the string representation of a selector into a parse tree that\n * consists of instances of various subclasses of the Selector class. It is\n * these subclasses that implement the selector matching logic, often\n * depending on features of the TraversalState object from the TreeTransformer\n * traversal.\n */\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\nimport type {TreeNode, TraversalState} from \"./tree-transformer\";\n\n/**\n * This is the base class for all Selector types. The key method that all\n * selector subclasses must implement is match(). It takes a TraversalState\n * object (from a TreeTransformer traversal) and tests whether the selector\n * matches at the current node. See the comment at the start of this file for\n * more details on the match() method.\n */\nexport default class Selector {\n static parse(selectorText: string): Selector {\n return new Parser(selectorText).parse();\n }\n\n /**\n * Return an array of the nodes that matched or null if no match.\n * This is the base class so we just throw an exception. All Selector\n * subclasses must provide an implementation of this method.\n */\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n throw new PerseusError(\n \"Selector subclasses must implement match()\",\n Errors.NotAllowed,\n );\n }\n\n /**\n * Selector subclasses all define a toString() method primarily\n * because it makes it easy to write parser tests.\n */\n toString(): string {\n return \"Unknown selector class\";\n }\n}\n\n/**\n * This class implements a parser for the selector grammar. Pass the source\n * text to the Parser() constructor, and then call the parse() method to\n * obtain a corresponding Selector object. parse() throws an exception\n * if there are syntax errors in the selector.\n *\n * This class is not exported, and you don't need to use it directly.\n * Instead call the static Selector.parse() method.\n */\nclass Parser {\n static TOKENS: RegExp; // We do lexing with a simple regular expression\n tokens: ReadonlyArray<string>; // The array of tokens\n tokenIndex: number; // Which token in the array we're looking at now\n\n constructor(s: string) {\n // Normalize whitespace:\n // - remove leading and trailing whitespace\n // - replace runs of whitespace with single space characters\n s = s.trim().replace(/\\s+/g, \" \");\n // Convert the string to an array of tokens. Note that the TOKENS\n // pattern ignores spaces that do not appear before identifiers\n // or the * wildcard.\n this.tokens = s.match(Parser.TOKENS) || [];\n this.tokenIndex = 0;\n }\n\n // Return the next token or the empty string if there are no more\n nextToken(): string {\n return this.tokens[this.tokenIndex] || \"\";\n }\n\n // Increment the token index to \"consume\" the token we were looking at\n // and move on to the next one.\n consume(): void {\n this.tokenIndex++;\n }\n\n // Return true if the current token is an identifier or false otherwise\n isIdentifier(): boolean {\n // The Parser.TOKENS regexp ensures that we only have to check\n // the first character of a token to know what kind of token it is.\n const c = this.tokens[this.tokenIndex][0];\n return (c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\");\n }\n\n // Consume space tokens until the next token is not a space.\n skipSpace(): void {\n while (this.nextToken() === \" \") {\n this.consume();\n }\n }\n\n // Parse a comma-separated sequence of tree selectors. This is the\n // entry point for the Parser class and the only method that clients\n // ever need to call.\n parse(): Selector {\n // We expect at least one tree selector\n const ts = this.parseTreeSelector();\n\n // Now see what's next\n let token = this.nextToken();\n\n // If there is no next token then we're done parsing and can return\n // the tree selector object we got above\n if (!token) {\n return ts;\n }\n\n // Otherwise, there is more go come and we're going to need a\n // list of tree selectors\n const treeSelectors = [ts];\n while (token) {\n // The only character we allow after a tree selector is a comma\n if (token === \",\") {\n this.consume();\n } else {\n throw new ParseError(\"Expected comma\");\n }\n\n // And if we saw a comma, then it must be followed by another\n // tree selector\n treeSelectors.push(this.parseTreeSelector());\n token = this.nextToken();\n }\n\n // If we parsed more than one tree selector, return them in a\n // SelectorList object.\n return new SelectorList(treeSelectors);\n }\n\n // Parse a sequence of node selectors linked together with\n // hierarchy combinators: space, >, + and ~.\n parseTreeSelector(): Selector {\n this.skipSpace(); // Ignore space after a comma, for example\n\n // A tree selector must begin with a node selector\n let ns: Selector = this.parseNodeSelector();\n\n for (;;) {\n // Now check the next token. If there is none, or if it is a\n // comma, then we're done with the treeSelector. Otherwise\n // we expect a combinator followed by another node selector.\n // If we don't see a combinator, we throw an error. If we\n // do see a combinator and another node selector then we\n // combine the current node selector with the new node selector\n // using a Selector subclass that depends on the combinator.\n const token = this.nextToken();\n\n if (!token || token === \",\") {\n break;\n } else if (token === \" \") {\n this.consume();\n ns = new AncestorCombinator(ns, this.parseNodeSelector());\n } else if (token === \">\") {\n this.consume();\n ns = new ParentCombinator(ns, this.parseNodeSelector());\n } else if (token === \"+\") {\n this.consume();\n ns = new PreviousCombinator(ns, this.parseNodeSelector());\n } else if (token === \"~\") {\n this.consume();\n ns = new SiblingCombinator(ns, this.parseNodeSelector());\n } else {\n throw new ParseError(\"Unexpected token: \" + token);\n }\n }\n\n return ns;\n }\n\n // Parse a single node selector.\n // For now, this is just a node type or a wildcard.\n parseNodeSelector(): Selector {\n // First, skip any whitespace\n this.skipSpace();\n\n const t = this.nextToken();\n if (t === \"*\") {\n this.consume();\n return new AnyNode();\n }\n if (this.isIdentifier()) {\n this.consume();\n return new TypeSelector(t);\n }\n\n throw new ParseError(\"Expected node type\");\n }\n}\n\n// We break the input string into tokens with this regexp. Token types\n// are identifiers, integers, punctuation and spaces. Note that spaces\n// tokens are only returned when they appear before an identifier or\n// wildcard token and are otherwise omitted.\nParser.TOKENS = /([a-zA-Z][\\w-]*)|(\\d+)|[^\\s]|(\\s(?=[a-zA-Z*]))/g;\n\n/**\n * This is a trivial Error subclass that the Parser uses to signal parse errors\n */\nclass ParseError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * This Selector subclass is a list of selectors. It matches a node if any of\n * the selectors on the list matches the node. It considers the selectors in\n * order, and returns the array of nodes returned by whichever one matches\n * first.\n */\nclass SelectorList extends Selector {\n selectors: ReadonlyArray<Selector>;\n\n constructor(selectors: ReadonlyArray<Selector>) {\n super();\n this.selectors = selectors;\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n for (let i = 0; i < this.selectors.length; i++) {\n const s = this.selectors[i];\n const result = s.match(state);\n if (result) {\n return result;\n }\n }\n return null;\n }\n\n toString(): string {\n let result = \"\";\n for (let i = 0; i < this.selectors.length; i++) {\n result += i > 0 ? \", \" : \"\";\n result += this.selectors[i].toString();\n }\n return result;\n }\n}\n\n/**\n * This trivial Selector subclass implements the '*' wildcard and\n * matches any node.\n */\nclass AnyNode extends Selector {\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n return [state.currentNode()];\n }\n\n toString(): string {\n return \"*\";\n }\n}\n\n/**\n * This selector subclass implements the <IDENTIFIER> part of the grammar.\n * it matches any node whose `type` property is a specified string\n */\nclass TypeSelector extends Selector {\n type: string;\n\n constructor(type: string) {\n super();\n this.type = type;\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const node = state.currentNode();\n if (node.type === this.type) {\n return [node];\n }\n return null;\n }\n\n toString(): string {\n return this.type;\n }\n}\n\n/**\n * This selector subclass is the superclass of the classes that implement\n * matching for the four combinators. It defines left and right properties for\n * the two selectors that are to be combined, but does not define a match\n * method.\n */\nclass SelectorCombinator extends Selector {\n left: Selector;\n right: Selector;\n\n constructor(left: Selector, right: Selector) {\n super();\n this.left = left;\n this.right = right;\n }\n}\n\n/**\n * This Selector subclass implements the space combinator. It matches if the\n * right selector matches the current node and the left selector matches some\n * ancestor of the current node.\n */\nclass AncestorCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n state = state.clone();\n while (state.hasParent()) {\n state.goToParent();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the > combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * the parent of the current node.\n */\nclass ParentCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n if (state.hasParent()) {\n state = state.clone();\n state.goToParent();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" > \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the + combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * the immediate previous sibling of the current node.\n */\nclass PreviousCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n if (state.hasPreviousSibling()) {\n state = state.clone();\n state.goToPreviousSibling();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" + \" + this.right.toString();\n }\n}\n\n/**\n * This Selector subclass implements the ~ combinator. It matches if the\n * right selector matches the current node and the left selector matches\n * any previous sibling of the current node.\n */\nclass SiblingCombinator extends SelectorCombinator {\n constructor(left: Selector, right: Selector) {\n super(left, right);\n }\n\n match(state: TraversalState): ReadonlyArray<TreeNode> | null | undefined {\n const rightResult = this.right.match(state);\n if (rightResult) {\n state = state.clone();\n while (state.hasPreviousSibling()) {\n state.goToPreviousSibling();\n const leftResult = this.left.match(state);\n if (leftResult) {\n return leftResult.concat(rightResult);\n }\n }\n }\n return null;\n }\n\n toString(): string {\n return this.left.toString() + \" ~ \" + this.right.toString();\n }\n}\n","/**\n * The Rule class represents a Perseus lint rule. A Rule instance has a check()\n * method that takes the same (node, state, content) arguments that a\n * TreeTransformer traversal callback function does. Call the check() method\n * during a tree traversal to determine whether the current node of the tree\n * violates the rule. If there is a violation, check() returns an array of\n * issues. Each issue is an object that includes the name of the rule,\n * an error message, and the start and end positions of the lint within the\n * node's content string. If there are no violations of the rule, check()\n * returns an empty array.\n *\n * A Rule is typically defined in terms of a name, a selector, a pattern\n * (RegExp) and a linting function. Use the `Rule.makeRule()` or\n * `Rule.makeWidgetRule()` static methods to create rules.\n *\n * Rules only apply to nodes matching both the selector and the RegExp pattern.\n * If check() is called with a non-matching node, then the linting function is\n * not called, and check() returns an empty array.\n *\n * Certain advanced lint rules need additional information about the content\n * being linted in order to detect lint. For example, a rule to check for\n * whitespace at the start and end of the URL for an image can't use the\n * information in the node or content arguments because the markdown parser\n * strips leading and trailing whitespace when parsing. (Nevertheless, these\n * spaces have been a practical problem for our content translation process so\n * in order to check for them, a lint rule needs access to the original\n * unparsed source text. Similarly, there are various lint rules that check\n * widget usage. For example, it is easy to write a lint rule to ensure that\n * images have alt text for images encoded in markdown. But when images are\n * added to our content via an image widget we also want to be able to check\n * for alt text. In order to do this, the lint rule needs to be able to look\n * widgets up by name in the widgets object associated with the parse tree.\n *\n * In order to support advanced linting rules like these, the check() method\n * takes a context object as its optional fourth argument, and passes this\n * object on to the lint function of each rule. Rules that require extra\n * context should not assume that they will always get it, and should verify\n * that the necessary context has been supplied before using it. Currently the\n * \"content\" property of the context object is the unparsed source text if\n * available, and the \"widgets\" property of the context object is the widget\n * object associated with that content string in the JSON object that defines\n * the Perseus article or exercise that is being linted.\n */\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\nimport {Severity} from \"./lint\";\nimport Selector from \"./selector\";\n\nimport type {Lint} from \"./lint\";\nimport type {TraversalState, TreeNode} from \"./tree-transformer\";\nimport type {PerseusWidgetTypes} from \"@khanacademy/perseus-core\";\n\nexport type MakeRuleOptions = {\n name: string;\n pattern?: RegExp;\n selector?: string;\n locale?: string;\n lint: LintTester;\n};\n\nexport type MakeWidgetRuleOptions<\n TWidgetType extends keyof PerseusWidgetTypes,\n> = {\n name: string;\n widgetType: TWidgetType;\n lint: (\n widgetInfo: PerseusWidgetTypes[TWidgetType],\n // TODO(benchristel): type context properly, here and everywhere it's\n // used in the perseus-linter package.\n context: any,\n ) => undefined | Lint | Lint[];\n};\n\nexport type MakeLintFunctionOptions = {\n message: string;\n severity: number;\n};\n\n// This represents the type returned by String.match(). It is an\n// array of strings, but also has index:number and input:string properties.\n// TypeScript doesn't handle it well, so we punt and just use any.\ntype PatternMatchType = any;\n\nexport type LinterIssue = {\n rule: string;\n message: string;\n start: number;\n end: number;\n target?: string;\n severity: number;\n metadata?: Record<string, any>;\n};\n\ntype LintRuleContextObject =\n | {\n content: string;\n contentType: \"article\" | \"exercise\";\n stack: string[];\n widgets: any[];\n }\n | null\n | undefined;\n\n// This is the type of the lint detection function that the Rule() constructor\n// expects as its fourth argument. It is passed the TraversalState object and\n// content string that were passed to check(), and is also passed the array of\n// nodes returned by the selector match and the array of strings returned by\n// the pattern match. It should return null if no lint is detected or an\n// error message or an object contining an error message.\ntype LintTester = (\n state: TraversalState,\n content: string,\n selectorMatch: ReadonlyArray<TreeNode>,\n patternMatch: PatternMatchType,\n context: LintRuleContextObject,\n) => Lint | Lint[] | undefined;\n\n/**\n * A Rule object describes a Perseus lint rule. See the comment at the top of\n * this file for detailed description.\n */\nexport default class Rule {\n name: string; // The name of the rule\n selector: Selector; // The specified selector or the DEFAULT_SELECTOR\n pattern: RegExp | null | undefined; // A regular expression if one was specified\n lint: LintTester; // The lint-testing function or a default\n static DEFAULT_SELECTOR: Selector;\n\n // The comment at the top of this file has detailed docs for\n // this constructor and its arguments\n constructor(\n name: string | null | undefined,\n selector: Selector | null | undefined,\n pattern: RegExp | null | undefined,\n lint: LintTester,\n ) {\n if (!selector && !pattern) {\n throw new PerseusError(\n \"Lint rules must have a selector or pattern\",\n Errors.InvalidInput,\n {metadata: {name}},\n );\n }\n\n this.name = name || \"unnamed rule\";\n this.selector = selector || Rule.DEFAULT_SELECTOR;\n this.pattern = pattern || null;\n this.lint = lint;\n }\n\n // A factory method for use with rules described in JSON files\n // See the documentation at the start of this file for details.\n static makeRule(options: MakeRuleOptions): Rule {\n return new Rule(\n options.name,\n options.selector ? Selector.parse(options.selector) : null,\n Rule.makePattern(options.pattern),\n options.lint,\n );\n }\n\n static makeWidgetRule<TWidgetType extends keyof PerseusWidgetTypes>(\n options: MakeWidgetRuleOptions<TWidgetType>,\n ): Rule {\n return new Rule(\n options.name,\n Selector.parse(\"widget\"),\n null,\n (state, content, nodes, match, context) => {\n // Only apply widget rules if the widget has the correct type.\n if (state.currentNode().widgetType !== options.widgetType) {\n return;\n }\n\n const widgetId = state.currentNode().id;\n if (!widgetId) {\n return;\n }\n\n const widgetInfo = context?.widgets?.[widgetId];\n if (!widgetInfo) {\n return;\n }\n\n return [options.lint(widgetInfo, context) ?? []]\n .flat()\n .map((lint) => ({\n ...lint,\n message: `${widgetId}: ${lint.message}`,\n }));\n },\n );\n }\n\n // Check the node n to see if it violates this lint rule. A return value\n // of false means there is no lint. A returned object indicates a lint\n // error. See the documentation at the top of this file for details.\n check(\n node: TreeNode,\n traversalState: TraversalState,\n content: string,\n context: LintRuleContextObject,\n ): LinterIssue[] {\n // Define some helper functions. These have to be inside the check\n // method because they need to close over both the `content` parameter\n // and the `this` binding.\n const toLinterIssue = (error: Lint): LinterIssue => {\n // If the error has no location data, we default the location to\n // the entire content string.\n const {location = {start: 0, end: content.length}} = error;\n return {\n rule: this.name,\n severity: error.severity,\n message: error.message,\n metadata: error.metadata,\n ...location,\n };\n };\n\n const toLinterIssues = (\n rawLintOutput: undefined | Lint | Lint[],\n ): LinterIssue[] => {\n if (rawLintOutput == null) {\n return [];\n }\n if (Array.isArray(rawLintOutput)) {\n return rawLintOutput.map(toLinterIssue);\n }\n return [toLinterIssue(rawLintOutput)];\n };\n\n // First, see if we match the selector.\n // If no selector was passed to the constructor, we use a\n // default selector that matches text nodes.\n const selectorMatch = this.selector.match(traversalState);\n\n // If the selector did not match, then we're done\n if (!selectorMatch) {\n return [];\n }\n\n // If the selector matched, then see if the pattern matches\n let patternMatch;\n if (this.pattern) {\n patternMatch = content.match(this.pattern);\n } else {\n // If there is no pattern, then just match all of the content.\n // Use a fake RegExp match object to represent this default match.\n patternMatch = Rule.FakePatternMatch(content, content, 0);\n }\n\n // If there was a pattern and it didn't match, then we're done\n if (!patternMatch) {\n return [];\n }\n\n try {\n // If we get here, then the selector and pattern have matched\n // so now we call the lint function to see if there is lint.\n return toLinterIssues(\n this.lint(\n traversalState,\n content,\n selectorMatch,\n patternMatch,\n context,\n ),\n );\n } catch (e: any) {\n // If the lint function threw an exception we handle that as\n // a special type of lint. We want the user to see the lint\n // warning in this case (even though it is out of their control)\n // so that the bug gets reported. Otherwise we'd never know that\n // a rule was failing.\n return [\n {\n rule: \"lint-rule-failure\",\n severity: Rule.Severity.ERROR,\n message: `Exception in rule ${this.name}: ${e.message}\nStack trace:\n${e.stack}`,\n start: 0,\n end: content.length,\n },\n ];\n }\n }\n\n /**\n * Create a linter function from a message.\n */\n static makeLintFunction({\n message,\n severity,\n }: MakeLintFunctionOptions): LintTester {\n return (\n state: TraversalState,\n content: string,\n selectorMatch: ReadonlyArray<TreeNode>,\n patternMatch: PatternMatchType,\n context: LintRuleContextObject,\n ) => {\n return {\n message,\n severity,\n location: {\n start: patternMatch.index,\n end: patternMatch.index + patternMatch[0].length,\n },\n };\n };\n }\n\n // The makeRule() factory function uses this static method to turn its\n // argument into a RegExp. If the argument is already a RegExp, we just\n // return it. Otherwise, we compile it into a RegExp and return that.\n // The reason this is necessary is that Rule.makeRule() is designed for\n // use with data from JSON files and JSON files can't include RegExp\n // literals. Strings passed to this function do not need to be delimited\n // with / characters unless you want to include flags for the RegExp.\n //\n // Examples:\n //\n // input \"\" ==> output null\n // input /foo/ ==> output /foo/\n // input \"foo\" ==> output /foo/\n // input \"/foo/i\" ==> output /foo/i\n //\n static makePattern(\n pattern?: RegExp | string | null,\n ): RegExp | null | undefined {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!pattern) {\n return null;\n }\n if (pattern instanceof RegExp) {\n return pattern;\n }\n if (pattern[0] === \"/\") {\n const lastSlash = pattern.lastIndexOf(\"/\");\n const expression = pattern.substring(1, lastSlash);\n const flags = pattern.substring(lastSlash + 1);\n // @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\"]'?\n // eslint-disable-next-line no-restricted-syntax\n return new RegExp(expression, flags as RegExp.flags);\n }\n return new RegExp(pattern);\n }\n\n // This static method returns an string array with index and input\n // properties added, in order to simulate the return value of the\n // String.match() method. We use it when a Rule has no pattern and we\n // want to simulate a match on the entire content string.\n static FakePatternMatch(\n input: string,\n match: string | null | undefined,\n index: number,\n ): PatternMatchType {\n const result: any = [match];\n result.index = index;\n result.input = input;\n return result;\n }\n\n static Severity: {\n ERROR: number;\n GUIDELINE: number;\n WARNING: number;\n } = Severity;\n}\n\nRule.DEFAULT_SELECTOR = Selector.parse(\"text\");\n","// Return the portion of a URL between // and /. This is the authority\n// portion which is usually just the hostname, but may also include\n// a username, password or port. We don't strip those things out because\n// we typically want to reject any URL that includes them\nconst HOSTNAME = /\\/\\/([^/]+)/;\n\n// Return the hostname of the URL, with any \"www.\" prefix removed.\n// If this is a relative URL with no hostname, return an empty string.\nexport function getHostname(url: string): string {\n if (!url) {\n return \"\";\n }\n const match = url.match(HOSTNAME);\n return match ? match[1] : \"\";\n}\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport {getHostname} from \"./lint-utils\";\n\nexport default Rule.makeRule({\n name: \"absolute-url\",\n selector: \"link, image\",\n lint: function (state, content, nodes, match) {\n const linkOrImage: any = nodes[0];\n const url = linkOrImage.target;\n const hostname = getHostname(url);\n\n if (\n hostname === \"khanacademy.org\" ||\n hostname.endsWith(\".khanacademy.org\")\n ) {\n return linterGuideline(`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.`);\n }\n },\n});\n","import {parse} from \"@khanacademy/pure-markdown\";\n\nimport {runLinter} from \"./run-linter\";\n\nimport type {LinterIssue} from \"./rule\";\nimport type {\n PerseusItem,\n PerseusArticle,\n PerseusRenderer,\n} from \"@khanacademy/perseus-core\";\n\nexport type ItemLinterIssues = {\n question: LinterIssue[];\n hints: LinterIssue[][];\n};\n/**\n * Lint a full Perseus item, including the question and all hints.\n *\n * @param parsedPerseusItem - A parsed PerseusItem, typically the output of\n * `parseAndMigratePerseusItem`.\n * @returns Question issues plus per-hint issue arrays.\n */\nexport function lintPerseusItem(\n parsedPerseusItem: PerseusItem,\n): ItemLinterIssues {\n const questionLint = lintPerseusRenderer(\n parsedPerseusItem.question,\n \"exercise\",\n );\n const hintLint = parsedPerseusItem.hints.map((hint) =>\n lintPerseusRenderer(hint, \"exercise\"),\n );\n\n return {\n question: questionLint,\n hints: hintLint,\n };\n}\n\n/**\n * Lint a Perseus article.\n *\n * @remarks A single `PerseusRenderer` is treated as one section, so the outer array\n * has length 1.\n * @param parsedPerseusArticle - A parsed PerseusArticle, typically the output\n * of `parseAndMigratePerseusArticle`.\n * @returns A nested array with one array of linter issues per article section\n */\nexport function lintPerseusArticle(\n parsedPerseusArticle: PerseusArticle,\n): LinterIssue[][] {\n const articleSections = Array.isArray(parsedPerseusArticle)\n ? parsedPerseusArticle\n : [parsedPerseusArticle];\n\n return articleSections.map((section) =>\n lintPerseusRenderer(section, \"article\"),\n );\n}\n\n/**\n * Lint a single Perseus renderer block by parsing its markdown content and\n * running the standard lint rules against it.\n *\n * @param parsedPerseusRenderer - Parsed renderer (content and widgets).\n * @param contentType - Lint context: article, exercise, or renderer-only.\n * @returns An array of lint issues found in the content.\n */\nexport function lintPerseusRenderer(\n parsedPerseusRenderer: PerseusRenderer,\n contentType: \"article\" | \"exercise\" | \"renderer\",\n): LinterIssue[] {\n const tree = parse(parsedPerseusRenderer.content);\n const context = {\n content: parsedPerseusRenderer.content,\n widgets: parsedPerseusRenderer.widgets,\n stack: [],\n contentType,\n };\n\n return [...runLinter(tree, context, false)];\n}\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nimport type {PerseusRenderer} from \"@khanacademy/perseus-core\";\n\nexport const ExplanationWidgetRule = Rule.makeWidgetRule({\n name: \"explanation\",\n widgetType: \"explanation\",\n lint(widget, context) {\n const renderer: PerseusRenderer = {\n content: widget.options.explanation,\n widgets: widget.options.widgets,\n images: {},\n };\n return lintPerseusRenderer(renderer, context);\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {PerseusWidgetsMap} from \"@khanacademy/perseus-core\";\n\nfunction hasExplanation(widgets: PerseusWidgetsMap): boolean {\n return Object.values(widgets).some(\n (widget) => widget.type === \"explanation\",\n );\n}\n\nconst instructions = `Don't use explanation widgets in graded groups. Use the Graded Group Hint instead.`;\n\n// Graded groups render their own \"Explain\" button, so an Explanation widget\n// inside one shows learners two differently-styled \"Explain\" buttons.\nexport const ExplanationInGradedGroup = Rule.makeWidgetRule({\n name: \"explanation-in-graded-group\",\n widgetType: \"graded-group\",\n lint: function (widget) {\n if (hasExplanation(widget.options.widgets)) {\n return linterWarning(\n `Contains explanation widget. ${instructions}`,\n );\n }\n },\n});\n\nexport const ExplanationInGradedGroupSet = Rule.makeWidgetRule({\n name: \"explanation-in-graded-group-set\",\n widgetType: \"graded-group-set\",\n lint: function (widget) {\n const groupNumbers = widget.options.gradedGroups\n .map((group, i) => (hasExplanation(group.widgets) ? i + 1 : 0))\n .filter((groupNumber) => groupNumber > 0);\n if (groupNumbers.length > 0) {\n return linterWarning(\n `Explanation widget in group ${groupNumbers.join(\" and \")}. ${instructions}`,\n );\n }\n },\n});\n","import * as KAS from \"@khanacademy/kas\";\n\nimport {linterError, linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nfunction buttonNotInButtonSet(name: string, set: string): string {\n return `Answer requires a button not found in the button sets: ${name} (in ${set})`;\n}\n\nconst stringToButtonSet = {\n \"\\\\sqrt\": \"prealgebra\",\n \"^\": \"prealgebra\",\n \"\\\\sin\": \"trig\",\n \"\\\\cos\": \"trig\",\n \"\\\\tan\": \"trig\",\n \"\\\\log\": \"logarithms\",\n \"\\\\ln\": \"logarithms\",\n};\n\n/**\n * Rule to make sure that Expression questions that require\n * a specific math symbol to answer have that math symbol\n * available in the keypad (desktop learners can use a keyboard,\n * but mobile learners must use the MathInput keypad)\n */\nexport const ExpressionWidgetButtons = Rule.makeWidgetRule({\n name: \"expression-widget-buttons\",\n widgetType: \"expression\",\n lint(widget) {\n const answers = widget.options.answerForms;\n const buttons: string[] = widget.options.buttonSets;\n for (const answer of answers) {\n for (const [str, set] of Object.entries(stringToButtonSet)) {\n if (answer.value.includes(str) && !buttons.includes(set)) {\n return linterWarning(buttonNotInButtonSet(str, set));\n }\n }\n }\n },\n});\n\n/**\n * Checks that expression widgets have a correct answer.\n */\nexport const ExpressionWidgetCorrectAnswer = Rule.makeWidgetRule({\n name: \"expression-widget-correct-answer\",\n widgetType: \"expression\",\n lint(widget) {\n const {answerForms} = widget.options;\n\n if (answerForms.length === 0) {\n return linterError(\"No answers specified.\");\n }\n\n const hasCorrect = answerForms.some((form) => {\n return form.considered === \"correct\";\n });\n if (!hasCorrect) {\n return linterError(\"No correct answer specified.\");\n }\n },\n});\n\n/**\n * Checks that each of an expression widget's answers is a parseable\n * expression, and is simplified if the answer requires simplification.\n */\nexport const ExpressionWidgetAnswerForms = Rule.makeWidgetRule({\n name: \"expression-widget-answer-forms\",\n widgetType: \"expression\",\n lint(widget) {\n const {answerForms, functions} = widget.options;\n const issues: string[] = [];\n\n answerForms.forEach((form, ix) => {\n if (form.value === \"\") {\n issues.push(`Answer ${ix + 1} is empty.`);\n return;\n }\n const expression = KAS.parse(form.value, {functions});\n if (!expression.parsed) {\n issues.push(`Couldn't parse ${form.value}.`);\n return;\n }\n if (form.simplify && !expression.expr.isSimplified()) {\n issues.push(\n `${form.value} isn't simplified, but is required to be.`,\n );\n }\n });\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nexport const FillInTheBlankRule = Rule.makeWidgetRule({\n name: \"fill-in-the-blank\",\n widgetType: \"fill-in-the-blank\",\n lint(widget, context) {\n const renderer = {\n content: widget.options.content,\n widgets: widget.options.widgets,\n images: {},\n };\n return lintPerseusRenderer(renderer, context);\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Taken from packages/perseus/src/util.ts\n// I can't import it directly because of circular dependencies.\n//\n// Removed the `^` at the beginning of the origial rWidgetRule from\n// Utils because it was only identifying widgets at the beginning of the\n// string, but we want to match widgets anywhere in the string.\n//\n// Note: We can't use PerseusMarkdown here because perseus is a\n// restricted dependency of perseus-linter (circular dependency).\nconst rWidgetRule = /\\[\\[\\u2603 (([a-z-]+) ([0-9]+))\\]\\]/;\n\nexport default Rule.makeWidgetRule({\n name: \"free-response-widget-error\",\n widgetType: \"free-response\",\n lint(widget) {\n const question = widget.options.question;\n if (!question) {\n return linterError(\"The question is empty\");\n }\n\n if (question.match(rWidgetRule) != null) {\n return linterError(\"The question contains a widget\");\n }\n },\n});\n","import {lintPerseusRenderer} from \"../lint-content\";\n\nimport type {Lint} from \"../lint\";\nimport type {PerseusGradedGroupWidgetOptions} from \"@khanacademy/perseus-core\";\n\ninterface Context {\n contentType: \"exercise\" | \"article\" | \"renderer\";\n}\n\nexport function lintGradedGroup(\n options: PerseusGradedGroupWidgetOptions,\n {contentType}: Context,\n): Lint[] {\n const {hint} = options;\n\n const issues = [...lintPerseusRenderer(options, contentType)];\n\n if (hint) {\n const hintIssues = lintPerseusRenderer(hint, contentType).map(\n (lint) => ({...lint, message: `(in hint) ${lint.message}`}),\n );\n issues.push(...hintIssues);\n }\n\n return issues;\n}\n","import Rule from \"../rule\";\n\nimport {lintGradedGroup} from \"./lint-graded-group\";\n\nexport const GradedGroupWidgetRule = Rule.makeWidgetRule({\n name: \"graded-group\",\n widgetType: \"graded-group\",\n lint: (widget, context) => lintGradedGroup(widget.options, context),\n});\n","import Rule from \"../rule\";\n\nimport {lintGradedGroup} from \"./lint-graded-group\";\n\nimport type {Lint} from \"../lint\";\n\nexport const GradedGroupSetWidgetRule = Rule.makeWidgetRule({\n name: \"graded-group-set\",\n widgetType: \"graded-group-set\",\n lint: (widget, context) => {\n return widget.options.gradedGroups.flatMap((gradedGroup, i) =>\n lintGradedGroup(gradedGroup, context).map(prefixGroupNumber(i + 1)),\n );\n },\n});\n\nfunction prefixGroupNumber(n: number): (lint: Lint) => Lint {\n return (lint) => ({...lint, message: `group ${n}: ${lint.message}`});\n}\n","import {lintPerseusRenderer} from \"../lint-content\";\nimport Rule from \"../rule\";\n\nexport const GroupWidgetRule = Rule.makeWidgetRule({\n name: \"group\",\n widgetType: \"group\",\n lint(widget, context) {\n return lintPerseusRenderer(widget.options, context);\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-level-1\",\n selector: \"heading\",\n lint: function (state, content, nodes, match) {\n const heading: any = nodes[0];\n if (heading.level === 1) {\n return linterWarning(`Don't use level-1 headings:\nBegin headings with two or more # characters.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-level-skip\",\n selector: \"heading ~ heading\",\n lint: function (state, content, nodes, match) {\n const currentHeading: any = nodes[1];\n const previousHeading: any = nodes[0];\n // A heading can have a level less than, the same as\n // or one more than the previous heading. But going up\n // by 2 or more levels is not right\n if (currentHeading.level > previousHeading.level + 1) {\n return linterWarning(`Skipped heading level:\nthis heading is level ${currentHeading.level} but\nthe previous heading was level ${previousHeading.level}`);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"heading-sentence-case\",\n selector: \"heading\",\n pattern: /^\\W*[a-z]/, // first letter is lowercase\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `First letter is lowercase:\nthe first letter of a heading should be capitalized.`,\n }),\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\n// These are 3-letter and longer words that we would not expect to be\n// capitalized even in a title-case heading. See\n// http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html\nconst littleWords = {\n and: true,\n nor: true,\n but: true,\n the: true,\n for: true,\n} as const;\n\nfunction isCapitalized(word: any) {\n const c = word[0];\n return c === c.toUpperCase();\n}\n\nexport default Rule.makeRule({\n name: \"heading-title-case\",\n selector: \"heading\",\n pattern: /[^\\s:]\\s+[A-Z]+[a-z]/,\n locale: \"en\",\n lint: function (state, content, nodes, match) {\n // We want to assert that heading text is in sentence case, not\n // title case. The pattern above requires a capital letter at the\n // start of the heading and allows them after a colon, or in\n // acronyms that are all capitalized.\n //\n // But we can't warn just because the pattern matched because\n // proper nouns are also allowed bo be capitalized. We're not\n // going to do dictionary lookup to check for proper nouns, so\n // we try a heuristic: if the title is more than 3 words long\n // and if all the words are capitalized or are on the list of\n // words that don't get capitalized, then we'll assume that\n // the heading is incorrectly in title case and will warn.\n // But if there is at least one non-capitalized long word then\n // we're not in title case and we should not warn.\n\n const heading = content.trim();\n let words = heading.split(/\\s+/);\n\n // Remove the first word and the little words\n words.shift();\n words = words.filter(\n // eslint-disable-next-line no-prototype-builtins\n (w) => w.length > 2 && !littleWords.hasOwnProperty(w),\n );\n\n // If there are at least 3 remaining words and all\n // are capitalized, then the heading is in title case.\n if (words.length >= 3 && words.every((w) => isCapitalized(w))) {\n return linterGuideline(`Title-case heading:\nThis heading appears to be in title-case, but should be sentence-case.\nOnly capitalize the first letter and proper nouns.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-alt-text\",\n selector: \"image\",\n lint: function (state, content, nodes, match) {\n const image: any = nodes[0];\n if (!image.alt || !image.alt.trim()) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.`);\n }\n if (image.alt.length < 8) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ${image.alt.length} characters long.`);\n }\n },\n});\n","import {parse, traverseContent} from \"@khanacademy/pure-markdown\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n/**\n * This rule warns when it sees Markdown images used in the\n * top-level content. We are migrating to use the `image`\n * widget exclusively for images and this helps us to alert\n * content authors of this policy change. This rule ignores\n * markdown images found within other widgets for now.\n */\nexport default Rule.makeRule({\n name: \"image-markdown\",\n selector: \"image\",\n lint: function (state, content, nodes, match, context) {\n // Check if we're inside a widget - if so, allow markdown images.\n if (context?.stack && context.stack.includes(\"widget\")) {\n return;\n }\n\n // Discourage using markdown images in main content\n const parsedMarkdown = parse(context?.content || \"\", {});\n let hasInlineImageNode = false;\n\n traverseContent(parsedMarkdown, (node: any) => {\n if (node.type === \"image\") {\n hasInlineImageNode = true;\n }\n });\n\n if (hasInlineImageNode) {\n return linterWarning(`[Inline markdown image]:\nMarkdown images are not recommended - these are images that use the\n format. Please use the Image widget instead.`);\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-spaces-around-urls\",\n selector: \"image\",\n lint: function (state, content, nodes, match, context) {\n const image: any = nodes[0];\n const url: string = image.target;\n\n // The markdown parser strips leading and trailing spaces for us,\n // but they're still a problem for our translation process, so\n // we need to go check for them in the unparsed source string\n // if we have it.\n if (context && context.content) {\n // Find the url in the original content and make sure that the\n // character before is '(' and the character after is ')'\n const index = context.content.indexOf(url);\n if (index === -1) {\n // It is not an error if we didn't find it.\n return;\n }\n\n if (\n context.content[index - 1] !== \"(\" ||\n context.content[index + url.length] !== \")\"\n ) {\n return linterError(`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.`);\n }\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"image-url-empty\",\n selector: \"image\",\n lint: function (state, content, nodes) {\n const image: any = nodes[0];\n const url = image.target;\n\n // If no URL is provided, an infinite spinner will be shown in articles\n // overlaying the page where the image should be. This prevents the page\n // from fully loading. As a result, we check for URLS with all images.\n if (!url || !url.trim()) {\n return linterError(\"Images should have a URL\");\n }\n\n // NOTE(TB): Ideally there would be a check to confirm the URL works\n // and leads to a valid resource, but fetching the URL would require\n // linting to be able to handle async functions, which it currently\n // cannot do.\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Normally we have one rule per file. But since our selector class\n// can't match specific widget types directly, this rule implements\n// a number of image widget related rules in one place. This should\n// slightly increase efficiency, but it means that if there is more\n// than one problem with an image widget, the user will only see one\n// problem at a time.\nexport default Rule.makeWidgetRule({\n name: \"image-widget-alt-text\",\n widgetType: \"image\",\n lint(widget) {\n // Decorative images don't need alt text validation\n if (widget.options.decorative) {\n return;\n }\n\n const alt = widget.options.alt;\n\n // Non-decorative images must have alt text\n if (!alt) {\n return linterWarning(`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.`);\n }\n\n // Alt text must be descriptive (at least 8 characters)\n if (alt.trim().length < 8) {\n return linterWarning(`Images should have alt text:\nfor accessibility, all images should have descriptive alt text.\nThis image's alt text is only ${alt.trim().length} characters long.`);\n }\n\n // Make sure the alt text is not too long to be navigable\n if (alt.trim().length > 125) {\n return linterWarning(`Images should have alt text:\nfor accessibility, image alt text should not exceed 125 characters.\nThis image's alt text is ${alt.trim().length} characters long.\nPlease pair your alt with a long description below if you need significantly\nmore text to sufficiently describe the image.`);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\n// Normally we have one rule per file. But since our selector class\n// can't match specific widget types directly, this rule implements\n// a number of image widget related rules in one place. This should\n// slightly increase efficiency, but it means that if there is more\n// than one problem with an image widget, the user will only see one\n// problem at a time.\nexport default Rule.makeWidgetRule({\n name: \"image-widget-empty-size\",\n widgetType: \"image\",\n lint(widget) {\n if (!widget.options.backgroundImage.url) {\n return;\n }\n\n const {width, height} = widget.options.backgroundImage;\n\n if (!width || !height) {\n return linterWarning(`Images should have a non-zero size.\nThis image has a width of ${width} and a height of ${height}.\nPlease use the \"Reset to original size\" button to set the size of the image.`);\n }\n },\n});\n","import {CoreWidgetRegistry} from \"@khanacademy/perseus-core\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"inaccessible-widget\",\n selector: \"widget\",\n lint: function (state, content, nodes, match, context) {\n const node = state.currentNode();\n const widgetType = node.widgetType;\n const widgetId = node.id;\n\n if (!widgetType || !widgetId) {\n return;\n }\n\n const widgetInfo = context?.widgets?.[widgetId];\n if (!widgetInfo) {\n return;\n }\n\n const accessible = CoreWidgetRegistry.isAccessible(\n widgetType,\n widgetInfo.options,\n );\n if (!accessible) {\n return linterWarning(\n `The \"${widgetType}\" widget is not accessible.`,\n {\n location: {start: 0, end: content.length},\n metadata: {\n widgetType: widgetType,\n widgetId: widgetId,\n },\n },\n );\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {\n Coord,\n GraphRange,\n LockedFigure,\n LockedFunctionType,\n PerseusInteractiveGraphWidgetOptions,\n} from \"@khanacademy/perseus-core\";\n\nexport default Rule.makeWidgetRule({\n name: \"interactive-graph-locked-figure-oob\",\n widgetType: \"interactive-graph\",\n lint(widget) {\n const {range, lockedFigures}: PerseusInteractiveGraphWidgetOptions =\n widget.options;\n\n const warnings: string[] = [];\n\n for (const figure of lockedFigures ?? []) {\n if (!hasPointInRange(figure, range)) {\n const figureType = getPreciseFigureType(figure);\n const isSinglePoint =\n figure.type === \"point\" || figure.type === \"label\";\n warnings.push(\n isSinglePoint\n ? `Locked ${figureType} is outside the graph bounds.`\n : `All defining points for locked ${figureType} are outside the graph bounds.`,\n );\n }\n }\n\n return warnings.map((warning) => linterWarning(warning));\n },\n});\n\nfunction getPreciseFigureType(figure: LockedFigure): string {\n switch (figure.type) {\n case \"line\":\n // Line, Segment, or Ray\n return figure.kind;\n case \"ellipse\":\n return figure.radius[0] === figure.radius[1] ? \"circle\" : \"ellipse\";\n default:\n return figure.type;\n }\n}\n\nfunction isInRange([x, y]: Coord, range: GraphRange): boolean {\n const [[xMin, xMax], [yMin, yMax]] = range;\n return x >= xMin && x <= xMax && y >= yMin && y <= yMax;\n}\n\n// Figures are only flagged when every point that defines them is off the\n// graph. Figures with a subset of points inside the graph are not flagged.\nfunction hasPointInRange(figure: LockedFigure, range: GraphRange): boolean {\n // Locked functions aren't checked.\n if (figure.type === \"function\") {\n return true;\n }\n\n return definingPoints(figure).some((point) => isInRange(point, range));\n}\n\nfunction definingPoints(\n figure: Exclude<LockedFigure, LockedFunctionType>,\n): Coord[] {\n switch (figure.type) {\n case \"point\":\n case \"label\":\n return [figure.coord];\n case \"line\":\n return figure.points.map((point) => point.coord);\n case \"vector\":\n case \"polygon\":\n return figure.points;\n case \"ellipse\": {\n // The center plus the four vertices at the ends of each axis.\n // The rotation is ignored for this simple implementation.\n const [cx, cy] = figure.center;\n const [rx, ry] = figure.radius;\n return [\n [cx, cy],\n [cx + rx, cy],\n [cx - rx, cy],\n [cx, cy + ry],\n [cx, cy - ry],\n ];\n }\n }\n}\n","import {vector as kvector} from \"@khanacademy/kmath\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"interactive-graph-widget-error\",\n widgetType: \"interactive-graph\",\n lint(widget) {\n const issues: string[] = [];\n const {correct, graph, lockedFigures} = widget.options;\n\n for (const figure of lockedFigures ?? []) {\n // A locked line on the graph cannot have length 0.\n if (\n figure.type === \"line\" &&\n kvector.equal(figure.points[0].coord, figure.points[1].coord)\n ) {\n issues.push(\"Locked line cannot have length 0.\");\n }\n\n // A locked polygon can't have all coordinates be the same.\n if (figure.type === \"polygon\") {\n if (\n // If every point is the same as the first point,\n // then all the points are the same.\n figure.points.every((point) =>\n kvector.equal(point, figure.points[0]),\n )\n ) {\n issues.push(\n \"Locked polygon cannot have all coordinates be the same.\",\n );\n }\n }\n\n // A locked ellipse must have positive radius.\n if (figure.type === \"ellipse\") {\n if (figure.radius[0] <= 0 || figure.radius[1] <= 0) {\n issues.push(\n \"Locked ellipse must have positive radius values.\",\n );\n }\n }\n }\n\n // Do not save a unlimited polygon that is open (coords is null).\n if (\n correct?.type === \"polygon\" &&\n correct.numSides === \"unlimited\" &&\n correct.coords == null\n ) {\n issues.push(\"Polygon must be closed.\");\n }\n\n // Exponential: the start asymptote must not fall between or on the\n // curve's start points — that makes the coefficient formula undefined.\n if (graph?.type === \"exponential\" && graph.startCoords != null) {\n const {coords, asymptote} = graph.startCoords;\n const asymptoteY = asymptote;\n const minY = Math.min(coords[0][1], coords[1][1]);\n const maxY = Math.max(coords[0][1], coords[1][1]);\n if (asymptoteY >= minY && asymptoteY <= maxY) {\n issues.push(\n \"The exponential start asymptote must not fall between or on the curve's start points.\",\n );\n }\n }\n\n checkShowPointLabelsHasLabels(graph, issues);\n checkShowPointLabelsHasLabels(correct, issues);\n\n return issues.map((issue) => linterError(issue));\n },\n});\n\n// Fields checked in addition to `type`, `showPointLabels`, and `pointLabels`\n// so we can compute the expected label count for graph types whose number\n// of labelable points depends on runtime configuration.\ntype ShowPointLabelsShape = {\n type: string;\n showPointLabels?: boolean;\n pointLabels?: readonly string[];\n numPoints?: number | \"unlimited\";\n numSides?: number | \"unlimited\";\n numSegments?: number;\n};\n\nfunction checkShowPointLabelsHasLabels(\n g: ShowPointLabelsShape | undefined,\n issues: Array<string>,\n) {\n if (g == null || g.type === \"none\" || g.type === \"vector\") {\n return;\n }\n if (g.showPointLabels !== true) {\n return;\n }\n const labels = g.pointLabels;\n if (labels === undefined || labels.every((l) => l == null || l === \"\")) {\n issues.push(\n \"showPointLabels is true but pointLabels has no labels. Provide a label for at least one point.\",\n );\n return;\n }\n const expected = expectedLabelCount(g);\n if (expected !== undefined && labels.length !== expected) {\n issues.push(\n `pointLabels has ${labels.length} entries but this graph type expects ${expected}. Use empty strings (\"\") to skip labels for specific points, e.g. [\"A\", \"\", \"C\"].`,\n );\n }\n}\n\n// Returns the number of labelable points on `g`, or `undefined` when the\n// count depends on runtime state that isn't authored (e.g. `numPoints:\n// \"unlimited\"`) and therefore can't be validated at lint time.\nfunction expectedLabelCount(g: ShowPointLabelsShape): number | undefined {\n switch (g.type) {\n case \"angle\":\n case \"quadratic\":\n return 3;\n case \"linear\":\n case \"ray\":\n case \"sinusoid\":\n case \"absolute-value\":\n case \"exponential\":\n case \"logarithm\":\n case \"tangent\":\n return 2;\n case \"circle\":\n return 1;\n case \"linear-system\":\n // Two lines, two endpoints each, flat-indexed.\n return 4;\n case \"segment\":\n // Two endpoints per segment, flat-indexed. Default to one\n // segment if `numSegments` isn't set (matches the widget's\n // default).\n return (g.numSegments ?? 1) * 2;\n case \"point\":\n if (g.numPoints === \"unlimited\" || g.numPoints == null) {\n return undefined;\n }\n return g.numPoints;\n case \"polygon\":\n if (g.numSides === \"unlimited\" || g.numSides == null) {\n return undefined;\n }\n return g.numSides;\n default:\n return undefined;\n }\n}\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"label-image-widget-error\",\n widgetType: \"label-image\",\n lint(widget) {\n const issues: string[] = [];\n const {choices, imageAlt, imageUrl, markers} = widget.options;\n\n if (choices.length < 2) {\n issues.push(\n \"label-image widget must have at least two answer choices\",\n );\n }\n\n if (!imageUrl) {\n issues.push(\"No image url provided\");\n } else if (!imageAlt) {\n issues.push(\"No image alt text provided\");\n }\n\n if (markers.length === 0) {\n issues.push(\"label-image widget requires at least one marker\");\n } else {\n let numNoAnswers = 0;\n let numNoLabels = 0;\n\n for (const marker of markers) {\n if (marker.answers.length === 0) {\n numNoAnswers++;\n }\n\n if (!marker.label) {\n numNoLabels++;\n }\n }\n\n if (numNoAnswers > 0) {\n issues.push(\n `label-image widget has ${numNoAnswers} markers with no answers selected`,\n );\n }\n\n if (numNoLabels > 0) {\n issues.push(\n `label-image widget has ${numNoLabels} markers with no ARIA label`,\n );\n }\n }\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport {getHostname} from \"./lint-utils\";\n\nconst LEGACY_HOSTNAME = \"ka-perseus-images.s3.amazonaws.com\";\n\nexport default Rule.makeWidgetRule({\n name: \"legacy-gif-url\",\n widgetType: \"image\",\n lint(widget) {\n const url = widget.options?.backgroundImage?.url;\n if (!url) {\n return;\n }\n\n // Legacy gifs hosted on the old S3 bucket don't render in the editor\n // iframe, so we encourage content creators to use the CDN URL instead\n // or confirm that the image displays correctly in the published content.\n if (\n getHostname(url) === LEGACY_HOSTNAME &&\n url.toLowerCase().endsWith(\".gif\")\n ) {\n return linterGuideline(`Legacy gif URL:\ngifs hosted at ${LEGACY_HOSTNAME} might not appear in the editor preview,\nbut can still be viewed in the published content. Please use a\ncdn.kastatic.org/ka-perseus-images/ URL instead or confirm the\nimage displays correctly in the published content.`);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"link-click-here\",\n selector: \"link\",\n pattern: /click here/i,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Inappropriate link text:\nDo not use the words \"click here\" in links.`,\n }),\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"long-paragraph\",\n selector: \"paragraph\",\n pattern: /^.{501,}/,\n lint: function (state, content, nodes, match) {\n return linterGuideline(`Paragraph too long:\nThis paragraph is ${content.length} characters long.\nShorten it to 500 characters or fewer.`);\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"matcher-widget-error\",\n widgetType: \"matcher\",\n lint(widget) {\n if (widget.options.left.length !== widget.options.right.length) {\n return linterError(\n \"The two halves of the matcher have different numbers of cards.\",\n );\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-adjacent\",\n selector: \"blockMath+blockMath\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Adjacent math blocks:\ncombine the blocks between \\\\begin{align} and \\\\end{align}`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-align-extra-break\",\n selector: \"blockMath\",\n pattern: /(\\\\{2,})\\s*\\\\end{align}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Extra space at end of block:\nDon't end an align block with backslashes`,\n }),\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-align-linebreaks\",\n selector: \"blockMath\",\n // Match any align block with double backslashes in it\n // Use [\\s\\S]* instead of .* so we match newlines as well.\n pattern: /\\\\begin{align}[\\s\\S]*\\\\\\\\[\\s\\S]+\\\\end{align}/,\n // Look for double backslashes and ensure that they are\n // followed by optional space and another pair of backslashes.\n // Note that this rule can't know where line breaks belong so\n // it can't tell whether backslashes are completely missing. It just\n // enforces that you don't have the wrong number of pairs of backslashes.\n lint: function (state, content, nodes, match) {\n let text = match[0];\n while (text.length) {\n const index = text.indexOf(\"\\\\\\\\\");\n if (index === -1) {\n // No more backslash pairs, so we found no lint\n return;\n }\n text = text.substring(index + 2);\n\n // Now we expect to find optional spaces, another pair of\n // backslashes, and more optional spaces not followed immediately\n // by another pair of backslashes.\n const nextpair = text.match(/^\\s*\\\\\\\\\\s*(?!\\\\\\\\)/);\n\n // If that does not match then we either have too few or too\n // many pairs of backslashes.\n if (!nextpair) {\n return linterWarning(\n \"Use four backslashes between lines of an align block\",\n );\n }\n\n // If it did match, then, shorten the string and continue looping\n // (because a single align block may have multiple lines that\n // all must be separated by two sets of double backslashes).\n text = text.substring(nextpair[0].length);\n }\n },\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-empty\",\n selector: \"math, blockMath\",\n pattern: /^$/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: \"Empty math: don't use $$ in your markdown.\",\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-frac\",\n selector: \"math, blockMath\",\n pattern: /\\\\frac[ {]/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: \"Use \\\\dfrac instead of \\\\frac in your math expressions.\",\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-nested\",\n selector: \"math, blockMath\",\n pattern: /\\\\text{[^$}]*\\$[^$}]*\\$[^}]*}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Nested math:\nDon't nest math expressions inside \\\\text{} blocks`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-starts-with-space\",\n selector: \"math, blockMath\",\n pattern: /^\\s*(~|\\\\qquad|\\\\quad|\\\\,|\\\\;|\\\\:|\\\\ |\\\\!|\\\\enspace|\\\\phantom)/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\\\;, \\\\quad, or \\\\phantom`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"math-text-empty\",\n selector: \"math, blockMath\",\n pattern: /\\\\text{\\s*}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: \"Empty \\\\text{} block in math expression\",\n }),\n});\n","import Rule from \"../rule\";\n\n// Because no selector is specified, this rule only applies to text nodes.\n// Math and code hold their content directly and do not have text nodes\n// beneath them (unlike the HTML DOM) so this rule automatically does not\n// apply inside $$ or ``.\nexport default Rule.makeRule({\n name: \"math-without-dollars\",\n pattern: /\\\\\\w+{[^}]*}|{|}/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.GUIDELINE,\n message: `This looks like LaTeX:\ndid you mean to put it inside dollar signs?`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"nested-lists\",\n selector: \"list list\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.WARNING,\n message: `Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation.`,\n }),\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"numeric-input-missing-label\",\n widgetType: \"numeric-input\",\n lint(widget) {\n if (!widget.options.labelText) {\n return linterWarning(`Inputs should have an aria label:\nWhile screen readers will fallback to a default label of 'Your answer', a more descriptive label would improve accessibility.`);\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {Lint} from \"../lint\";\n\nexport default Rule.makeWidgetRule({\n name: \"numeric-input-widget-error\",\n widgetType: \"numeric-input\",\n lint(widget) {\n const issues: Lint[] = [];\n const answers = widget.options.answers;\n if (answers.some((answer) => answer.value == null)) {\n issues.push(linterError(\"One or more answers is empty\"));\n }\n\n answers.forEach((answer, i) => {\n const formatError =\n answer.strict &&\n (!answer.answerForms || answer.answerForms.length === 0);\n if (formatError) {\n issues.push(\n linterError(\n `Answer ${i + 1} requires a format, but no format was selected`,\n ),\n );\n }\n });\n\n return issues;\n },\n});\n","import {makeSafeUrl} from \"@khanacademy/perseus-core\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"phet-simulation-widget-error\",\n widgetType: \"phet-simulation\",\n lint(widget) {\n if (\n makeSafeUrl(\n widget.options.url,\n \"en\",\n \"https://phet.colorado.edu\",\n ) === null\n ) {\n return linterError(\"The URL is not from the PhET domain.\");\n }\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"python-program-widget-error\",\n widgetType: \"python-program\",\n lint(widget) {\n const errors: Array<string> = [];\n const height = widget.options.height;\n const programID = widget.options.programID;\n\n if (programID === \"\") {\n errors.push(\"The program ID is required.\");\n }\n\n if (!Number.isInteger(height) || height < 1) {\n errors.push(\"The height must be a positive integer.\");\n }\n\n return errors.map((error) => linterError(error));\n },\n});\n","import {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeWidgetRule({\n name: \"radio-widget-error\",\n widgetType: \"radio\",\n lint(widget) {\n const choices = widget.options.choices;\n\n // Error if no choice is marked as correct\n if (!choices.some((choice) => choice.correct)) {\n return linterError(\"No choice is marked as correct.\");\n }\n\n // Error if NOTA (none of the above) and another choice are both marked as correct\n const correctChoices = choices.filter((choice) => choice.correct);\n const hasNotaCorrect = correctChoices.some(\n (choice) => choice.isNoneOfTheAbove,\n );\n\n if (hasNotaCorrect && correctChoices.length > 1) {\n return linterError(\n \"Cannot mark both None of the Above and another choice as correct.\",\n );\n }\n\n return;\n },\n});\n","import {parse, traverseContent} from \"@khanacademy/pure-markdown\";\n\nimport {linterError} from \"../lint\";\nimport Rule from \"../rule\";\n\n// There's nothing to sort with fewer than two cards.\nconst minCards = 2;\n\n// A card holding an image must hold nothing else: an image next to text,\n// math, or another image is not allowed.\nfunction hasMixedContent(card: string): boolean {\n const contentNodes: any[] = [];\n\n traverseContent(parse(card.trim(), {}), (node: any) => {\n // Markdown always wraps a card in a paragraph, so that wrapper\n // doesn't count as content.\n if (node.type !== \"paragraph\") {\n contentNodes.push(node);\n }\n });\n\n return (\n contentNodes.length > 1 &&\n contentNodes.some((node) => node.type === \"image\")\n );\n}\n\nexport default Rule.makeWidgetRule({\n name: \"sorter-widget-error\",\n widgetType: \"sorter\",\n lint(widget) {\n const issues: string[] = [];\n const correct: string[] = widget.options.correct ?? [];\n\n if (correct.length < minCards) {\n issues.push(`Sorter requires at least ${minCards} cards.`);\n }\n\n if (correct.some((card) => card.trim() === \"\")) {\n issues.push(\"Sorter cards cannot be blank.\");\n }\n\n if (correct.some(hasMixedContent)) {\n issues.push(\"Sorter cards cannot mix images with other content.\");\n }\n\n return issues.map((issue) => linterError(issue));\n },\n});\n","import {SORTER_MAX_CARDS} from \"@khanacademy/perseus-core\";\n\nimport {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nimport type {PerseusSorterWidgetOptions} from \"@khanacademy/perseus-core\";\n\n// Exported for tests\nexport const sorterMaxIdealCards = 5;\nexport const sorterMaxHorizontalCards = 5;\n\nexport default Rule.makeWidgetRule({\n name: \"sorter-widget-warning\",\n widgetType: \"sorter\",\n lint(widget) {\n const warnings: string[] = [];\n const options: PerseusSorterWidgetOptions = widget.options;\n const {layout, correct = []} = options;\n\n if (correct.length > SORTER_MAX_CARDS) {\n warnings.push(\n `Sorter cannot have more than ${SORTER_MAX_CARDS} cards.`,\n );\n }\n\n if (\n layout === \"horizontal\" &&\n correct.length > sorterMaxHorizontalCards\n ) {\n warnings.push(\n `Sorter cannot have more than ${sorterMaxHorizontalCards} cards in horizontal layout.`,\n );\n }\n\n if (correct.length > sorterMaxIdealCards) {\n warnings.push(\n `Having more than ${sorterMaxIdealCards} cards in Sorter is discouraged.`,\n );\n }\n\n return warnings.map((warning) => linterWarning(warning));\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"static-widget-in-question-stem\",\n selector: \"widget\",\n lint: (state, content, nodes, match, context) => {\n if (context?.contentType !== \"exercise\") {\n return;\n }\n\n if (context.stack.includes(\"hint\")) {\n return;\n }\n\n const nodeId = state.currentNode().id;\n if (!nodeId) {\n return;\n }\n\n const widget = context?.widgets?.[nodeId];\n if (!widget) {\n return;\n }\n\n if (widget.static) {\n return linterWarning(\n `Widget in question stem is static (non-interactive).`,\n );\n }\n },\n});\n","import {linterGuideline} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport const MISSING_CAPTION_MESSAGE = `Table is missing a caption:\nScreen reader users rely on a caption to understand what a table contains\nbefore navigating its cells. Add one by putting a line of the form:\n|| Your caption here || directly above the table or using our Titled Table\ntemplate below.`;\n\nexport const EMPTY_CAPTION_MESSAGE = `Table caption is empty:\nThis table has a caption line, but there is no text between the || markers,\nso screen reader users hear an empty caption. Please add the appropriate\ntitle for your table.`;\n\n/**\n * Recursively collect the text of a parsed inline markdown node (or array of\n * them). A titled table's title is the output of `parseInline`, so its text\n * may be nested inside emphasis, strong, math, etc. rather than being a flat\n * string.\n */\nfunction getTextContent(node: any): string {\n if (typeof node === \"string\") {\n return node;\n }\n if (Array.isArray(node)) {\n return node.map(getTextContent).join(\"\");\n }\n if (node && typeof node === \"object\") {\n return getTextContent(node.content);\n }\n return \"\";\n}\n\n// Returns the text of a `titledTable` node's title, with no leading or\n// trailing whitespace. An empty string means the caption has no text in it.\nfunction getTitleText(titledTable: any): string {\n return getTextContent(titledTable?.title).trim();\n}\n\n// Returns true when every column header cell of a `table` node has no text in it\n// (for example \"| | |\"). Each header cell is an array of inline nodes.\nfunction hasEmptyHeaders(table: any): boolean {\n return table.header.every(\n (cell: any) => getTextContent(cell).trim() === \"\",\n );\n}\n\nexport default Rule.makeRule({\n name: \"table-missing-caption\",\n // The selector grammar has no `:not()`, so we match every table and\n // inspect its parent in `lint()`. A captioned table is parsed as a\n // `titledTable` node whose `table` property holds the table itself, so\n // the table's parent tells us whether a caption was authored.\n selector: \"table\",\n lint: function (state, _content, nodes) {\n // A table whose column headers are all empty isn't being used as a\n // data table (instead as a layout table) so a caption is not required\n // to ensure accessibility of the content.\n if (hasEmptyHeaders(nodes[0])) {\n return;\n }\n\n const parent = state.parent();\n\n if (parent?.type !== \"titledTable\") {\n return linterGuideline(MISSING_CAPTION_MESSAGE);\n }\n\n // The table has a caption line, but an author can write one with no\n // text in it (for example \"|| ||\"), which renders an empty\n // <caption> element. That is no more useful than having no caption.\n if (getTitleText(parent) === \"\") {\n return linterGuideline(EMPTY_CAPTION_MESSAGE);\n }\n },\n});\n","import {linterWarning} from \"../lint\";\nimport Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"table-missing-cells\",\n selector: \"table\",\n lint: function (state, content, nodes, match) {\n const table: any = nodes[0];\n const headerLength = table.header.length;\n const rowLengths = table.cells.map((r) => r.length);\n for (let r = 0; r < rowLengths.length; r++) {\n if (rowLengths[r] !== headerLength) {\n return linterWarning(`Table rows don't match header:\nThe table header has ${headerLength} cells, but\nRow ${r + 1} has ${rowLengths[r]} cells.`);\n }\n }\n },\n});\n","import Rule from \"../rule\";\n\n// Because no selector is specified, this rule only applies to text nodes.\n// Math and code hold their content directly and do not have text nodes\n// beneath them (unlike the HTML DOM) so this rule automatically does not\n// apply inside $$ or ``.\nexport default Rule.makeRule({\n name: \"unbalanced-code-delimiters\",\n pattern: /[`~]+/,\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters`,\n }),\n});\n","import Rule from \"../rule\";\n\nexport default Rule.makeRule({\n name: \"unescaped-dollar\",\n selector: \"unescapedDollar\",\n lint: Rule.makeLintFunction({\n severity: Rule.Severity.ERROR,\n message: `Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\\\$`,\n }),\n});\n","import AbsoluteUrl from \"./absolute-url\";\nimport {ExplanationWidgetRule} from \"./explanation\";\nimport {\n ExplanationInGradedGroup,\n ExplanationInGradedGroupSet,\n} from \"./explanation-in-graded-group\";\nimport {\n ExpressionWidgetAnswerForms,\n ExpressionWidgetButtons,\n ExpressionWidgetCorrectAnswer,\n} from \"./expression-widget\";\nimport {FillInTheBlankRule} from \"./fill-in-the-blank\";\nimport FreeResponseWidgetError from \"./free-response-widget-error\";\nimport {GradedGroupWidgetRule} from \"./graded-group\";\nimport {GradedGroupSetWidgetRule} from \"./graded-group-set\";\nimport {GroupWidgetRule} from \"./group\";\nimport HeadingLevel1 from \"./heading-level-1\";\nimport HeadingLevelSkip from \"./heading-level-skip\";\nimport HeadingSentenceCase from \"./heading-sentence-case\";\nimport HeadingTitleCase from \"./heading-title-case\";\nimport ImageAltText from \"./image-alt-text\";\nimport ImageMarkdown from \"./image-markdown\";\nimport ImageSpacesAroundUrls from \"./image-spaces-around-urls\";\nimport ImageUrlEmpty from \"./image-url-empty\";\nimport ImageWidgetAltText from \"./image-widget-alt-text\";\nimport ImageWidgetEmptySize from \"./image-widget-empty-size\";\nimport InaccessibleWidget from \"./inaccessible-widget\";\nimport InteractiveGraphLockedFigureOob from \"./interactive-graph-locked-figure-oob\";\nimport InteractiveGraphWidgetError from \"./interactive-graph-widget-error\";\nimport LabelImageWidgetError from \"./label-image-widget-error\";\nimport LegacyGifUrl from \"./legacy-gif-url\";\nimport LinkClickHere from \"./link-click-here\";\nimport LongParagraph from \"./long-paragraph\";\nimport MatcherWidgetError from \"./matcher-widget-error\";\nimport MathAdjacent from \"./math-adjacent\";\nimport MathAlignExtraBreak from \"./math-align-extra-break\";\nimport MathAlignLinebreaks from \"./math-align-linebreaks\";\nimport MathEmpty from \"./math-empty\";\nimport MathFrac from \"./math-frac\";\nimport MathNested from \"./math-nested\";\nimport MathStartsWithSpace from \"./math-starts-with-space\";\nimport MathTextEmpty from \"./math-text-empty\";\nimport MathWithoutDollars from \"./math-without-dollars\";\nimport NestedLists from \"./nested-lists\";\nimport NumericInputMissingLabel from \"./numeric-input-missing-label\";\nimport NumericInputWidgetError from \"./numeric-input-widget-error\";\nimport PhetSimulationWidgetError from \"./phet-simulation-widget-error\";\nimport PythonProgramWidgetError from \"./python-program-widget-error\";\nimport RadioWidgetError from \"./radio-widget-error\";\nimport SorterWidgetError from \"./sorter-widget-error\";\nimport SorterWidgetWarning from \"./sorter-widget-warning\";\nimport StaticWidgetInQuestionStem from \"./static-widget-in-question-stem\";\nimport TableMissingCaption from \"./table-missing-caption\";\nimport TableMissingCells from \"./table-missing-cells\";\nimport UnbalancedCodeDelimiters from \"./unbalanced-code-delimiters\";\nimport UnescapedDollar from \"./unescaped-dollar\";\n\nimport type Rule from \"../rule\";\n\nexport function allRules(): Rule[] {\n return [\n AbsoluteUrl,\n ExplanationInGradedGroup,\n ExplanationInGradedGroupSet,\n ExplanationWidgetRule,\n ExpressionWidgetAnswerForms,\n ExpressionWidgetButtons,\n ExpressionWidgetCorrectAnswer,\n FillInTheBlankRule,\n FreeResponseWidgetError,\n GradedGroupSetWidgetRule,\n GradedGroupWidgetRule,\n GroupWidgetRule,\n HeadingLevel1,\n HeadingLevelSkip,\n HeadingSentenceCase,\n HeadingTitleCase,\n ImageAltText,\n ImageMarkdown,\n ImageSpacesAroundUrls,\n ImageUrlEmpty,\n ImageWidgetAltText,\n ImageWidgetEmptySize,\n InaccessibleWidget,\n InteractiveGraphLockedFigureOob,\n InteractiveGraphWidgetError,\n LabelImageWidgetError,\n LegacyGifUrl,\n LinkClickHere,\n LongParagraph,\n MatcherWidgetError,\n MathAdjacent,\n MathAlignExtraBreak,\n MathAlignLinebreaks,\n MathEmpty,\n MathFrac,\n MathNested,\n MathStartsWithSpace,\n MathTextEmpty,\n MathWithoutDollars,\n NestedLists,\n NumericInputMissingLabel,\n NumericInputWidgetError,\n PhetSimulationWidgetError,\n PythonProgramWidgetError,\n RadioWidgetError,\n SorterWidgetError,\n SorterWidgetWarning,\n StaticWidgetInQuestionStem,\n TableMissingCaption,\n TableMissingCells,\n UnbalancedCodeDelimiters,\n UnescapedDollar,\n ];\n}\n","/**\n * TreeTransformer is a class for traversing and transforming trees. Create a\n * TreeTransformer by passing the root node of the tree to the\n * constructor. Then traverse that tree by calling the traverse() method. The\n * argument to traverse() is a callback function that will be called once for\n * each node in the tree. This is a post-order depth-first traversal: the\n * callback is not called on the a way down, but on the way back up. That is,\n * the children of a node are traversed before the node itself is.\n *\n * The traversal callback function is passed three arguments, the node being\n * traversed, a TraversalState object, and the concatentated text content of\n * the node and all of its descendants. The TraversalState object is the most\n * most interesting argument: it has methods for querying the ancestors and\n * siblings of the node, and for deleting or replacing the node. These\n * transformation methods are why this class is a tree transformer and not\n * just a tree traverser.\n *\n * A typical tree traversal looks like this:\n *\n * new TreeTransformer(root).traverse((node, state, content) => {\n * let parent = state.parent();\n * let previous = state.previousSibling();\n * // etc.\n * });\n *\n * The traverse() method descends through nodes and arrays of nodes and calls\n * the traverse callback on each node on the way back up to the root of the\n * tree. (Note that it only calls the callback on the nodes themselves, not\n * any arrays that contain nodes.) A node is loosely defined as any object\n * with a string-valued `type` property. Objects that do not have a type\n * property are assumed to not be part of the tree and are not traversed. When\n * traversing an array, all elements of the array are examined, and any that\n * are nodes or arrays are recursively traversed. When traversing a node, all\n * properties of the object are examined and any node or array values are\n * recursively traversed. In typical parse trees, the children of a node are\n * in a `children` or `content` array, but this class is designed to handle\n * more general trees. The Perseus markdown parser, for example, produces\n * nodes of type \"table\" that have children in the `header` and `cells`\n * properties.\n *\n * CAUTION: the traverse() method does not make any attempt to detect\n * cycles. If you call it on a cyclic graph instead of a tree, it will cause\n * infinite recursion (or, more likely, a stack overflow).\n *\n * If a node has a text-valued `content` property, it is taken to be the\n * plain-text content of the node. The traverse() method concatenates these\n * content strings and passes them to the traversal callback for each\n * node. This means that the callback has access the full text content of its\n * node and all of the nodes descendants.\n *\n * See the TraversalState class for more information on what information and\n * methods are available to the traversal callback.\n **/\n\nimport {Errors, PerseusError} from \"@khanacademy/perseus-core\";\n\n/**\n * TreeNode represents a node in a linted parse tree.\n */\nexport type TreeNode =\n | {\n type: string;\n content: string;\n id?: string;\n widgetType?: string;\n }\n | {\n type: \"lint\";\n content: TreeNode;\n message: string;\n ruleName: string;\n blockHighlight?: boolean;\n insideTable: boolean;\n severity: number;\n id?: undefined;\n widgetType?: undefined;\n };\n\n// TraversalCallback is the type of the callback function passed to the\n// traverse() method. It is invoked with node, state, and content arguments\n// and is expected to return nothing.\ntype TraversalCallback = (\n node: TreeNode,\n state: TraversalState,\n content: string,\n) => void;\n\n// This is the TreeTransformer class described in detail at the\n// top of this file.\nexport default class TreeTransformer {\n root: TreeNode;\n\n // To create a tree transformer, just pass the root node of the tree\n constructor(root: TreeNode) {\n this.root = root;\n }\n\n // A utility function for determing whether an arbitrary value is a node\n static isNode(n: any): boolean {\n return n && typeof n === \"object\" && typeof n.type === \"string\";\n }\n\n // Determines whether a value is a node with type \"text\" and has\n // a text-valued `content` property.\n static isTextNode(n: any): boolean {\n return (\n TreeTransformer.isNode(n) &&\n n.type === \"text\" &&\n typeof n.content === \"string\"\n );\n }\n\n // This is the main entry point for the traverse() method. See the comment\n // at the top of this file for a detailed description. Note that this\n // method just creates a new TraversalState object to use for this\n // traversal and then invokes the internal _traverse() method to begin the\n // recursion.\n traverse(f: TraversalCallback): void {\n this._traverse(this.root, new TraversalState(this.root), f);\n }\n\n // Do a post-order traversal of node and its descendants, invoking the\n // callback function f() once for each node and returning the concatenated\n // text content of the node and its descendants. f() is passed three\n // arguments: the current node, a TraversalState object representing the\n // current state of the traversal, and a string that holds the\n // concatenated text of the node and its descendants.\n //\n // This private method holds all the traversal logic and implementation\n // details. Note that this method uses the TraversalState object to store\n // information about the structure of the tree.\n _traverse(\n n: TreeNode | Array<TreeNode>,\n state: TraversalState,\n f: TraversalCallback,\n ): string {\n let content = \"\";\n if (TreeTransformer.isNode(n)) {\n // If we were called on a node object, then we handle it\n // this way.\n // eslint-disable-next-line no-restricted-syntax\n const node = n as TreeNode; // safe cast; we just tested\n\n // Put the node on the stack before recursing on its children\n state._containers.push(node);\n state._ancestors.push(node);\n\n // Record the node's text content if it has any.\n // Usually this is for nodes with a type property of \"text\",\n // but other nodes types like \"math\" may also have content.\n if (typeof node.content === \"string\") {\n content = node.content;\n }\n\n // Recurse on the node. If there was content above, then there\n // probably won't be any children to recurse on, but we check\n // anyway.\n //\n // If we wanted to make the traversal completely specific to the\n // actual Perseus parse trees that we'll be dealing with we could\n // put a switch statement here to dispatch on the node type\n // property with specific recursion steps for each known type of\n // node.\n const keys = Object.keys(node);\n keys.forEach((key) => {\n // Never recurse on the type property\n if (key === \"type\") {\n return;\n }\n // Ignore properties that are null or primitive and only\n // recurse on objects and arrays. Note that we don't do a\n // isNode() check here. That is done in the recursive call to\n // _traverse(). Note that the recursive call on each child\n // returns the text content of the child and we add that\n // content to the content for this node. Also note that we\n // push the name of the property we're recursing over onto a\n // TraversalState stack.\n const value = node[key];\n if (value && typeof value === \"object\") {\n state._indexes.push(key);\n content += this._traverse(value, state, f);\n state._indexes.pop();\n }\n });\n\n // Restore the stacks after recursing on the children\n state._currentNode = state._ancestors.pop();\n state._containers.pop();\n\n // And finally call the traversal callback for this node. Note\n // that this is post-order traversal. We call the callback on the\n // way back up the tree, not on the way down. That way we already\n // know all the content contained within the node.\n f(node, state, content);\n } else if (Array.isArray(n)) {\n // If we were called on an array instead of a node, then\n // this is the code we use to recurse.\n const nodes = n;\n\n // Push the array onto the stack. This will allow the\n // TraversalState object to locate siblings of this node.\n state._containers.push(nodes);\n\n // Now loop through this array and recurse on each element in it.\n // Before recursing on an element, we push its array index on a\n // TraversalState stack so that the TraversalState sibling methods\n // can work. Note that TraversalState methods can alter the length\n // of the array, and change the index of the current node, so we\n // are careful here to test the array length on each iteration and\n // to reset the index when we pop the stack. Also note that we\n // concatentate the text content of the children.\n let index = 0;\n while (index < nodes.length) {\n state._indexes.push(index);\n content += this._traverse(nodes[index], state, f);\n // Casting to convince TypeScript that this is a number\n // eslint-disable-next-line no-restricted-syntax\n index = (state._indexes.pop() as number) + 1;\n }\n\n // Pop the array off the stack. Note, however, that we do not call\n // the traversal callback on the array. That function is only\n // called for nodes, not arrays of nodes.\n state._containers.pop();\n }\n\n // The _traverse() method always returns the text content of\n // this node and its children. This is the one piece of state that\n // is not tracked in the TraversalState object.\n return content;\n }\n}\n\n// An instance of this class is passed to the callback function for\n// each node traversed. The class itself is not exported, but its\n// methods define the API available to the traversal callback.\n\n/**\n * This class represents the state of a tree traversal. An instance is created\n * by the traverse() method of the TreeTransformer class to maintain the state\n * for that traversal, and the instance is passed to the traversal callback\n * function for each node that is traversed. This class is not intended to be\n * instantiated directly, but is exported so that its type can be used for\n * type annotaions.\n **/\nexport class TraversalState {\n // The root node of the tree being traversed\n root: TreeNode;\n\n // These are internal state properties. Use the accessor methods defined\n // below instead of using these properties directly. Note that the\n // _containers and _indexes stacks can have two different types of\n // elements, depending on whether we just recursed on an array or on a\n // node. This is hard for TypeScript to deal with, so you'll see a number of\n // type casts through the any type when working with these two properties.\n _currentNode: TreeNode | null | undefined;\n _containers: Stack<TreeNode | Array<TreeNode>>;\n _indexes: Stack<string | number>;\n _ancestors: Stack<TreeNode>;\n\n // The constructor just stores the root node and creates empty stacks.\n constructor(root: TreeNode) {\n this.root = root;\n\n // When the callback is called, this property will hold the\n // node that is currently being traversed.\n this._currentNode = null;\n\n // This is a stack of the objects and arrays that we've\n // traversed through before reaching the currentNode.\n // It is different than the ancestors array.\n this._containers = new Stack();\n\n // This stack has the same number of elements as the _containers\n // stack. The last element of this._indexes[] is the index of\n // the current node in the object or array that is the last element\n // of this._containers[]. If the last element of this._containers[] is\n // an array, then the last element of this stack will be a number.\n // Otherwise if the last container is an object, then the last index\n // will be a string property name.\n this._indexes = new Stack();\n\n // This is a stack of the ancestor nodes of the current one.\n // It is different than the containers[] stack because it only\n // includes nodes, not arrays.\n this._ancestors = new Stack();\n }\n\n /**\n * Return the current node in the traversal. Any time the traversal\n * callback is called, this method will return the name value as the\n * first argument to the callback.\n */\n currentNode(): TreeNode {\n return this._currentNode || this.root;\n }\n\n /**\n * Return the parent of the current node, if there is one, or null.\n */\n parent(): TreeNode | null | undefined {\n return this._ancestors.top();\n }\n\n /**\n * Return an array of ancestor nodes. The first element of this array is\n * the same as this.parent() and the last element is the root node. If we\n * are currently at the root node, the the returned array will be empty.\n * This method makes a copy of the internal state, so modifications to the\n * returned array have no effect on the traversal.\n */\n ancestors(): ReadonlyArray<TreeNode> {\n return this._ancestors.values();\n }\n\n /**\n * Return the next sibling of this node, if it has one, or null otherwise.\n */\n nextSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n\n // If we're at the root of the tree or if the parent is an\n // object instead of an array, then there are no siblings.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!siblings || !Array.isArray(siblings)) {\n return null;\n }\n\n // The top index is a number because the top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (siblings.length > index + 1) {\n return siblings[index + 1];\n }\n return null; // There is no next sibling\n }\n\n /**\n * Return the previous sibling of this node, if it has one, or null\n * otherwise.\n */\n previousSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n\n // If we're at the root of the tree or if the parent is an\n // object instead of an array, then there are no siblings.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!siblings || !Array.isArray(siblings)) {\n return null;\n }\n\n // The top index is a number because the top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (index > 0) {\n return siblings[index - 1];\n }\n return null; // There is no previous sibling\n }\n\n /**\n * Remove the next sibling node (if there is one) from the tree. Returns\n * the removed sibling or null. This method makes it easy to traverse a\n * tree and concatenate adjacent text nodes into a single node.\n */\n removeNextSibling(): TreeNode | null | undefined {\n const siblings = this._containers.top();\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (siblings && Array.isArray(siblings)) {\n // top index is a number because top container is an array\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n if (siblings.length > index + 1) {\n return siblings.splice(index + 1, 1)[0];\n }\n }\n return null;\n }\n\n /**\n * Replace the current node in the tree with the specified nodes. If no\n * nodes are passed, this is a node deletion. If one node (or array) is\n * passed, this is a 1-for-1 replacement. If more than one node is passed\n * then this is a combination of deletion and insertion. The new node or\n * nodes will not be traversed, so this method can safely be used to\n * reparent the current node node beneath a new parent.\n *\n * This method throws an error if you attempt to replace the root node of\n * the tree.\n */\n replace(...replacements: ReadonlyArray<TreeNode>): void {\n const parent = this._containers.top();\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!parent) {\n throw new PerseusError(\n \"Can't replace the root of the tree\",\n Errors.Internal,\n );\n }\n\n // The top of the container stack is either an array or an object\n // and the top of the indexes stack is a corresponding array index\n // or object property. This is hard for TypeScript, so we have to do some\n // unsafe casting and be careful when we use which cast version\n if (Array.isArray(parent)) {\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.top() as number;\n // For an array parent we just splice the new nodes in\n parent.splice(index, 1, ...replacements);\n // Adjust the index to account for the changed array length.\n // We don't want to traverse any of the newly inserted nodes.\n this._indexes.pop();\n this._indexes.push(index + replacements.length - 1);\n } else {\n // eslint-disable-next-line no-restricted-syntax\n const property = this._indexes.top() as string;\n // For an object parent we care how many new nodes there are\n if (replacements.length === 0) {\n // Deletion\n delete parent[property];\n } else if (replacements.length === 1) {\n // Replacement\n parent[property] = replacements[0];\n } else {\n // Replace one node with an array of nodes\n parent[property] = replacements;\n }\n }\n }\n\n /**\n * Returns true if the current node has a previous sibling and false\n * otherwise. If this method returns false, then previousSibling() will\n * return null, and goToPreviousSibling() will throw an error.\n */\n hasPreviousSibling(): boolean {\n return (\n Array.isArray(this._containers.top()) &&\n // eslint-disable-next-line no-restricted-syntax\n (this._indexes.top() as number) > 0\n );\n }\n\n /**\n * Modify this traversal state object to have the state it would have had\n * when visiting the previous sibling. Note that you may want to use\n * clone() to make a copy before modifying the state object like this.\n * This mutator method is not typically used during ordinary tree\n * traversals, but is used by the Selector class for matching multi-node\n * selectors.\n */\n goToPreviousSibling(): void {\n if (!this.hasPreviousSibling()) {\n throw new PerseusError(\n \"goToPreviousSibling(): node has no previous sibling\",\n Errors.Internal,\n );\n }\n\n this._currentNode = this.previousSibling();\n // Since we know that we have a previous sibling, we know that\n // the value on top of the stack is a number, but we have to do\n // this unsafe cast because TypeScript doesn't know that.\n // eslint-disable-next-line no-restricted-syntax\n const index = this._indexes.pop() as number;\n this._indexes.push(index - 1);\n }\n\n /**\n * Returns true if the current node has an ancestor and false otherwise.\n * If this method returns false, then the parent() method will return\n * null and goToParent() will throw an error\n */\n hasParent(): boolean {\n return this._ancestors.size() !== 0;\n }\n\n /**\n * Modify this object to look like it will look when we (later) visit the\n * parent node of this node. You should not modify the instance passed to\n * the tree traversal callback. Instead, make a copy with the clone()\n * method and modify that. This mutator method is not typically used\n * during ordinary tree traversals, but is used by the Selector class for\n * matching multi-node selectors that involve parent and ancestor\n * selectors.\n */\n goToParent(): void {\n if (!this.hasParent()) {\n throw new PerseusError(\n \"goToParent(): node has no ancestor\",\n Errors.NotAllowed,\n );\n }\n\n this._currentNode = this._ancestors.pop();\n\n // We need to pop the containers and indexes stacks at least once\n // and more as needed until we restore the invariant that\n // this._containers.top()[this.indexes.top()] === this._currentNode\n //\n while (\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n this._containers.size() &&\n this._containers.top()[this._indexes.top()] !== this._currentNode\n ) {\n this._containers.pop();\n this._indexes.pop();\n }\n }\n\n /**\n * Return a new TraversalState object that is a copy of this one.\n * This method is useful in conjunction with the mutating methods\n * goToParent() and goToPreviousSibling().\n */\n clone(): TraversalState {\n const clone = new TraversalState(this.root);\n clone._currentNode = this._currentNode;\n clone._containers = this._containers.clone();\n clone._indexes = this._indexes.clone();\n clone._ancestors = this._ancestors.clone();\n return clone;\n }\n\n /**\n * Returns true if this TraversalState object is equal to that\n * TraversalState object, or false otherwise. This method exists\n * primarily for use by our unit tests.\n */\n equals(that: TraversalState): boolean {\n return (\n this.root === that.root &&\n this._currentNode === that._currentNode &&\n this._containers.equals(that._containers) &&\n this._indexes.equals(that._indexes) &&\n this._ancestors.equals(that._ancestors)\n );\n }\n}\n\n/**\n * This class is an internal utility that just treats an array as a stack\n * and gives us a top() method so we don't have to write expressions like\n * `ancestors[ancestors.length-1]`. The values() method automatically\n * copies the internal array so we don't have to worry about client code\n * modifying our internal stacks. The use of this Stack abstraction makes\n * the TraversalState class simpler in a number of places.\n */\nclass Stack<T> {\n stack: Array<T>;\n\n constructor(array?: ReadonlyArray<T> | null) {\n this.stack = array ? array.slice(0) : [];\n }\n\n /** Push a value onto the stack. */\n push(v: T): void {\n this.stack.push(v);\n }\n\n /** Pop a value off of the stack. */\n pop(): T {\n // @ts-expect-error - TS2322 - Type 'T | undefined' is not assignable to type 'T'.\n return this.stack.pop();\n }\n\n /** Return the top value of the stack without popping it. */\n top(): T {\n return this.stack[this.stack.length - 1];\n }\n\n /** Return a copy of the stack as an array */\n values(): ReadonlyArray<T> {\n return this.stack.slice(0);\n }\n\n /** Return the number of elements in the stack */\n size(): number {\n return this.stack.length;\n }\n\n /** Return a string representation of the stack */\n toString(): string {\n return this.stack.toString();\n }\n\n /** Return a shallow copy of the stack */\n clone(): Stack<T> {\n return new Stack(this.stack);\n }\n\n /**\n * Compare this stack to another and return true if the contents of\n * the two arrays are the same.\n */\n equals(that: Stack<T>): boolean {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (!that || !that.stack || that.stack.length !== this.stack.length) {\n return false;\n }\n for (let i = 0; i < this.stack.length; i++) {\n if (this.stack[i] !== that.stack[i]) {\n return false;\n }\n }\n return true;\n }\n}\n","import {allRules} from \"./rules/all-rules\";\nimport TreeTransformer from \"./tree-transformer\";\n\nimport type {LinterIssue} from \"./rule\";\nimport type {TreeNode} from \"./tree-transformer\";\n\n/**\n * Run the Perseus linter over the specified markdown parse tree, with the\n * specified context object, and return a (possibly empty) array of lint\n * warning objects. If the highlight argument is true, this function also\n * modifies the parse tree to add \"lint\" nodes that can be visually rendered,\n * highlighting the problems for the user. The optional rules argument is an\n * array of Rule objects specifying which lint rules should be applied to this\n * parse tree. When omitted, a default set of rules is used.\n *\n * The context object may have additional properties that some lint rules\n * require:\n *\n * context.content is the source content string that was parsed to create\n * the parse tree.\n *\n * context.widgets is the widgets object associated\n * with the content string\n */\nexport function runLinter(\n tree: any,\n context: any,\n highlight: boolean,\n): ReadonlyArray<LinterIssue> {\n const issues: Array<LinterIssue> = [];\n const tt = new TreeTransformer(tree);\n\n // The markdown parser often outputs adjacent text nodes. We\n // coalesce them before linting for efficiency and accuracy.\n tt.traverse((node, state, content) => {\n if (TreeTransformer.isTextNode(node)) {\n let next = state.nextSibling();\n while (TreeTransformer.isTextNode(next)) {\n // @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'.\n node.content += next.content;\n state.removeNextSibling();\n next = state.nextSibling();\n }\n }\n });\n\n // HTML tables are complicated, and the CSS we use in\n // ../components/lint.jsx to display lint does not work to\n // correctly position the lint indicators in the margin when the\n // lint is inside a table. So as a workaround we keep track of all\n // the lint that appears within a table and move it up to the\n // table element itself.\n //\n // It is not ideal to have to do this here,\n // but it is cleaner here than fixing up the lint during rendering\n // in perseus-markdown.jsx. If our lint display was simpler and\n // did not require indicators in the margin, this wouldn't be a\n // problem. Or, if we modified the lint display stuff so that\n // indicator positioning and tooltip display were both handled\n // with JavaScript (instead of pure CSS), then we could avoid this\n // issue too. But using JavaScript has its own downsides: there is\n // risk that the linter JavaScript would interfere with\n // widget-related Javascript.\n let tableIssues: LinterIssue[] = [];\n let insideTable = false;\n\n // Traverse through the nodes of the parse tree. At each node, loop\n // through the array of lint rules and check whether there is a\n // lint violation at that node.\n tt.traverse((node, state, content) => {\n const nodeIssues: LinterIssue[] = [];\n\n // Generate a stack so we can identify our position in the tree in\n // lint rules\n const stack = [...context.stack];\n stack.push(node.type);\n\n const nodeContext = {\n ...context,\n stack: stack.join(\".\"),\n } as const;\n\n allRules().forEach((rule) => {\n const ruleIssues = rule.check(node, state, content, nodeContext);\n for (const issue of ruleIssues) {\n // The start and end locations are relative to this\n // particular node, and so are not generally very useful.\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (issue.start || issue.end) {\n issue.target = content.substring(issue.start, issue.end);\n }\n\n // Add the issue to the list of all lint we've found\n issues.push(issue);\n\n // If we're going to be highlighting lint, then we also\n // need to keep track of issues specific to this node.\n if (highlight) {\n nodeIssues.push(issue);\n }\n }\n });\n\n // If we're not highlighting lint in the tree, then we're done\n // traversing this node.\n if (!highlight) {\n return;\n }\n\n // If the node we are currently at is a table, and there was lint\n // inside the table, then we want to add that lint here\n if (node.type === \"table\") {\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (tableIssues.length) {\n nodeIssues.push(...tableIssues);\n }\n\n // We're not in a table anymore, and don't have to remember\n // the issues for the table\n insideTable = false;\n tableIssues = [];\n } else if (!insideTable) {\n // Otherwise, if we are not already inside a table, check\n // to see if we've entered one. Because this is a post-order\n // traversal we'll see the table contents before the table itself.\n // Note that once we're inside the table, we don't have to\n // do this check each time... We can just wait until we ascend\n // up to the table, then we'll know we're out of it.\n insideTable = state.ancestors().some((n) => n.type === \"table\");\n }\n\n // If we are inside a table and there were any issues on\n // this node, then we need to save the issues for display\n // on the table itself\n if (insideTable && nodeIssues.length > 0) {\n tableIssues.push(...nodeIssues);\n }\n\n // If there were any issues on this node, and if we're highlighting\n // lint, then reparent the node so we can highlight it. Note that\n // a single node can have multiple issues. If this happends we\n // concatenate the issues and newline separate them. (The lint.jsx\n // component that displays the issues may want to convert the\n // newlines into <br> tags.) We also provide a lint rule name\n // so that lint.jsx can link to a document that provides more details\n // on that particular lint rule. If there is more than one issue\n // we only link to the first rule, however.\n //\n // Note that even if we're inside a table, we still reparent the\n // linty node so that it can be highlighted. We just make a note\n // of whether this lint is inside a table or not.\n if (nodeIssues.length > 0) {\n nodeIssues.sort((a, b) => {\n return a.severity - b.severity;\n });\n\n if (node.type !== \"text\" || nodeIssues.length > 1) {\n // If the linty node is not a text node, or if there is more\n // than one issue on a text node, then reparent the entire\n // node under a new lint node and put the issues there.\n state.replace({\n type: \"lint\",\n content: node,\n message: nodeIssues.map((w) => w.message).join(\"\\n\\n\"),\n ruleName: nodeIssues[0].rule,\n blockHighlight: nodeContext.blockHighlight,\n insideTable: insideTable,\n severity: nodeIssues[0].severity,\n });\n } else {\n //\n // Otherwise, it is a single issue on a text node, and we\n // only want to highlight the actual linty part of that string\n // of text. So we want to replace the text node with (in the\n // general case) three nodes:\n //\n // 1) A new text node that holds the non-linty prefix\n //\n // 2) A lint node that is the parent of a new text node\n // that holds the linty part\n //\n // 3) A new text node that holds the non-linty suffix\n //\n // If the lint begins and/or ends at the boundaries of the\n // original text node, then nodes 1 and/or 3 won't exist, of\n // course.\n //\n // Note that we could generalize this to work with multple\n // issues on a text node as long as the issues are\n // non-overlapping. Hopefully, though, multiple issues in a\n // single text node will be rare in practice. Also, we don't\n // have a good way to display multiple lint indicators on a\n // single line, so keeping them combined in that case might\n // be the best thing, anyway.\n //\n const content = node.content; // Text nodes have content\n const issue = nodeIssues[0]; // There is only one issue.\n // These are the lint boundaries within the content\n const start = issue.start;\n const end = issue.end;\n const prefix = content.substring(0, start);\n const lint = content.substring(start, end);\n const suffix = content.substring(end);\n const replacements: TreeNode[] = []; // What we'll replace the node with\n\n // The prefix text node, if there is one\n if (prefix) {\n replacements.push({\n type: \"text\",\n content: prefix,\n });\n }\n\n // The lint node wrapped around the linty text\n replacements.push({\n type: \"lint\",\n content: {\n type: \"text\",\n content: lint,\n },\n message: issue.message,\n ruleName: issue.rule,\n insideTable: insideTable,\n severity: issue.severity,\n });\n\n // The suffix node, if there is one\n if (suffix) {\n replacements.push({\n type: \"text\",\n content: suffix,\n });\n }\n\n // Now replace the lint text node with the one to three\n // nodes in the replacement array\n state.replace(...replacements);\n }\n }\n });\n\n return issues;\n}\n","export {libVersion} from \"./version\";\n\nexport {linterContextDefault} from \"./proptypes\";\n\nexport {default as Rule} from \"./rule\";\nexport {runLinter} from \"./run-linter\";\n\nexport type {LinterIssue} from \"./rule\";\nexport type {LinterContextProps} from \"./types\";\n\nexport function pushContextStack(context: any, name: string): any {\n const stack = context.stack || [];\n return {\n ...context,\n stack: stack.concat(name),\n };\n}\n\nexport {\n lintPerseusArticle,\n lintPerseusItem,\n lintPerseusRenderer,\n type ItemLinterIssues,\n} from \"./lint-content\";\n"],"mappings":";;;;;;IAMM4C,IAAU,+BACHC,IAAa;AAE1BC,EAAgCF,GAASC,CAAU;;;ACPnD,IAAaE,KAA2C;CACpD,aAAa;CACb,eAAe;CACf,OAAO,CAAC;AACZ,GCAaC,IAAW;CACpB,OAAO;CACP,SAAS;CACT,WAAW;AACf;AAWA,SAAgB,cAAc,GAAiB,GAA6B;CACxE,OAAO;EACH;EACA,UAAUA,EAAS;EACnB,GAAGC;CACP;AACJ;AAEA,SAAgB,YAAY,GAAiB,GAA6B;CACtE,OAAO;EACH;EACA,UAAUD,EAAS;EACnB,GAAGC;CACP;AACJ;AAEA,SAAgB,gBAAgB,GAAiB,GAA6B;CAC1E,OAAO;EACH;EACA,UAAUD,EAAS;EACnB,GAAGC;CACP;AACJ;;;ACmDA,IAAqB,WAArB,MAA8B;CAC1B,OAAO,MAAM,GAAgC;EACzC,OAAO,IAAIC,EAAOC,CAAY,CAAC,CAAC,MAAM;CAC1C;CAOA,MAAM,GAAmE;EACrE,MAAM,IAAIC,EACN,8CACAC,EAAO,UACX;CACJ;CAMA,WAAmB;EACf,OAAO;CACX;AACJ,GAWMH,IAAN,MAAM,OAAO;CAKT,YAAY,GAAW;EASnB,AALA,IAAII,EAAE,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG,GAIhC,KAAK,SAASA,EAAE,MAAM,OAAO,MAAM,KAAK,CAAC,GACzC,KAAK,aAAa;CACtB;CAGA,YAAoB;EAChB,OAAO,KAAK,OAAO,KAAK,eAAe;CAC3C;CAIA,UAAgB;EACZ,KAAK;CACT;CAGA,eAAwB;EAGpB,IAAMC,IAAI,KAAK,OAAO,KAAK,WAAW,CAAC;EACvC,OAAQA,KAAK,OAAOA,KAAK,OAASA,KAA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E,CAAC;GAC5B,CAAC;QACE;IA0BH,IAAM/L,IAAUd,EAAK,SACf4D,IAAQiJ,EAAW,IAEnBQ,IAAQzJ,EAAM,OACd0J,IAAM1J,EAAM,KACZ2J,IAASzM,EAAQ,UAAU,GAAGuM,CAAK,GACnC3M,IAAOI,EAAQ,UAAUuM,GAAOC,CAAG,GACnCE,IAAS1M,EAAQ,UAAUwM,CAAG,GAC9BpB,IAA2B,CAAC;IAiClC,AA9BIqB,KACArB,EAAa,KAAK;KACd,MAAM;KACN,SAASqB;IACb,CAAC,GAILrB,EAAa,KAAK;KACd,MAAM;KACN,SAAS;MACL,MAAM;MACN,SAASxL;KACb;KACA,SAASkD,EAAM;KACf,UAAUA,EAAM;KACH;KACb,UAAUA,EAAM;IACpB,CAAC,GAGG4J,KACAtB,EAAa,KAAK;KACd,MAAM;KACN,SAASsB;IACb,CAAC,GAKL1N,EAAM,QAAQ,GAAGoM,CAAY;GACjC;EACJ;CACJ,CAAC,GAEMxI;AACX;;;ACxOA,SAAgB,iBAAiB,GAAc,GAAmB;CAC9D,IAAMoJ,IAAQjM,EAAQ,SAAS,CAAC;CAChC,OAAO;EACH,GAAGA;EACH,OAAOiM,EAAM,OAAOrM,CAAI;CAC5B;AACJ"}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"description": "Linter engine for Perseus",
|
|
4
4
|
"author": "Khan Academy",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "8.0.
|
|
6
|
+
"version": "8.0.1",
|
|
7
7
|
"publishConfig": {
|
|
8
8
|
"access": "public"
|
|
9
9
|
},
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
],
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@khanacademy/kas": "3.1.1",
|
|
27
|
-
"@khanacademy/kmath": "3.1.
|
|
28
|
-
"@khanacademy/perseus-core": "42.
|
|
27
|
+
"@khanacademy/kmath": "3.1.6",
|
|
28
|
+
"@khanacademy/perseus-core": "42.3.0",
|
|
29
29
|
"@khanacademy/perseus-utils": "3.0.2",
|
|
30
|
-
"@khanacademy/pure-markdown": "
|
|
30
|
+
"@khanacademy/pure-markdown": "4.0.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@internal/build-settings": "0.9.2"
|