@khanacademy/perseus-linter 6.2.0 → 7.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 CHANGED
@@ -1,185 +1,1141 @@
1
- import { addLibraryVersionToPerseusDebug } from '@khanacademy/perseus-utils';
2
- import { PerseusError, Errors, CoreWidgetRegistry, makeSafeUrl, SORTER_MAX_CARDS } from '@khanacademy/perseus-core';
3
- import * as KAS from '@khanacademy/kas';
4
- import { parse, traverseContent } from '@khanacademy/pure-markdown';
5
- import { vector } from '@khanacademy/kmath';
6
-
7
- const libName="@khanacademy/perseus-linter";const libVersion="6.2.0";addLibraryVersionToPerseusDebug(libName,libVersion);
8
-
9
- const linterContextDefault={contentType:"",highlightLint:false,stack:[]};
10
-
11
- class Selector{static parse(selectorText){return new Parser(selectorText).parse()}match(state){throw new PerseusError("Selector subclasses must implement match()",Errors.NotAllowed)}toString(){return "Unknown selector class"}}class Parser{nextToken(){return this.tokens[this.tokenIndex]||""}consume(){this.tokenIndex++;}isIdentifier(){const c=this.tokens[this.tokenIndex][0];return c>="a"&&c<="z"||c>="A"&&c<="Z"}skipSpace(){while(this.nextToken()===" "){this.consume();}}parse(){const ts=this.parseTreeSelector();let token=this.nextToken();if(!token){return ts}const treeSelectors=[ts];while(token){if(token===","){this.consume();}else {throw new ParseError("Expected comma")}treeSelectors.push(this.parseTreeSelector());token=this.nextToken();}return new SelectorList(treeSelectors)}parseTreeSelector(){this.skipSpace();let ns=this.parseNodeSelector();for(;;){const token=this.nextToken();if(!token||token===","){break}else if(token===" "){this.consume();ns=new AncestorCombinator(ns,this.parseNodeSelector());}else if(token===">"){this.consume();ns=new ParentCombinator(ns,this.parseNodeSelector());}else if(token==="+"){this.consume();ns=new PreviousCombinator(ns,this.parseNodeSelector());}else if(token==="~"){this.consume();ns=new SiblingCombinator(ns,this.parseNodeSelector());}else {throw new ParseError("Unexpected token: "+token)}}return ns}parseNodeSelector(){this.skipSpace();const t=this.nextToken();if(t==="*"){this.consume();return new AnyNode}if(this.isIdentifier()){this.consume();return new TypeSelector(t)}throw new ParseError("Expected node type")}constructor(s){s=s.trim().replace(/\s+/g," ");this.tokens=s.match(Parser.TOKENS)||[];this.tokenIndex=0;}}Parser.TOKENS=/([a-zA-Z][\w-]*)|(\d+)|[^\s]|(\s(?=[a-zA-Z*]))/g;class ParseError extends Error{constructor(message){super(message);}}class SelectorList extends Selector{match(state){for(let i=0;i<this.selectors.length;i++){const s=this.selectors[i];const result=s.match(state);if(result){return result}}return null}toString(){let result="";for(let i=0;i<this.selectors.length;i++){result+=i>0?", ":"";result+=this.selectors[i].toString();}return result}constructor(selectors){super();this.selectors=selectors;}}class AnyNode extends Selector{match(state){return [state.currentNode()]}toString(){return "*"}}class TypeSelector extends Selector{match(state){const node=state.currentNode();if(node.type===this.type){return [node]}return null}toString(){return this.type}constructor(type){super();this.type=type;}}class SelectorCombinator extends Selector{constructor(left,right){super();this.left=left;this.right=right;}}class AncestorCombinator extends SelectorCombinator{match(state){const rightResult=this.right.match(state);if(rightResult){state=state.clone();while(state.hasParent()){state.goToParent();const leftResult=this.left.match(state);if(leftResult){return leftResult.concat(rightResult)}}}return null}toString(){return this.left.toString()+" "+this.right.toString()}constructor(left,right){super(left,right);}}class ParentCombinator extends SelectorCombinator{match(state){const rightResult=this.right.match(state);if(rightResult){if(state.hasParent()){state=state.clone();state.goToParent();const leftResult=this.left.match(state);if(leftResult){return leftResult.concat(rightResult)}}}return null}toString(){return this.left.toString()+" > "+this.right.toString()}constructor(left,right){super(left,right);}}class PreviousCombinator extends SelectorCombinator{match(state){const rightResult=this.right.match(state);if(rightResult){if(state.hasPreviousSibling()){state=state.clone();state.goToPreviousSibling();const leftResult=this.left.match(state);if(leftResult){return leftResult.concat(rightResult)}}}return null}toString(){return this.left.toString()+" + "+this.right.toString()}constructor(left,right){super(left,right);}}class SiblingCombinator extends SelectorCombinator{match(state){const rightResult=this.right.match(state);if(rightResult){state=state.clone();while(state.hasPreviousSibling()){state.goToPreviousSibling();const leftResult=this.left.match(state);if(leftResult){return leftResult.concat(rightResult)}}}return null}toString(){return this.left.toString()+" ~ "+this.right.toString()}constructor(left,right){super(left,right);}}
12
-
13
- class Rule{static makeRule(options){return new Rule(options.name,options.severity,options.selector?Selector.parse(options.selector):null,Rule.makePattern(options.pattern),options.lint||options.message,options.applies)}check(node,traversalState,content,context){const selectorMatch=this.selector.match(traversalState);if(!selectorMatch){return null}let patternMatch;if(this.pattern){patternMatch=content.match(this.pattern);}else {patternMatch=Rule.FakePatternMatch(content,content,0);}if(!patternMatch){return null}try{const error=this.lint(traversalState,content,selectorMatch,patternMatch,context);if(!error){return null}if(typeof error==="string"){return {rule:this.name,severity:this.severity,message:error,start:0,end:content.length}}return {rule:this.name,severity:this.severity,message:error.message,start:error.start,end:error.end,metadata:error.metadata}}catch(e){return {rule:"lint-rule-failure",severity:this.severity,message:`Exception in rule ${this.name}: ${e.message}
1
+ import { addLibraryVersionToPerseusDebug as e } from "@khanacademy/perseus-utils";
2
+ import { CoreWidgetRegistry as t, Errors as n, PerseusError as r, SORTER_MAX_CARDS as i, makeSafeUrl as a } from "@khanacademy/perseus-core";
3
+ import * as o from "@khanacademy/kas";
4
+ import { parse as s, traverseContent as c } from "@khanacademy/pure-markdown";
5
+ import { vector as l } from "@khanacademy/kmath";
6
+ //#region \0rolldown/runtime.js
7
+ var u = "@khanacademy/perseus-linter", d = "7.0.1";
8
+ e(u, d);
9
+ //#endregion
10
+ //#region packages/perseus-linter/src/proptypes.ts
11
+ var f = {
12
+ contentType: "",
13
+ highlightLint: !1,
14
+ stack: []
15
+ }, Selector = class {
16
+ static parse(e) {
17
+ return new p(e).parse();
18
+ }
19
+ match(e) {
20
+ throw new r("Selector subclasses must implement match()", n.NotAllowed);
21
+ }
22
+ toString() {
23
+ return "Unknown selector class";
24
+ }
25
+ }, p = class Parser {
26
+ constructor(e) {
27
+ e = e.trim().replace(/\s+/g, " "), this.tokens = e.match(Parser.TOKENS) || [], this.tokenIndex = 0;
28
+ }
29
+ nextToken() {
30
+ return this.tokens[this.tokenIndex] || "";
31
+ }
32
+ consume() {
33
+ this.tokenIndex++;
34
+ }
35
+ isIdentifier() {
36
+ let e = this.tokens[this.tokenIndex][0];
37
+ return e >= "a" && e <= "z" || e >= "A" && e <= "Z";
38
+ }
39
+ skipSpace() {
40
+ for (; this.nextToken() === " ";) this.consume();
41
+ }
42
+ parse() {
43
+ let e = this.parseTreeSelector(), t = this.nextToken();
44
+ if (!t) return e;
45
+ let n = [e];
46
+ for (; t;) {
47
+ if (t === ",") this.consume();
48
+ else throw new ParseError("Expected comma");
49
+ n.push(this.parseTreeSelector()), t = this.nextToken();
50
+ }
51
+ return new SelectorList(n);
52
+ }
53
+ parseTreeSelector() {
54
+ this.skipSpace();
55
+ let e = this.parseNodeSelector();
56
+ for (;;) {
57
+ let t = this.nextToken();
58
+ if (!t || t === ",") break;
59
+ if (t === " ") this.consume(), e = new AncestorCombinator(e, this.parseNodeSelector());
60
+ else if (t === ">") this.consume(), e = new ParentCombinator(e, this.parseNodeSelector());
61
+ else if (t === "+") this.consume(), e = new PreviousCombinator(e, this.parseNodeSelector());
62
+ else if (t === "~") this.consume(), e = new SiblingCombinator(e, this.parseNodeSelector());
63
+ else throw new ParseError("Unexpected token: " + t);
64
+ }
65
+ return e;
66
+ }
67
+ parseNodeSelector() {
68
+ this.skipSpace();
69
+ let e = this.nextToken();
70
+ if (e === "*") return this.consume(), new AnyNode();
71
+ if (this.isIdentifier()) return this.consume(), new TypeSelector(e);
72
+ throw new ParseError("Expected node type");
73
+ }
74
+ };
75
+ p.TOKENS = /([a-zA-Z][\w-]*)|(\d+)|[^\s]|(\s(?=[a-zA-Z*]))/g;
76
+ var ParseError = class extends Error {
77
+ constructor(e) {
78
+ super(e);
79
+ }
80
+ }, SelectorList = class extends Selector {
81
+ constructor(e) {
82
+ super(), this.selectors = e;
83
+ }
84
+ match(e) {
85
+ for (let t = 0; t < this.selectors.length; t++) {
86
+ let n = this.selectors[t].match(e);
87
+ if (n) return n;
88
+ }
89
+ return null;
90
+ }
91
+ toString() {
92
+ let e = "";
93
+ for (let t = 0; t < this.selectors.length; t++) e += t > 0 ? ", " : "", e += this.selectors[t].toString();
94
+ return e;
95
+ }
96
+ }, AnyNode = class extends Selector {
97
+ match(e) {
98
+ return [e.currentNode()];
99
+ }
100
+ toString() {
101
+ return "*";
102
+ }
103
+ }, TypeSelector = class extends Selector {
104
+ constructor(e) {
105
+ super(), this.type = e;
106
+ }
107
+ match(e) {
108
+ let t = e.currentNode();
109
+ return t.type === this.type ? [t] : null;
110
+ }
111
+ toString() {
112
+ return this.type;
113
+ }
114
+ }, SelectorCombinator = class extends Selector {
115
+ constructor(e, t) {
116
+ super(), this.left = e, this.right = t;
117
+ }
118
+ }, AncestorCombinator = class extends SelectorCombinator {
119
+ constructor(e, t) {
120
+ super(e, t);
121
+ }
122
+ match(e) {
123
+ let t = this.right.match(e);
124
+ if (t) for (e = e.clone(); e.hasParent();) {
125
+ e.goToParent();
126
+ let n = this.left.match(e);
127
+ if (n) return n.concat(t);
128
+ }
129
+ return null;
130
+ }
131
+ toString() {
132
+ return this.left.toString() + " " + this.right.toString();
133
+ }
134
+ }, ParentCombinator = class extends SelectorCombinator {
135
+ constructor(e, t) {
136
+ super(e, t);
137
+ }
138
+ match(e) {
139
+ let t = this.right.match(e);
140
+ if (t && e.hasParent()) {
141
+ e = e.clone(), e.goToParent();
142
+ let n = this.left.match(e);
143
+ if (n) return n.concat(t);
144
+ }
145
+ return null;
146
+ }
147
+ toString() {
148
+ return this.left.toString() + " > " + this.right.toString();
149
+ }
150
+ }, PreviousCombinator = class extends SelectorCombinator {
151
+ constructor(e, t) {
152
+ super(e, t);
153
+ }
154
+ match(e) {
155
+ let t = this.right.match(e);
156
+ if (t && e.hasPreviousSibling()) {
157
+ e = e.clone(), e.goToPreviousSibling();
158
+ let n = this.left.match(e);
159
+ if (n) return n.concat(t);
160
+ }
161
+ return null;
162
+ }
163
+ toString() {
164
+ return this.left.toString() + " + " + this.right.toString();
165
+ }
166
+ }, SiblingCombinator = class extends SelectorCombinator {
167
+ constructor(e, t) {
168
+ super(e, t);
169
+ }
170
+ match(e) {
171
+ let t = this.right.match(e);
172
+ if (t) for (e = e.clone(); e.hasPreviousSibling();) {
173
+ e.goToPreviousSibling();
174
+ let n = this.left.match(e);
175
+ if (n) return n.concat(t);
176
+ }
177
+ return null;
178
+ }
179
+ toString() {
180
+ return this.left.toString() + " ~ " + this.right.toString();
181
+ }
182
+ }, m, h = class Rule {
183
+ constructor(e, t, i, a, o, s) {
184
+ if (!i && !a) throw new r("Lint rules must have a selector or pattern", n.InvalidInput, { metadata: { name: e } });
185
+ this.name = e || "unnamed rule", this.severity = t, this.selector = i || Rule.DEFAULT_SELECTOR, this.pattern = a || null, typeof o == "function" ? (this.lint = o, this.message = null) : (this.lint = (...e) => this._defaultLintFunction(...e), this.message = o), this.applies = s || function() {
186
+ return !0;
187
+ };
188
+ }
189
+ static makeRule(e) {
190
+ return new Rule(e.name, e.severity, e.selector ? Selector.parse(e.selector) : null, Rule.makePattern(e.pattern), e.lint || e.message, e.applies);
191
+ }
192
+ static makeWidgetRule(e) {
193
+ return new Rule(e.name, e.severity, Selector.parse("widget"), null, (t, n, r, i, a) => {
194
+ if (t.currentNode().widgetType !== e.widgetType) return;
195
+ let o = t.currentNode().id;
196
+ if (!o) return;
197
+ let s = a?.widgets?.[o];
198
+ if (!s) return;
199
+ let c = e.lint(s);
200
+ if (c) return `${o}: ${c}`;
201
+ }, void 0);
202
+ }
203
+ check(e, t, n, r) {
204
+ let i = this.selector.match(t);
205
+ if (!i) return null;
206
+ let a;
207
+ if (a = this.pattern ? n.match(this.pattern) : Rule.FakePatternMatch(n, n, 0), !a) return null;
208
+ try {
209
+ let e = this.lint(t, n, i, a, r);
210
+ return e ? typeof e == "string" ? {
211
+ rule: this.name,
212
+ severity: this.severity,
213
+ message: e,
214
+ start: 0,
215
+ end: n.length
216
+ } : {
217
+ rule: this.name,
218
+ severity: this.severity,
219
+ message: e.message,
220
+ start: e.start,
221
+ end: e.end,
222
+ metadata: e.metadata
223
+ } : null;
224
+ } catch (e) {
225
+ return {
226
+ rule: "lint-rule-failure",
227
+ severity: this.severity,
228
+ message: `Exception in rule ${this.name}: ${e.message}
14
229
  Stack trace:
15
- ${e.stack}`,start:0,end:content.length}}}_defaultLintFunction(state,content,selectorMatch,patternMatch,context){return {message:this.message||"",start:patternMatch.index,end:patternMatch.index+patternMatch[0].length}}static makePattern(pattern){if(!pattern){return null}if(pattern instanceof RegExp){return pattern}if(pattern[0]==="/"){const lastSlash=pattern.lastIndexOf("/");const expression=pattern.substring(1,lastSlash);const flags=pattern.substring(lastSlash+1);return new RegExp(expression,flags)}return new RegExp(pattern)}static FakePatternMatch(input,match,index){const result=[match];result.index=index;result.input=input;return result}constructor(name,severity,selector,pattern,lint,applies){if(!selector&&!pattern){throw new PerseusError("Lint rules must have a selector or pattern",Errors.InvalidInput,{metadata:{name}})}this.name=name||"unnamed rule";this.severity=severity||Rule.Severity.BULK_WARNING;this.selector=selector||Rule.DEFAULT_SELECTOR;this.pattern=pattern||null;if(typeof lint==="function"){this.lint=lint;this.message=null;}else {this.lint=(...args)=>this._defaultLintFunction(...args);this.message=lint;}this.applies=applies||function(){return true};}}Rule.Severity={ERROR:1,WARNING:2,GUIDELINE:3,BULK_WARNING:4};Rule.DEFAULT_SELECTOR=Selector.parse("text");
16
-
17
- const HOSTNAME=/\/\/([^/]+)/;function getHostname(url){if(!url){return ""}const match=url.match(HOSTNAME);return match?match[1]:""}
18
-
19
- var AbsoluteUrl = Rule.makeRule({name:"absolute-url",severity:Rule.Severity.GUIDELINE,selector:"link, image",lint:function(state,content,nodes,match){const url=nodes[0].target;const hostname=getHostname(url);if(hostname==="khanacademy.org"||hostname.endsWith(".khanacademy.org")){return `Don't use absolute URLs:
20
- When linking to KA content or images, omit the
21
- https://www.khanacademy.org URL prefix.
22
- Use a relative URL beginning with / instead.`}}});
23
-
24
- var DoubleSpacingAfterTerminal = Rule.makeRule({name:"double-spacing-after-terminal",severity:Rule.Severity.BULK_WARNING,selector:"paragraph",pattern:/[.!?] {2}/i,message:`Use a single space after a sentence-ending period, or
25
- any other kind of terminal punctuation.`});
26
-
27
- function hasExplanation(widgets){return Object.values(widgets).some(widget=>widget.type==="explanation")}var ExplanationInGradedGroup = Rule.makeRule({name:"explanation-in-graded-group",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const message=location=>`Explanation widget in ${location}: Use the Graded Group Hint instead.`;if(widget.type==="graded-group"){const options=widget.options;if(hasExplanation(options.widgets)){return message(nodeId)}}if(widget.type==="graded-group-set"){const options=widget.options;const groupNumbers=options.gradedGroups.map((group,i)=>hasExplanation(group.widgets)?i+1:0).filter(groupNumber=>groupNumber>0);if(groupNumbers.length>0){return message(`${nodeId}, group ${groupNumbers.join(" and ")}`)}}}});
28
-
29
- function buttonNotInButtonSet(name,set){return `Answer requires a button not found in the button sets: ${name} (in ${set})`}const stringToButtonSet={"\\sqrt":"prealgebra","^":"prealgebra","\\sin":"trig","\\cos":"trig","\\tan":"trig","\\log":"logarithms","\\ln":"logarithms"};var ExpressionWidget = Rule.makeRule({name:"expression-widget",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="expression"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const answers=widget.options.answerForms;const buttons=widget.options.buttonSets;for(const answer of answers){for(const[str,set]of Object.entries(stringToButtonSet)){if(answer.value.includes(str)&&!buttons.includes(set)){return buttonNotInButtonSet(str,set)}}}}});
30
-
31
- var ExpressionWidgetError = Rule.makeRule({name:"expression-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="expression"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context&&context.widgets&&context.widgets[nodeId];if(!widget){return}const issues=[];const{answerForms,functions}=widget.options;if(answerForms.length===0){issues.push("No answers specified.");}else {const hasCorrect=answerForms.some(form=>{return form.considered==="correct"});if(!hasCorrect){issues.push("No correct answer specified.");}answerForms.forEach((form,ix)=>{if(form.value===""){issues.push(`Answer ${ix+1} is empty.`);}else {const expression=KAS.parse(form.value,{functions:functions});if(!expression.parsed){issues.push(`Couldn't parse ${form.value}.`);}else if(form.simplify&&!expression.expr.isSimplified()){issues.push(`${form.value} isn't simplified, but is required to be.`);}}});}const allWarningsString=issues.join("\n\n");return allWarningsString}});
32
-
33
- var ExtraContentSpacing = Rule.makeRule({name:"extra-content-spacing",selector:"paragraph",pattern:/\s+$/,applies:function(context){return context?.contentType==="article"},message:`No extra whitespace at the end of content blocks.`});
34
-
35
- const rWidgetRule=/\[\[\u2603 (([a-z-]+) ([0-9]+))\]\]/;var FreeResponseWidgetError = Rule.makeRule({name:"free-response-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="free-response"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context&&context.widgets&&context.widgets[nodeId];if(!widget){return}const question=widget.options.question;if(!question){return "The question is empty"}if(question.match(rWidgetRule)!=null){return "The question contains a widget"}}});
36
-
37
- var HeadingLevel1 = Rule.makeRule({name:"heading-level-1",severity:Rule.Severity.WARNING,selector:"heading",lint:function(state,content,nodes,match){if(nodes[0].level===1){return `Don't use level-1 headings:
38
- Begin headings with two or more # characters.`}}});
39
-
40
- var HeadingLevelSkip = Rule.makeRule({name:"heading-level-skip",severity:Rule.Severity.WARNING,selector:"heading ~ heading",lint:function(state,content,nodes,match){const currentHeading=nodes[1];const previousHeading=nodes[0];if(currentHeading.level>previousHeading.level+1){return `Skipped heading level:
41
- this heading is level ${currentHeading.level} but
42
- the previous heading was level ${previousHeading.level}`}}});
43
-
44
- var HeadingSentenceCase = Rule.makeRule({name:"heading-sentence-case",severity:Rule.Severity.GUIDELINE,selector:"heading",pattern:/^\W*[a-z]/,message:`First letter is lowercase:
45
- the first letter of a heading should be capitalized.`});
46
-
47
- const littleWords={and:true,nor:true,but:true,the:true,for:true};function isCapitalized(word){const c=word[0];return c===c.toUpperCase()}var HeadingTitleCase = Rule.makeRule({name:"heading-title-case",severity:Rule.Severity.GUIDELINE,selector:"heading",pattern:/[^\s:]\s+[A-Z]+[a-z]/,locale:"en",lint:function(state,content,nodes,match){const heading=content.trim();let words=heading.split(/\s+/);words.shift();words=words.filter(w=>w.length>2&&!littleWords.hasOwnProperty(w));if(words.length>=3&&words.every(w=>isCapitalized(w))){return `Title-case heading:
48
- This heading appears to be in title-case, but should be sentence-case.
49
- Only capitalize the first letter and proper nouns.`}}});
50
-
51
- var ImageAltText = Rule.makeRule({name:"image-alt-text",severity:Rule.Severity.WARNING,selector:"image",lint:function(state,content,nodes,match){const image=nodes[0];if(!image.alt||!image.alt.trim()){return `Images should have alt text:
52
- for accessibility, all images should have alt text.
53
- Specify alt text inside square brackets after the !.`}if(image.alt.length<8){return `Images should have alt text:
230
+ ${e.stack}`,
231
+ start: 0,
232
+ end: n.length
233
+ };
234
+ }
235
+ }
236
+ _defaultLintFunction(e, t, n, r, i) {
237
+ return {
238
+ message: this.message || "",
239
+ start: r.index,
240
+ end: r.index + r[0].length
241
+ };
242
+ }
243
+ static makePattern(e) {
244
+ if (!e) return null;
245
+ if (e instanceof RegExp) return e;
246
+ if (e[0] === "/") {
247
+ let t = e.lastIndexOf("/"), n = e.substring(1, t), r = e.substring(t + 1);
248
+ return new RegExp(n, r);
249
+ }
250
+ return new RegExp(e);
251
+ }
252
+ static FakePatternMatch(e, t, n) {
253
+ let r = [t];
254
+ return r.index = n, r.input = e, r;
255
+ }
256
+ };
257
+ m = h, m.Severity = {
258
+ ERROR: 1,
259
+ WARNING: 2,
260
+ GUIDELINE: 3
261
+ }, h.DEFAULT_SELECTOR = Selector.parse("text");
262
+ //#endregion
263
+ //#region packages/perseus-linter/src/rules/lint-utils.ts
264
+ var ee = /\/\/([^/]+)/;
265
+ function getHostname(e) {
266
+ if (!e) return "";
267
+ let t = e.match(ee);
268
+ return t ? t[1] : "";
269
+ }
270
+ //#endregion
271
+ //#region packages/perseus-linter/src/rules/absolute-url.ts
272
+ var g = h.makeRule({
273
+ name: "absolute-url",
274
+ severity: h.Severity.GUIDELINE,
275
+ selector: "link, image",
276
+ lint: function(e, t, n, r) {
277
+ let i = n[0].target, a = getHostname(i);
278
+ if (a === "khanacademy.org" || a.endsWith(".khanacademy.org")) return "Don't use absolute URLs:\nWhen linking to KA content or images, omit the\nhttps://www.khanacademy.org URL prefix.\nUse a relative URL beginning with / instead.";
279
+ }
280
+ });
281
+ //#endregion
282
+ //#region packages/perseus-linter/src/rules/explanation-in-graded-group.ts
283
+ function hasExplanation(e) {
284
+ return Object.values(e).some((e) => e.type === "explanation");
285
+ }
286
+ var _ = "Don't use explanation widgets in graded groups. Use the Graded Group Hint instead.", te = h.makeWidgetRule({
287
+ name: "explanation-in-graded-group",
288
+ severity: h.Severity.WARNING,
289
+ widgetType: "graded-group",
290
+ lint: function(e) {
291
+ if (hasExplanation(e.options.widgets)) return `Contains explanation widget. ${_}`;
292
+ }
293
+ }), ne = h.makeWidgetRule({
294
+ name: "explanation-in-graded-group-set",
295
+ severity: h.Severity.WARNING,
296
+ widgetType: "graded-group-set",
297
+ lint: function(e) {
298
+ let t = e.options.gradedGroups.map((e, t) => hasExplanation(e.widgets) ? t + 1 : 0).filter((e) => e > 0);
299
+ if (t.length > 0) return `Explanation widget in group ${t.join(" and ")}. ${_}`;
300
+ }
301
+ });
302
+ //#endregion
303
+ //#region packages/perseus-linter/src/rules/expression-widget.ts
304
+ function buttonNotInButtonSet(e, t) {
305
+ return `Answer requires a button not found in the button sets: ${e} (in ${t})`;
306
+ }
307
+ var re = {
308
+ "\\sqrt": "prealgebra",
309
+ "^": "prealgebra",
310
+ "\\sin": "trig",
311
+ "\\cos": "trig",
312
+ "\\tan": "trig",
313
+ "\\log": "logarithms",
314
+ "\\ln": "logarithms"
315
+ }, ie = h.makeWidgetRule({
316
+ name: "expression-widget-buttons",
317
+ widgetType: "expression",
318
+ severity: h.Severity.WARNING,
319
+ lint(e) {
320
+ let t = e.options.answerForms, n = e.options.buttonSets;
321
+ for (let e of t) for (let [t, r] of Object.entries(re)) if (e.value.includes(t) && !n.includes(r)) return buttonNotInButtonSet(t, r);
322
+ }
323
+ }), v = h.makeWidgetRule({
324
+ name: "expression-widget-correct-answer",
325
+ widgetType: "expression",
326
+ severity: h.Severity.ERROR,
327
+ lint(e) {
328
+ let { answerForms: t } = e.options;
329
+ if (t.length === 0) return "No answers specified.";
330
+ if (!t.some((e) => e.considered === "correct")) return "No correct answer specified.";
331
+ }
332
+ }), y = h.makeWidgetRule({
333
+ name: "expression-widget-answer-forms",
334
+ widgetType: "expression",
335
+ severity: h.Severity.ERROR,
336
+ lint(e) {
337
+ let { answerForms: t, functions: n } = e.options, r = [];
338
+ return t.forEach((e, t) => {
339
+ if (e.value === "") {
340
+ r.push(`Answer ${t + 1} is empty.`);
341
+ return;
342
+ }
343
+ let i = o.parse(e.value, { functions: n });
344
+ i.parsed ? e.simplify && !i.expr.isSimplified() && r.push(`${e.value} isn't simplified, but is required to be.`) : r.push(`Couldn't parse ${e.value}.`);
345
+ }), r.join("\n\n");
346
+ }
347
+ }), b = /\[\[\u2603 (([a-z-]+) ([0-9]+))\]\]/, x = h.makeRule({
348
+ name: "free-response-widget-error",
349
+ severity: h.Severity.ERROR,
350
+ selector: "widget",
351
+ lint: function(e, t, n, r, i) {
352
+ if (e.currentNode().widgetType !== "free-response") return;
353
+ let a = e.currentNode().id;
354
+ if (!a) return;
355
+ let o = i && i.widgets && i.widgets[a];
356
+ if (!o) return;
357
+ let s = o.options.question;
358
+ if (!s) return "The question is empty";
359
+ if (s.match(b) != null) return "The question contains a widget";
360
+ }
361
+ }), S = h.makeRule({
362
+ name: "heading-level-1",
363
+ severity: h.Severity.WARNING,
364
+ selector: "heading",
365
+ lint: function(e, t, n, r) {
366
+ if (n[0].level === 1) return "Don't use level-1 headings:\nBegin headings with two or more # characters.";
367
+ }
368
+ }), C = h.makeRule({
369
+ name: "heading-level-skip",
370
+ severity: h.Severity.WARNING,
371
+ selector: "heading ~ heading",
372
+ lint: function(e, t, n, r) {
373
+ let i = n[1], a = n[0];
374
+ if (i.level > a.level + 1) return `Skipped heading level:
375
+ this heading is level ${i.level} but
376
+ the previous heading was level ${a.level}`;
377
+ }
378
+ }), w = h.makeRule({
379
+ name: "heading-sentence-case",
380
+ severity: h.Severity.GUIDELINE,
381
+ selector: "heading",
382
+ pattern: /^\W*[a-z]/,
383
+ message: "First letter is lowercase:\nthe first letter of a heading should be capitalized."
384
+ }), T = {
385
+ and: !0,
386
+ nor: !0,
387
+ but: !0,
388
+ the: !0,
389
+ for: !0
390
+ };
391
+ function isCapitalized(e) {
392
+ let t = e[0];
393
+ return t === t.toUpperCase();
394
+ }
395
+ var E = h.makeRule({
396
+ name: "heading-title-case",
397
+ severity: h.Severity.GUIDELINE,
398
+ selector: "heading",
399
+ pattern: /[^\s:]\s+[A-Z]+[a-z]/,
400
+ locale: "en",
401
+ lint: function(e, t, n, r) {
402
+ let i = t.trim().split(/\s+/);
403
+ if (i.shift(), i = i.filter((e) => e.length > 2 && !T.hasOwnProperty(e)), i.length >= 3 && i.every((e) => isCapitalized(e))) return "Title-case heading:\nThis heading appears to be in title-case, but should be sentence-case.\nOnly capitalize the first letter and proper nouns.";
404
+ }
405
+ }), D = h.makeRule({
406
+ name: "image-alt-text",
407
+ severity: h.Severity.WARNING,
408
+ selector: "image",
409
+ lint: function(e, t, n, r) {
410
+ let i = n[0];
411
+ if (!i.alt || !i.alt.trim()) return "Images should have alt text:\nfor accessibility, all images should have alt text.\nSpecify alt text inside square brackets after the !.";
412
+ if (i.alt.length < 8) return `Images should have alt text:
54
413
  for accessibility, all images should have descriptive alt text.
55
- This image's alt text is only ${image.alt.length} characters long.`}}});
56
-
57
- var ImageInTable = Rule.makeRule({name:"image-in-table",severity:Rule.Severity.BULK_WARNING,selector:"table image",message:`Image in table:
58
- do not put images inside of tables.`});
59
-
60
- var ImageMarkdown = Rule.makeRule({name:"image-markdown",severity:Rule.Severity.WARNING,selector:"image",lint:function(state,content,nodes,match,context){if(context?.stack&&context.stack.includes("widget")){return null}const parsedMarkdown=parse(context?.content||"",{});let hasInlineImageNode=false;traverseContent(parsedMarkdown,node=>{if(node.type==="image"){hasInlineImageNode=true;}});if(hasInlineImageNode){return `[Inline markdown image]:
61
- Markdown images are not recommended - these are images that use the
62
- ![alt](url) format. Please use the Image widget instead.`}return null}});
63
-
64
- var ImageSpacesAroundUrls = Rule.makeRule({name:"image-spaces-around-urls",severity:Rule.Severity.ERROR,selector:"image",lint:function(state,content,nodes,match,context){const image=nodes[0];const url=image.target;if(context&&context.content){const index=context.content.indexOf(url);if(index===-1){return}if(context.content[index-1]!=="("||context.content[index+url.length]!==")"){return `Whitespace before or after image url:
65
- For images, don't include any space or newlines after '(' or before ')'.
66
- Whitespace in image URLs causes translation difficulties.`}}}});
67
-
68
- var ImageUrlEmpty = Rule.makeRule({name:"image-url-empty",severity:Rule.Severity.ERROR,selector:"image",lint:function(state,content,nodes){const image=nodes[0];const url=image.target;if(!url||!url.trim()){return "Images should have a URL"}}});
69
-
70
- var ImageWidgetAltText = Rule.makeRule({name:"image-widget-alt-text",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="image"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context&&context.widgets&&context.widgets[nodeId];if(!widget){return}if(widget.options.decorative){return}const alt=widget.options.alt;if(!alt){return `Images should have alt text:
71
- for accessibility, all images should have a text description.
72
- Add a description in the "Alt Text" box of the image widget.`}if(alt.trim().length<8){return `Images should have alt text:
414
+ This image's alt text is only ${i.alt.length} characters long.`;
415
+ }
416
+ }), O = h.makeRule({
417
+ name: "image-markdown",
418
+ severity: h.Severity.WARNING,
419
+ selector: "image",
420
+ lint: function(e, t, n, r, i) {
421
+ if (i?.stack && i.stack.includes("widget")) return null;
422
+ let a = s(i?.content || "", {}), o = !1;
423
+ return c(a, (e) => {
424
+ e.type === "image" && (o = !0);
425
+ }), o ? "[Inline markdown image]:\nMarkdown images are not recommended - these are images that use the\n![alt](url) format. Please use the Image widget instead." : null;
426
+ }
427
+ }), k = h.makeRule({
428
+ name: "image-spaces-around-urls",
429
+ severity: h.Severity.ERROR,
430
+ selector: "image",
431
+ lint: function(e, t, n, r, i) {
432
+ let a = n[0].target;
433
+ if (i && i.content) {
434
+ let e = i.content.indexOf(a);
435
+ if (e === -1) return;
436
+ if (i.content[e - 1] !== "(" || i.content[e + a.length] !== ")") return "Whitespace before or after image url:\nFor images, don't include any space or newlines after '(' or before ')'.\nWhitespace in image URLs causes translation difficulties.";
437
+ }
438
+ }
439
+ }), A = h.makeRule({
440
+ name: "image-url-empty",
441
+ severity: h.Severity.ERROR,
442
+ selector: "image",
443
+ lint: function(e, t, n) {
444
+ let r = n[0].target;
445
+ if (!r || !r.trim()) return "Images should have a URL";
446
+ }
447
+ }), j = h.makeRule({
448
+ name: "image-widget-alt-text",
449
+ severity: h.Severity.WARNING,
450
+ selector: "widget",
451
+ lint: function(e, t, n, r, i) {
452
+ if (e.currentNode().widgetType !== "image") return;
453
+ let a = e.currentNode().id;
454
+ if (!a) return;
455
+ let o = i && i.widgets && i.widgets[a];
456
+ if (!o || o.options.decorative) return;
457
+ let s = o.options.alt;
458
+ if (!s) return "Images should have alt text:\nfor accessibility, all images should have a text description.\nAdd a description in the \"Alt Text\" box of the image widget.";
459
+ if (s.trim().length < 8) return `Images should have alt text:
73
460
  for accessibility, all images should have descriptive alt text.
74
- This image's alt text is only ${alt.trim().length} characters long.`}if(alt.trim().length>125){return `Images should have alt text:
461
+ This image's alt text is only ${s.trim().length} characters long.`;
462
+ if (s.trim().length > 125) return `Images should have alt text:
75
463
  for accessibility, image alt text should not exceed 125 characters.
76
- This image's alt text is ${alt.trim().length} characters long.
464
+ This image's alt text is ${s.trim().length} characters long.
77
465
  Please pair your alt with a long description below if you need significantly
78
- more text to sufficiently describe the image.`}}});
79
-
80
- var ImageWidgetEmptySize = Rule.makeRule({name:"image-widget-empty-size",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="image"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context&&context.widgets&&context.widgets[nodeId];if(!widget){return}if(!widget.options.backgroundImage.url){return}const{width,height}=widget.options.backgroundImage;if(!width||!height){return `Images should have a non-zero size.
81
- This image has a width of ${width} and a height of ${height}.
82
- Please use the "Reset to original size" button to set the size of the image.`}}});
83
-
84
- var InaccessibleWidget = Rule.makeRule({name:"inaccessible-widget",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){const node=state.currentNode();const widgetType=node.widgetType;const widgetId=node.id;if(!widgetType||!widgetId){return}const widgetInfo=context?.widgets?.[widgetId];if(!widgetInfo){return}const accessible=CoreWidgetRegistry.isAccessible(widgetType,widgetInfo.options);if(!accessible){return {message:`The "${widgetType}" widget is not accessible.`,start:0,end:content.length,metadata:{widgetType:widgetType,widgetId:widgetId}}}}});
85
-
86
- var InteractiveGraphLockedFigureOob = Rule.makeRule({name:"interactive-graph-locked-figure-oob",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="interactive-graph"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const{range,lockedFigures}=widget.options;const warnings=[];for(const figure of lockedFigures??[]){if(!hasPointInRange(figure,range)){const figureType=getPreciseFigureType(figure);const isSinglePoint=figure.type==="point"||figure.type==="label";warnings.push(isSinglePoint?`Locked ${figureType} is outside the graph bounds.`:`All defining points for locked ${figureType} are outside the graph bounds.`);}}return warnings.join("\n\n")}});function getPreciseFigureType(figure){switch(figure.type){case "line":return figure.kind;case "ellipse":return figure.radius[0]===figure.radius[1]?"circle":"ellipse";default:return figure.type}}function isInRange([x,y],range){const[[xMin,xMax],[yMin,yMax]]=range;return x>=xMin&&x<=xMax&&y>=yMin&&y<=yMax}function hasPointInRange(figure,range){if(figure.type==="function"){return true}return definingPoints(figure).some(point=>isInRange(point,range))}function definingPoints(figure){switch(figure.type){case "point":case "label":return [figure.coord];case "line":return figure.points.map(point=>point.coord);case "vector":case "polygon":return figure.points;case "ellipse":{const[cx,cy]=figure.center;const[rx,ry]=figure.radius;return [[cx,cy],[cx+rx,cy],[cx-rx,cy],[cx,cy+ry],[cx,cy-ry]]}}}
87
-
88
- var InteractiveGraphWidgetError = Rule.makeRule({name:"interactive-graph-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="interactive-graph"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const issues=[];const{correct,graph,lockedFigures}=widget.options;for(const figure of lockedFigures??[]){if(figure.type==="line"&&vector.equal(figure.points[0].coord,figure.points[1].coord)){issues.push("Locked line cannot have length 0.");}if(figure.type==="polygon"){if(figure.points.every(point=>vector.equal(point,figure.points[0]))){issues.push("Locked polygon cannot have all coordinates be the same.");}}if(figure.type==="ellipse"){if(figure.radius[0]<=0||figure.radius[1]<=0){issues.push("Locked ellipse must have positive radius values.");}}}if(correct?.type==="polygon"&&correct.numSides==="unlimited"&&correct.coords==null){issues.push("Polygon must be closed.");}if(graph?.type==="exponential"&&graph.startCoords!=null){const{coords,asymptote}=graph.startCoords;const asymptoteY=asymptote;const minY=Math.min(coords[0][1],coords[1][1]);const maxY=Math.max(coords[0][1],coords[1][1]);if(asymptoteY>=minY&&asymptoteY<=maxY){issues.push("The exponential start asymptote must not fall between or on the curve's start points.");}}checkShowPointLabelsHasLabels(graph,issues);checkShowPointLabelsHasLabels(correct,issues);const allIssuesString=issues.join("\n\n");return allIssuesString}});function checkShowPointLabelsHasLabels(g,issues){if(g==null||g.type==="none"||g.type==="vector"){return}if(g.showPointLabels!==true){return}const labels=g.pointLabels;if(labels===undefined||labels.every(l=>l==null||l==="")){issues.push("showPointLabels is true but pointLabels has no labels. Provide a label for at least one point.");return}const expected=expectedLabelCount(g);if(expected!==undefined&&labels.length!==expected){issues.push(`pointLabels has ${labels.length} entries but this graph type expects ${expected}. Use empty strings ("") to skip labels for specific points, e.g. ["A", "", "C"].`);}}function expectedLabelCount(g){switch(g.type){case "angle":case "quadratic":return 3;case "linear":case "ray":case "sinusoid":case "absolute-value":case "exponential":case "logarithm":case "tangent":return 2;case "circle":return 1;case "linear-system":return 4;case "segment":return (g.numSegments??1)*2;case "point":if(g.numPoints==="unlimited"||g.numPoints==null){return undefined}return g.numPoints;case "polygon":if(g.numSides==="unlimited"||g.numSides==null){return undefined}return g.numSides;default:return undefined}}
89
-
90
- var LabelImageWidgetError = Rule.makeRule({name:"label-image-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="label-image"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const warnings=[];const{choices,imageAlt,imageUrl,markers}=widget.options;if(choices.length<2){warnings.push("label-image widget must have at least two answer choices");}if(!imageUrl){warnings.push("No image url provided");}else if(!imageAlt){warnings.push("No image alt text provided");}if(!markers.length){warnings.push("label-image widget requires at least one marker");}else {let numNoAnswers=0;let numNoLabels=0;for(const marker of markers){if(!marker.answers.length){numNoAnswers++;}if(!marker.label){numNoLabels++;}}if(numNoAnswers>0){warnings.push(`label-image widget has ${numNoAnswers} markers with no answers selected`);}if(numNoLabels>0){warnings.push(`label-image widget has ${numNoLabels} markers with no ARIA label`);}}const allWarningsString=warnings.join("\n\n");return allWarningsString}});
91
-
92
- const LEGACY_HOSTNAME="ka-perseus-images.s3.amazonaws.com";var LegacyGifUrl = Rule.makeRule({name:"legacy-gif-url",severity:Rule.Severity.GUIDELINE,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="image"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context&&context.widgets&&context.widgets[nodeId];if(!widget){return}const url=widget.options?.backgroundImage?.url;if(!url){return}if(getHostname(url)===LEGACY_HOSTNAME&&url.toLowerCase().endsWith(".gif")){return `Legacy gif URL:
93
- gifs hosted at ${LEGACY_HOSTNAME} might not appear in the editor preview,
466
+ more text to sufficiently describe the image.`;
467
+ }
468
+ }), M = h.makeRule({
469
+ name: "image-widget-empty-size",
470
+ severity: h.Severity.WARNING,
471
+ selector: "widget",
472
+ lint: function(e, t, n, r, i) {
473
+ if (e.currentNode().widgetType !== "image") return;
474
+ let a = e.currentNode().id;
475
+ if (!a) return;
476
+ let o = i && i.widgets && i.widgets[a];
477
+ if (!o || !o.options.backgroundImage.url) return;
478
+ let { width: s, height: c } = o.options.backgroundImage;
479
+ if (!s || !c) return `Images should have a non-zero size.
480
+ This image has a width of ${s} and a height of ${c}.
481
+ Please use the "Reset to original size" button to set the size of the image.`;
482
+ }
483
+ }), N = h.makeRule({
484
+ name: "inaccessible-widget",
485
+ severity: h.Severity.WARNING,
486
+ selector: "widget",
487
+ lint: function(e, n, r, i, a) {
488
+ let o = e.currentNode(), s = o.widgetType, c = o.id;
489
+ if (!s || !c) return;
490
+ let l = a?.widgets?.[c];
491
+ if (l && !t.isAccessible(s, l.options)) return {
492
+ message: `The "${s}" widget is not accessible.`,
493
+ start: 0,
494
+ end: n.length,
495
+ metadata: {
496
+ widgetType: s,
497
+ widgetId: c
498
+ }
499
+ };
500
+ }
501
+ }), P = h.makeRule({
502
+ name: "interactive-graph-locked-figure-oob",
503
+ severity: h.Severity.WARNING,
504
+ selector: "widget",
505
+ lint: function(e, t, n, r, i) {
506
+ if (e.currentNode().widgetType !== "interactive-graph") return;
507
+ let a = e.currentNode().id;
508
+ if (!a) return;
509
+ let o = i?.widgets?.[a];
510
+ if (!o) return;
511
+ let { range: s, lockedFigures: c } = o.options, l = [];
512
+ for (let e of c ?? []) if (!hasPointInRange(e, s)) {
513
+ let t = getPreciseFigureType(e), n = e.type === "point" || e.type === "label";
514
+ l.push(n ? `Locked ${t} is outside the graph bounds.` : `All defining points for locked ${t} are outside the graph bounds.`);
515
+ }
516
+ return l.join("\n\n");
517
+ }
518
+ });
519
+ function getPreciseFigureType(e) {
520
+ switch (e.type) {
521
+ case "line": return e.kind;
522
+ case "ellipse": return e.radius[0] === e.radius[1] ? "circle" : "ellipse";
523
+ default: return e.type;
524
+ }
525
+ }
526
+ function isInRange([e, t], n) {
527
+ let [[r, i], [a, o]] = n;
528
+ return e >= r && e <= i && t >= a && t <= o;
529
+ }
530
+ function hasPointInRange(e, t) {
531
+ return e.type === "function" || definingPoints(e).some((e) => isInRange(e, t));
532
+ }
533
+ function definingPoints(e) {
534
+ switch (e.type) {
535
+ case "point":
536
+ case "label": return [e.coord];
537
+ case "line": return e.points.map((e) => e.coord);
538
+ case "vector":
539
+ case "polygon": return e.points;
540
+ case "ellipse": {
541
+ let [t, n] = e.center, [r, i] = e.radius;
542
+ return [
543
+ [t, n],
544
+ [t + r, n],
545
+ [t - r, n],
546
+ [t, n + i],
547
+ [t, n - i]
548
+ ];
549
+ }
550
+ }
551
+ }
552
+ //#endregion
553
+ //#region packages/perseus-linter/src/rules/interactive-graph-widget-error.ts
554
+ var F = h.makeRule({
555
+ name: "interactive-graph-widget-error",
556
+ severity: h.Severity.ERROR,
557
+ selector: "widget",
558
+ lint: function(e, t, n, r, i) {
559
+ if (e.currentNode().widgetType !== "interactive-graph") return;
560
+ let a = e.currentNode().id;
561
+ if (!a) return;
562
+ let o = i?.widgets?.[a];
563
+ if (!o) return;
564
+ let s = [], { correct: c, graph: u, lockedFigures: d } = o.options;
565
+ for (let e of d ?? []) e.type === "line" && l.equal(e.points[0].coord, e.points[1].coord) && s.push("Locked line cannot have length 0."), e.type === "polygon" && e.points.every((t) => l.equal(t, e.points[0])) && s.push("Locked polygon cannot have all coordinates be the same."), e.type === "ellipse" && (e.radius[0] <= 0 || e.radius[1] <= 0) && s.push("Locked ellipse must have positive radius values.");
566
+ if (c?.type === "polygon" && c.numSides === "unlimited" && c.coords == null && s.push("Polygon must be closed."), u?.type === "exponential" && u.startCoords != null) {
567
+ let { coords: e, asymptote: t } = u.startCoords, n = t, r = Math.min(e[0][1], e[1][1]), i = Math.max(e[0][1], e[1][1]);
568
+ n >= r && n <= i && s.push("The exponential start asymptote must not fall between or on the curve's start points.");
569
+ }
570
+ return checkShowPointLabelsHasLabels(u, s), checkShowPointLabelsHasLabels(c, s), s.join("\n\n");
571
+ }
572
+ });
573
+ function checkShowPointLabelsHasLabels(e, t) {
574
+ if (e == null || e.type === "none" || e.type === "vector" || e.showPointLabels !== !0) return;
575
+ let n = e.pointLabels;
576
+ if (n === void 0 || n.every((e) => e == null || e === "")) {
577
+ t.push("showPointLabels is true but pointLabels has no labels. Provide a label for at least one point.");
578
+ return;
579
+ }
580
+ let r = expectedLabelCount(e);
581
+ r !== void 0 && n.length !== r && t.push(`pointLabels has ${n.length} entries but this graph type expects ${r}. Use empty strings ("") to skip labels for specific points, e.g. ["A", "", "C"].`);
582
+ }
583
+ function expectedLabelCount(e) {
584
+ switch (e.type) {
585
+ case "angle":
586
+ case "quadratic": return 3;
587
+ case "linear":
588
+ case "ray":
589
+ case "sinusoid":
590
+ case "absolute-value":
591
+ case "exponential":
592
+ case "logarithm":
593
+ case "tangent": return 2;
594
+ case "circle": return 1;
595
+ case "linear-system": return 4;
596
+ case "segment": return (e.numSegments ?? 1) * 2;
597
+ case "point": return e.numPoints === "unlimited" || e.numPoints == null ? void 0 : e.numPoints;
598
+ case "polygon": return e.numSides === "unlimited" || e.numSides == null ? void 0 : e.numSides;
599
+ default: return;
600
+ }
601
+ }
602
+ //#endregion
603
+ //#region packages/perseus-linter/src/rules/label-image-widget-error.ts
604
+ var I = h.makeRule({
605
+ name: "label-image-widget-error",
606
+ severity: h.Severity.ERROR,
607
+ selector: "widget",
608
+ lint: function(e, t, n, r, i) {
609
+ if (e.currentNode().widgetType !== "label-image") return;
610
+ let a = e.currentNode().id;
611
+ if (!a) return;
612
+ let o = i?.widgets?.[a];
613
+ if (!o) return;
614
+ let s = [], { choices: c, imageAlt: l, imageUrl: u, markers: d } = o.options;
615
+ if (c.length < 2 && s.push("label-image widget must have at least two answer choices"), u ? l || s.push("No image alt text provided") : s.push("No image url provided"), !d.length) s.push("label-image widget requires at least one marker");
616
+ else {
617
+ let e = 0, t = 0;
618
+ for (let n of d) n.answers.length || e++, n.label || t++;
619
+ e > 0 && s.push(`label-image widget has ${e} markers with no answers selected`), t > 0 && s.push(`label-image widget has ${t} markers with no ARIA label`);
620
+ }
621
+ return s.join("\n\n");
622
+ }
623
+ }), L = "ka-perseus-images.s3.amazonaws.com", R = h.makeRule({
624
+ name: "legacy-gif-url",
625
+ severity: h.Severity.GUIDELINE,
626
+ selector: "widget",
627
+ lint: function(e, t, n, r, i) {
628
+ if (e.currentNode().widgetType !== "image") return;
629
+ let a = e.currentNode().id;
630
+ if (!a) return;
631
+ let o = i && i.widgets && i.widgets[a];
632
+ if (!o) return;
633
+ let s = o.options?.backgroundImage?.url;
634
+ if (s && getHostname(s) === L && s.toLowerCase().endsWith(".gif")) return `Legacy gif URL:
635
+ gifs hosted at ${L} might not appear in the editor preview,
94
636
  but can still be viewed in the published content. Please use a
95
637
  cdn.kastatic.org/ka-perseus-images/ URL instead or confirm the
96
- image displays correctly in the published content.`}}});
97
-
98
- var LinkClickHere = Rule.makeRule({name:"link-click-here",severity:Rule.Severity.WARNING,selector:"link",pattern:/click here/i,message:`Inappropriate link text:
99
- Do not use the words "click here" in links.`});
100
-
101
- var LongParagraph = Rule.makeRule({name:"long-paragraph",severity:Rule.Severity.GUIDELINE,selector:"paragraph",pattern:/^.{501,}/,lint:function(state,content,nodes,match){return `Paragraph too long:
102
- This paragraph is ${content.length} characters long.
103
- Shorten it to 500 characters or fewer.`}});
104
-
105
- var MatcherWidgetError = Rule.makeRule({name:"matcher-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="matcher"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}if(widget.options.left.length!==widget.options.right.length){return "The two halves of the matcher have different numbers of cards."}}});
106
-
107
- var MathAdjacent = Rule.makeRule({name:"math-adjacent",severity:Rule.Severity.WARNING,selector:"blockMath+blockMath",message:`Adjacent math blocks:
108
- combine the blocks between \\begin{align} and \\end{align}`});
109
-
110
- var MathAlignExtraBreak = Rule.makeRule({name:"math-align-extra-break",severity:Rule.Severity.WARNING,selector:"blockMath",pattern:/(\\{2,})\s*\\end{align}/,message:`Extra space at end of block:
111
- Don't end an align block with backslashes`});
112
-
113
- var MathAlignLinebreaks = Rule.makeRule({name:"math-align-linebreaks",severity:Rule.Severity.WARNING,selector:"blockMath",pattern:/\\begin{align}[\s\S]*\\\\[\s\S]+\\end{align}/,lint:function(state,content,nodes,match){let text=match[0];while(text.length){const index=text.indexOf("\\\\");if(index===-1){return}text=text.substring(index+2);const nextpair=text.match(/^\s*\\\\\s*(?!\\\\)/);if(!nextpair){return "Use four backslashes between lines of an align block"}text=text.substring(nextpair[0].length);}}});
114
-
115
- var MathEmpty = Rule.makeRule({name:"math-empty",severity:Rule.Severity.WARNING,selector:"math, blockMath",pattern:/^$/,message:"Empty math: don't use $$ in your markdown."});
116
-
117
- var MathFrac = Rule.makeRule({name:"math-frac",severity:Rule.Severity.GUIDELINE,selector:"math, blockMath",pattern:/\\frac[ {]/,message:"Use \\dfrac instead of \\frac in your math expressions."});
118
-
119
- var MathNested = Rule.makeRule({name:"math-nested",severity:Rule.Severity.ERROR,selector:"math, blockMath",pattern:/\\text{[^$}]*\$[^$}]*\$[^}]*}/,message:`Nested math:
120
- Don't nest math expressions inside \\text{} blocks`});
121
-
122
- var MathStartsWithSpace = Rule.makeRule({name:"math-starts-with-space",severity:Rule.Severity.GUIDELINE,selector:"math, blockMath",pattern:/^\s*(~|\\qquad|\\quad|\\,|\\;|\\:|\\ |\\!|\\enspace|\\phantom)/,message:`Math starts with space:
123
- math should not be indented. Do not begin math expressions with
124
- LaTeX space commands like ~, \\;, \\quad, or \\phantom`});
125
-
126
- var MathTextEmpty = Rule.makeRule({name:"math-text-empty",severity:Rule.Severity.WARNING,selector:"math, blockMath",pattern:/\\text{\s*}/,message:"Empty \\text{} block in math expression"});
127
-
128
- var MathWithoutDollars = Rule.makeRule({name:"math-without-dollars",severity:Rule.Severity.GUIDELINE,pattern:/\\\w+{[^}]*}|{|}/,message:`This looks like LaTeX:
129
- did you mean to put it inside dollar signs?`});
130
-
131
- var NestedLists = Rule.makeRule({name:"nested-lists",severity:Rule.Severity.WARNING,selector:"list list",message:`Nested lists:
132
- nested lists are hard to read on mobile devices;
133
- do not use additional indentation.`});
134
-
135
- var NumericInputMissingLabel = Rule.makeRule({name:"numeric-input-missing-label",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="numeric-input"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}if(!widget.options.labelText){return `Inputs should have an aria label:
136
- While screen readers will fallback to a default label of 'Your answer', a more descriptive label would improve accessibility.`}}});
137
-
138
- var NumericInputWidgetError = Rule.makeRule({name:"numeric-input-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="numeric-input"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const issues=[];const answers=widget.options.answers;if(answers.some(answer=>answer.value==null)){issues.push("One or more answers is empty");}answers.forEach((answer,i)=>{const formatError=answer.strict&&(!answer.answerForms||answer.answerForms.length===0);if(formatError){issues.push(`Answer ${i+1} requires a format, but no format was selected`);}});const allWarningsString=issues.join("\n\n");return allWarningsString}});
139
-
140
- var PhetSimulationWidgetError = Rule.makeRule({name:"phet-simulation-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="phet-simulation"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}if(makeSafeUrl(widget.options.url,"en","https://phet.colorado.edu")===null){return "The URL is not from the PhET domain."}}});
141
-
142
- var PythonProgramWidgetError = Rule.makeRule({name:"python-program-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="python-program"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const errors=[];const height=widget.options.height;const programID=widget.options.programID;if(programID===""){errors.push("The program ID is required.");}if(!Number.isInteger(height)||height<1){errors.push("The height must be a positive integer.");}const allErrorsString=errors.join("\n\n");return allErrorsString}});
143
-
144
- var RadioWidgetError = Rule.makeRule({name:"radio-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="radio"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const choices=widget.options.choices;if(!choices.some(choice=>choice.correct)){return "No choice is marked as correct."}const correctChoices=choices.filter(choice=>choice.correct);const hasNotaCorrect=correctChoices.some(choice=>choice.isNoneOfTheAbove);if(hasNotaCorrect&&correctChoices.length>1){return "Cannot mark both None of the Above and another choice as correct."}return}});
145
-
146
- const minCards=2;function hasMixedContent(card){const contentNodes=[];traverseContent(parse(card.trim(),{}),node=>{if(node.type!=="paragraph"){contentNodes.push(node);}});return contentNodes.length>1&&contentNodes.some(node=>node.type==="image")}var SorterWidgetError = Rule.makeRule({name:"sorter-widget-error",severity:Rule.Severity.ERROR,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="sorter"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const warnings=[];const correct=widget.options.correct??[];if(correct.length<minCards){warnings.push(`Sorter requires at least ${minCards} cards.`);}if(correct.some(card=>card.trim()==="")){warnings.push("Sorter cards cannot be blank.");}if(correct.some(hasMixedContent)){warnings.push("Sorter cards cannot mix images with other content.");}return warnings.join("\n\n")}});
147
-
148
- const sorterMaxIdealCards=5;const sorterMaxHorizontalCards=5;var SorterWidgetWarning = Rule.makeRule({name:"sorter-widget-warning",severity:Rule.Severity.WARNING,selector:"widget",lint:function(state,content,nodes,match,context){if(state.currentNode().widgetType!=="sorter"){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}const warnings=[];const options=widget.options;const{layout,correct=[]}=options;if(correct.length>SORTER_MAX_CARDS){warnings.push(`Sorter cannot have more than ${SORTER_MAX_CARDS} cards.`);}if(layout==="horizontal"&&correct.length>sorterMaxHorizontalCards){warnings.push(`Sorter cannot have more than ${sorterMaxHorizontalCards} cards in horizontal layout.`);}if(correct.length>sorterMaxIdealCards){warnings.push(`Having more than ${sorterMaxIdealCards} cards in Sorter is discouraged.`);}return warnings.join("\n\n")}});
149
-
150
- var StaticWidgetInQuestionStem = Rule.makeRule({name:"static-widget-in-question-stem",severity:Rule.Severity.WARNING,selector:"widget",lint:(state,content,nodes,match,context)=>{if(context?.contentType!=="exercise"){return}if(context.stack.includes("hint")){return}const nodeId=state.currentNode().id;if(!nodeId){return}const widget=context?.widgets?.[nodeId];if(!widget){return}if(widget.static){return `Widget in question stem is static (non-interactive).`}}});
151
-
152
- const MISSING_CAPTION_MESSAGE=`Table is missing a caption:
153
- Screen reader users rely on a caption to understand what a table contains
154
- before navigating its cells. Add one by putting a line of the form:
155
- || Your caption here || directly above the table or using our Titled Table
156
- template below.`;const EMPTY_CAPTION_MESSAGE=`Table caption is empty:
157
- This table has a caption line, but there is no text between the || markers,
158
- so screen reader users hear an empty caption. Please add the appropriate
159
- title for your table.`;function getTextContent(node){if(typeof node==="string"){return node}if(Array.isArray(node)){return node.map(getTextContent).join("")}if(node&&typeof node==="object"){return getTextContent(node.content)}return ""}function getTitleText(titledTable){return getTextContent(titledTable?.title).trim()}var TableMissingCaption = Rule.makeRule({name:"table-missing-caption",severity:Rule.Severity.GUIDELINE,selector:"table",lint:function(state){const parent=state.parent();if(parent?.type!=="titledTable"){return MISSING_CAPTION_MESSAGE}if(getTitleText(parent)===""){return EMPTY_CAPTION_MESSAGE}}});
160
-
161
- var TableMissingCells = Rule.makeRule({name:"table-missing-cells",severity:Rule.Severity.WARNING,selector:"table",lint:function(state,content,nodes,match){const table=nodes[0];const headerLength=table.header.length;const rowLengths=table.cells.map(r=>r.length);for(let r=0;r<rowLengths.length;r++){if(rowLengths[r]!==headerLength){return `Table rows don't match header:
162
- The table header has ${headerLength} cells, but
163
- Row ${r+1} has ${rowLengths[r]} cells.`}}}});
164
-
165
- var UnbalancedCodeDelimiters = Rule.makeRule({name:"unbalanced-code-delimiters",severity:Rule.Severity.ERROR,pattern:/[`~]+/,message:`Unbalanced code delimiters:
166
- code blocks should begin and end with the same type and number of delimiters`});
167
-
168
- var UnescapedDollar = Rule.makeRule({name:"unescaped-dollar",severity:Rule.Severity.ERROR,selector:"unescapedDollar",message:`Unescaped dollar sign:
169
- Dollar signs must appear in pairs or be escaped as \\$`});
170
-
171
- var WidgetInTable = Rule.makeRule({name:"widget-in-table",severity:Rule.Severity.BULK_WARNING,selector:"table widget",message:`Widget in table:
172
- do not put widgets inside of tables.`});
173
-
174
- var AllRules = [AbsoluteUrl,DoubleSpacingAfterTerminal,ImageUrlEmpty,ExpressionWidget,ExtraContentSpacing,HeadingLevel1,HeadingLevelSkip,HeadingSentenceCase,HeadingTitleCase,ImageAltText,ImageMarkdown,ImageInTable,LinkClickHere,LongParagraph,MathAdjacent,MathAlignExtraBreak,MathAlignLinebreaks,MathEmpty,MathFrac,MathNested,MathStartsWithSpace,MathTextEmpty,NestedLists,StaticWidgetInQuestionStem,TableMissingCaption,TableMissingCells,UnescapedDollar,WidgetInTable,MathWithoutDollars,UnbalancedCodeDelimiters,ImageSpacesAroundUrls,ImageWidgetAltText,ImageWidgetEmptySize,LegacyGifUrl,InaccessibleWidget,RadioWidgetError,ExpressionWidgetError,FreeResponseWidgetError,MatcherWidgetError,NumericInputMissingLabel,NumericInputWidgetError,PhetSimulationWidgetError,PythonProgramWidgetError,LabelImageWidgetError,InteractiveGraphWidgetError,InteractiveGraphLockedFigureOob,SorterWidgetError,SorterWidgetWarning,ExplanationInGradedGroup];
175
-
176
- class TreeTransformer{static isNode(n){return n&&typeof n==="object"&&typeof n.type==="string"}static isTextNode(n){return TreeTransformer.isNode(n)&&n.type==="text"&&typeof n.content==="string"}traverse(f){this._traverse(this.root,new TraversalState(this.root),f);}_traverse(n,state,f){let content="";if(TreeTransformer.isNode(n)){const node=n;state._containers.push(node);state._ancestors.push(node);if(typeof node.content==="string"){content=node.content;}const keys=Object.keys(node);keys.forEach(key=>{if(key==="type"){return}const value=node[key];if(value&&typeof value==="object"){state._indexes.push(key);content+=this._traverse(value,state,f);state._indexes.pop();}});state._currentNode=state._ancestors.pop();state._containers.pop();f(node,state,content);}else if(Array.isArray(n)){const nodes=n;state._containers.push(nodes);let index=0;while(index<nodes.length){state._indexes.push(index);content+=this._traverse(nodes[index],state,f);index=state._indexes.pop()+1;}state._containers.pop();}return content}constructor(root){this.root=root;}}class TraversalState{currentNode(){return this._currentNode||this.root}parent(){return this._ancestors.top()}ancestors(){return this._ancestors.values()}nextSibling(){const siblings=this._containers.top();if(!siblings||!Array.isArray(siblings)){return null}const index=this._indexes.top();if(siblings.length>index+1){return siblings[index+1]}return null}previousSibling(){const siblings=this._containers.top();if(!siblings||!Array.isArray(siblings)){return null}const index=this._indexes.top();if(index>0){return siblings[index-1]}return null}removeNextSibling(){const siblings=this._containers.top();if(siblings&&Array.isArray(siblings)){const index=this._indexes.top();if(siblings.length>index+1){return siblings.splice(index+1,1)[0]}}return null}replace(...replacements){const parent=this._containers.top();if(!parent){throw new PerseusError("Can't replace the root of the tree",Errors.Internal)}if(Array.isArray(parent)){const index=this._indexes.top();parent.splice(index,1,...replacements);this._indexes.pop();this._indexes.push(index+replacements.length-1);}else {const property=this._indexes.top();if(replacements.length===0){delete parent[property];}else if(replacements.length===1){parent[property]=replacements[0];}else {parent[property]=replacements;}}}hasPreviousSibling(){return Array.isArray(this._containers.top())&&this._indexes.top()>0}goToPreviousSibling(){if(!this.hasPreviousSibling()){throw new PerseusError("goToPreviousSibling(): node has no previous sibling",Errors.Internal)}this._currentNode=this.previousSibling();const index=this._indexes.pop();this._indexes.push(index-1);}hasParent(){return this._ancestors.size()!==0}goToParent(){if(!this.hasParent()){throw new PerseusError("goToParent(): node has no ancestor",Errors.NotAllowed)}this._currentNode=this._ancestors.pop();while(this._containers.size()&&this._containers.top()[this._indexes.top()]!==this._currentNode){this._containers.pop();this._indexes.pop();}}clone(){const clone=new TraversalState(this.root);clone._currentNode=this._currentNode;clone._containers=this._containers.clone();clone._indexes=this._indexes.clone();clone._ancestors=this._ancestors.clone();return clone}equals(that){return this.root===that.root&&this._currentNode===that._currentNode&&this._containers.equals(that._containers)&&this._indexes.equals(that._indexes)&&this._ancestors.equals(that._ancestors)}constructor(root){this.root=root;this._currentNode=null;this._containers=new Stack;this._indexes=new Stack;this._ancestors=new Stack;}}class Stack{push(v){this.stack.push(v);}pop(){return this.stack.pop()}top(){return this.stack[this.stack.length-1]}values(){return this.stack.slice(0)}size(){return this.stack.length}toString(){return this.stack.toString()}clone(){return new Stack(this.stack)}equals(that){if(!that||!that.stack||that.stack.length!==this.stack.length){return false}for(let i=0;i<this.stack.length;i++){if(this.stack[i]!==that.stack[i]){return false}}return true}constructor(array){this.stack=array?array.slice(0):[];}}
177
-
178
- const allLintRules=AllRules.filter(r=>r.severity<Rule.Severity.BULK_WARNING);function runLinter(tree,context,highlight,rules=allLintRules){const warnings=[];const tt=new TreeTransformer(tree);tt.traverse((node,state,content)=>{if(TreeTransformer.isTextNode(node)){let next=state.nextSibling();while(TreeTransformer.isTextNode(next)){node.content+=next.content;state.removeNextSibling();next=state.nextSibling();}}});let tableWarnings=[];let insideTable=false;tt.traverse((node,state,content)=>{const nodeWarnings=[];const applicableRules=rules.filter(r=>r.applies(context));const stack=[...context.stack];stack.push(node.type);const nodeContext={...context,stack:stack.join(".")};applicableRules.forEach(rule=>{const warning=rule.check(node,state,content,nodeContext);if(warning){if(warning.start||warning.end){warning.target=content.substring(warning.start,warning.end);}warnings.push(warning);if(highlight){nodeWarnings.push(warning);}}});if(!highlight){return}if(node.type==="table"){if(tableWarnings.length){nodeWarnings.push(...tableWarnings);}insideTable=false;tableWarnings=[];}else if(!insideTable){insideTable=state.ancestors().some(n=>n.type==="table");}if(insideTable&&nodeWarnings.length>0){tableWarnings.push(...nodeWarnings);}if(nodeWarnings.length>0){nodeWarnings.sort((a,b)=>{return a.severity-b.severity});if(node.type!=="text"||nodeWarnings.length>1){state.replace({type:"lint",content:node,message:nodeWarnings.map(w=>w.message).join("\n\n"),ruleName:nodeWarnings[0].rule,blockHighlight:nodeContext.blockHighlight,insideTable:insideTable,severity:nodeWarnings[0].severity});}else {const content=node.content;const warning=nodeWarnings[0];const start=warning.start;const end=warning.end;const prefix=content.substring(0,start);const lint=content.substring(start,end);const suffix=content.substring(end);const replacements=[];if(prefix){replacements.push({type:"text",content:prefix});}replacements.push({type:"lint",content:{type:"text",content:lint},message:warning.message,ruleName:warning.rule,insideTable:insideTable,severity:warning.severity});if(suffix){replacements.push({type:"text",content:suffix});}state.replace(...replacements);}}});return warnings}
179
-
180
- function lintPerseusItem(parsedPerseusItem){const questionLint=lintPerseusRenderer(parsedPerseusItem.question,"exercise");const hintLint=parsedPerseusItem.hints.map(hint=>lintPerseusRenderer(hint,"exercise"));return {question:questionLint,hints:hintLint}}function lintPerseusArticle(parsedPerseusArticle){const articleSections=Array.isArray(parsedPerseusArticle)?parsedPerseusArticle:[parsedPerseusArticle];return articleSections.map(section=>lintPerseusRenderer(section,"article"))}function lintPerseusRenderer(parsedPerseusRenderer,contentType){const tree=parse(parsedPerseusRenderer.content);const context={content:parsedPerseusRenderer.content,widgets:parsedPerseusRenderer.widgets,stack:[],contentType};return [...runLinter(tree,context,false)]}
181
-
182
- function pushContextStack(context,name){const stack=context.stack||[];return {...context,stack:stack.concat(name)}}
638
+ image displays correctly in the published content.`;
639
+ }
640
+ }), z = h.makeRule({
641
+ name: "link-click-here",
642
+ severity: h.Severity.WARNING,
643
+ selector: "link",
644
+ pattern: /click here/i,
645
+ message: "Inappropriate link text:\nDo not use the words \"click here\" in links."
646
+ }), B = h.makeRule({
647
+ name: "long-paragraph",
648
+ severity: h.Severity.GUIDELINE,
649
+ selector: "paragraph",
650
+ pattern: /^.{501,}/,
651
+ lint: function(e, t, n, r) {
652
+ return `Paragraph too long:
653
+ This paragraph is ${t.length} characters long.
654
+ Shorten it to 500 characters or fewer.`;
655
+ }
656
+ }), V = h.makeRule({
657
+ name: "matcher-widget-error",
658
+ severity: h.Severity.ERROR,
659
+ selector: "widget",
660
+ lint: function(e, t, n, r, i) {
661
+ if (e.currentNode().widgetType !== "matcher") return;
662
+ let a = e.currentNode().id;
663
+ if (!a) return;
664
+ let o = i?.widgets?.[a];
665
+ if (o && o.options.left.length !== o.options.right.length) return "The two halves of the matcher have different numbers of cards.";
666
+ }
667
+ }), ae = h.makeRule({
668
+ name: "math-adjacent",
669
+ severity: h.Severity.WARNING,
670
+ selector: "blockMath+blockMath",
671
+ message: "Adjacent math blocks:\ncombine the blocks between \\begin{align} and \\end{align}"
672
+ }), H = h.makeRule({
673
+ name: "math-align-extra-break",
674
+ severity: h.Severity.WARNING,
675
+ selector: "blockMath",
676
+ pattern: /(\\{2,})\s*\\end{align}/,
677
+ message: "Extra space at end of block:\nDon't end an align block with backslashes"
678
+ }), U = h.makeRule({
679
+ name: "math-align-linebreaks",
680
+ severity: h.Severity.WARNING,
681
+ selector: "blockMath",
682
+ pattern: /\\begin{align}[\s\S]*\\\\[\s\S]+\\end{align}/,
683
+ lint: function(e, t, n, r) {
684
+ let i = r[0];
685
+ for (; i.length;) {
686
+ let e = i.indexOf("\\\\");
687
+ if (e === -1) return;
688
+ i = i.substring(e + 2);
689
+ let t = i.match(/^\s*\\\\\s*(?!\\\\)/);
690
+ if (!t) return "Use four backslashes between lines of an align block";
691
+ i = i.substring(t[0].length);
692
+ }
693
+ }
694
+ }), W = h.makeRule({
695
+ name: "math-empty",
696
+ severity: h.Severity.WARNING,
697
+ selector: "math, blockMath",
698
+ pattern: /^$/,
699
+ message: "Empty math: don't use $$ in your markdown."
700
+ }), G = h.makeRule({
701
+ name: "math-frac",
702
+ severity: h.Severity.GUIDELINE,
703
+ selector: "math, blockMath",
704
+ pattern: /\\frac[ {]/,
705
+ message: "Use \\dfrac instead of \\frac in your math expressions."
706
+ }), K = h.makeRule({
707
+ name: "math-nested",
708
+ severity: h.Severity.ERROR,
709
+ selector: "math, blockMath",
710
+ pattern: /\\text{[^$}]*\$[^$}]*\$[^}]*}/,
711
+ message: "Nested math:\nDon't nest math expressions inside \\text{} blocks"
712
+ }), q = h.makeRule({
713
+ name: "math-starts-with-space",
714
+ severity: h.Severity.GUIDELINE,
715
+ selector: "math, blockMath",
716
+ pattern: /^\s*(~|\\qquad|\\quad|\\,|\\;|\\:|\\ |\\!|\\enspace|\\phantom)/,
717
+ message: "Math starts with space:\nmath should not be indented. Do not begin math expressions with\nLaTeX space commands like ~, \\;, \\quad, or \\phantom"
718
+ }), J = h.makeRule({
719
+ name: "math-text-empty",
720
+ severity: h.Severity.WARNING,
721
+ selector: "math, blockMath",
722
+ pattern: /\\text{\s*}/,
723
+ message: "Empty \\text{} block in math expression"
724
+ }), oe = h.makeRule({
725
+ name: "math-without-dollars",
726
+ severity: h.Severity.GUIDELINE,
727
+ pattern: /\\\w+{[^}]*}|{|}/,
728
+ message: "This looks like LaTeX:\ndid you mean to put it inside dollar signs?"
729
+ }), se = h.makeRule({
730
+ name: "nested-lists",
731
+ severity: h.Severity.WARNING,
732
+ selector: "list list",
733
+ message: "Nested lists:\nnested lists are hard to read on mobile devices;\ndo not use additional indentation."
734
+ }), ce = h.makeRule({
735
+ name: "numeric-input-missing-label",
736
+ severity: h.Severity.WARNING,
737
+ selector: "widget",
738
+ lint: function(e, t, n, r, i) {
739
+ if (e.currentNode().widgetType !== "numeric-input") return;
740
+ let a = e.currentNode().id;
741
+ if (!a) return;
742
+ let o = i?.widgets?.[a];
743
+ if (o && !o.options.labelText) return "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.";
744
+ }
745
+ }), le = h.makeRule({
746
+ name: "numeric-input-widget-error",
747
+ severity: h.Severity.ERROR,
748
+ selector: "widget",
749
+ lint: function(e, t, n, r, i) {
750
+ if (e.currentNode().widgetType !== "numeric-input") return;
751
+ let a = e.currentNode().id;
752
+ if (!a) return;
753
+ let o = i?.widgets?.[a];
754
+ if (!o) return;
755
+ let s = [], c = o.options.answers;
756
+ return c.some((e) => e.value == null) && s.push("One or more answers is empty"), c.forEach((e, t) => {
757
+ e.strict && (!e.answerForms || e.answerForms.length === 0) && s.push(`Answer ${t + 1} requires a format, but no format was selected`);
758
+ }), s.join("\n\n");
759
+ }
760
+ }), ue = h.makeRule({
761
+ name: "phet-simulation-widget-error",
762
+ severity: h.Severity.ERROR,
763
+ selector: "widget",
764
+ lint: function(e, t, n, r, i) {
765
+ if (e.currentNode().widgetType !== "phet-simulation") return;
766
+ let o = e.currentNode().id;
767
+ if (!o) return;
768
+ let s = i?.widgets?.[o];
769
+ if (s && a(s.options.url, "en", "https://phet.colorado.edu") === null) return "The URL is not from the PhET domain.";
770
+ }
771
+ }), de = h.makeRule({
772
+ name: "python-program-widget-error",
773
+ severity: h.Severity.ERROR,
774
+ selector: "widget",
775
+ lint: function(e, t, n, r, i) {
776
+ if (e.currentNode().widgetType !== "python-program") return;
777
+ let a = e.currentNode().id;
778
+ if (!a) return;
779
+ let o = i?.widgets?.[a];
780
+ if (!o) return;
781
+ let s = [], c = o.options.height;
782
+ return o.options.programID === "" && s.push("The program ID is required."), (!Number.isInteger(c) || c < 1) && s.push("The height must be a positive integer."), s.join("\n\n");
783
+ }
784
+ }), fe = h.makeRule({
785
+ name: "radio-widget-error",
786
+ severity: h.Severity.ERROR,
787
+ selector: "widget",
788
+ lint: function(e, t, n, r, i) {
789
+ if (e.currentNode().widgetType !== "radio") return;
790
+ let a = e.currentNode().id;
791
+ if (!a) return;
792
+ let o = i?.widgets?.[a];
793
+ if (!o) return;
794
+ let s = o.options.choices;
795
+ if (!s.some((e) => e.correct)) return "No choice is marked as correct.";
796
+ let c = s.filter((e) => e.correct);
797
+ if (c.some((e) => e.isNoneOfTheAbove) && c.length > 1) return "Cannot mark both None of the Above and another choice as correct.";
798
+ }
799
+ }), Y = 2;
800
+ function hasMixedContent(e) {
801
+ let t = [];
802
+ return c(s(e.trim(), {}), (e) => {
803
+ e.type !== "paragraph" && t.push(e);
804
+ }), t.length > 1 && t.some((e) => e.type === "image");
805
+ }
806
+ var pe = h.makeRule({
807
+ name: "sorter-widget-error",
808
+ severity: h.Severity.ERROR,
809
+ selector: "widget",
810
+ lint: function(e, t, n, r, i) {
811
+ if (e.currentNode().widgetType !== "sorter") return;
812
+ let a = e.currentNode().id;
813
+ if (!a) return;
814
+ let o = i?.widgets?.[a];
815
+ if (!o) return;
816
+ let s = [], c = o.options.correct ?? [];
817
+ return c.length < Y && s.push(`Sorter requires at least ${Y} cards.`), c.some((e) => e.trim() === "") && s.push("Sorter cards cannot be blank."), c.some(hasMixedContent) && s.push("Sorter cards cannot mix images with other content."), s.join("\n\n");
818
+ }
819
+ }), me = h.makeRule({
820
+ name: "sorter-widget-warning",
821
+ severity: h.Severity.WARNING,
822
+ selector: "widget",
823
+ lint: function(e, t, n, r, a) {
824
+ if (e.currentNode().widgetType !== "sorter") return;
825
+ let o = e.currentNode().id;
826
+ if (!o) return;
827
+ let s = a?.widgets?.[o];
828
+ if (!s) return;
829
+ let c = [], { layout: l, correct: u = [] } = s.options;
830
+ return u.length > i && c.push(`Sorter cannot have more than ${i} cards.`), l === "horizontal" && u.length > 5 && c.push("Sorter cannot have more than 5 cards in horizontal layout."), u.length > 5 && c.push("Having more than 5 cards in Sorter is discouraged."), c.join("\n\n");
831
+ }
832
+ }), he = h.makeRule({
833
+ name: "static-widget-in-question-stem",
834
+ severity: h.Severity.WARNING,
835
+ selector: "widget",
836
+ lint: (e, t, n, r, i) => {
837
+ if (i?.contentType !== "exercise" || i.stack.includes("hint")) return;
838
+ let a = e.currentNode().id;
839
+ if (!a) return;
840
+ let o = i?.widgets?.[a];
841
+ if (o && o.static) return "Widget in question stem is static (non-interactive).";
842
+ }
843
+ }), ge = "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.", X = "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.";
844
+ function getTextContent(e) {
845
+ return typeof e == "string" ? e : Array.isArray(e) ? e.map(getTextContent).join("") : e && typeof e == "object" ? getTextContent(e.content) : "";
846
+ }
847
+ function getTitleText(e) {
848
+ return getTextContent(e?.title).trim();
849
+ }
850
+ var _e = h.makeRule({
851
+ name: "table-missing-caption",
852
+ severity: h.Severity.GUIDELINE,
853
+ selector: "table",
854
+ lint: function(e) {
855
+ let t = e.parent();
856
+ if (t?.type !== "titledTable") return ge;
857
+ if (getTitleText(t) === "") return X;
858
+ }
859
+ }), ve = h.makeRule({
860
+ name: "table-missing-cells",
861
+ severity: h.Severity.WARNING,
862
+ selector: "table",
863
+ lint: function(e, t, n, r) {
864
+ let i = n[0], a = i.header.length, o = i.cells.map((e) => e.length);
865
+ for (let e = 0; e < o.length; e++) if (o[e] !== a) return `Table rows don't match header:
866
+ The table header has ${a} cells, but
867
+ Row ${e + 1} has ${o[e]} cells.`;
868
+ }
869
+ }), ye = h.makeRule({
870
+ name: "unbalanced-code-delimiters",
871
+ severity: h.Severity.ERROR,
872
+ pattern: /[`~]+/,
873
+ message: "Unbalanced code delimiters:\ncode blocks should begin and end with the same type and number of delimiters"
874
+ }), Z = [
875
+ g,
876
+ A,
877
+ ie,
878
+ v,
879
+ S,
880
+ C,
881
+ w,
882
+ E,
883
+ D,
884
+ O,
885
+ z,
886
+ B,
887
+ ae,
888
+ H,
889
+ U,
890
+ W,
891
+ G,
892
+ K,
893
+ q,
894
+ J,
895
+ se,
896
+ he,
897
+ _e,
898
+ ve,
899
+ h.makeRule({
900
+ name: "unescaped-dollar",
901
+ severity: h.Severity.ERROR,
902
+ selector: "unescapedDollar",
903
+ message: "Unescaped dollar sign:\nDollar signs must appear in pairs or be escaped as \\$"
904
+ }),
905
+ oe,
906
+ ye,
907
+ k,
908
+ j,
909
+ M,
910
+ R,
911
+ N,
912
+ fe,
913
+ y,
914
+ x,
915
+ V,
916
+ ce,
917
+ le,
918
+ ue,
919
+ de,
920
+ I,
921
+ F,
922
+ P,
923
+ pe,
924
+ me,
925
+ te,
926
+ ne
927
+ ], Q = class TreeTransformer {
928
+ constructor(e) {
929
+ this.root = e;
930
+ }
931
+ static isNode(e) {
932
+ return e && typeof e == "object" && typeof e.type == "string";
933
+ }
934
+ static isTextNode(e) {
935
+ return TreeTransformer.isNode(e) && e.type === "text" && typeof e.content == "string";
936
+ }
937
+ traverse(e) {
938
+ this._traverse(this.root, new be(this.root), e);
939
+ }
940
+ _traverse(e, t, n) {
941
+ let r = "";
942
+ if (TreeTransformer.isNode(e)) {
943
+ let i = e;
944
+ t._containers.push(i), t._ancestors.push(i), typeof i.content == "string" && (r = i.content), Object.keys(i).forEach((e) => {
945
+ if (e === "type") return;
946
+ let a = i[e];
947
+ a && typeof a == "object" && (t._indexes.push(e), r += this._traverse(a, t, n), t._indexes.pop());
948
+ }), t._currentNode = t._ancestors.pop(), t._containers.pop(), n(i, t, r);
949
+ } else if (Array.isArray(e)) {
950
+ let i = e;
951
+ t._containers.push(i);
952
+ let a = 0;
953
+ for (; a < i.length;) t._indexes.push(a), r += this._traverse(i[a], t, n), a = t._indexes.pop() + 1;
954
+ t._containers.pop();
955
+ }
956
+ return r;
957
+ }
958
+ }, be = class TraversalState {
959
+ constructor(e) {
960
+ this.root = e, this._currentNode = null, this._containers = new $(), this._indexes = new $(), this._ancestors = new $();
961
+ }
962
+ currentNode() {
963
+ return this._currentNode || this.root;
964
+ }
965
+ parent() {
966
+ return this._ancestors.top();
967
+ }
968
+ ancestors() {
969
+ return this._ancestors.values();
970
+ }
971
+ nextSibling() {
972
+ let e = this._containers.top();
973
+ if (!e || !Array.isArray(e)) return null;
974
+ let t = this._indexes.top();
975
+ return e.length > t + 1 ? e[t + 1] : null;
976
+ }
977
+ previousSibling() {
978
+ let e = this._containers.top();
979
+ if (!e || !Array.isArray(e)) return null;
980
+ let t = this._indexes.top();
981
+ return t > 0 ? e[t - 1] : null;
982
+ }
983
+ removeNextSibling() {
984
+ let e = this._containers.top();
985
+ if (e && Array.isArray(e)) {
986
+ let t = this._indexes.top();
987
+ if (e.length > t + 1) return e.splice(t + 1, 1)[0];
988
+ }
989
+ return null;
990
+ }
991
+ replace(...e) {
992
+ let t = this._containers.top();
993
+ if (!t) throw new r("Can't replace the root of the tree", n.Internal);
994
+ if (Array.isArray(t)) {
995
+ let n = this._indexes.top();
996
+ t.splice(n, 1, ...e), this._indexes.pop(), this._indexes.push(n + e.length - 1);
997
+ } else {
998
+ let n = this._indexes.top();
999
+ e.length === 0 ? delete t[n] : t[n] = e.length === 1 ? e[0] : e;
1000
+ }
1001
+ }
1002
+ hasPreviousSibling() {
1003
+ return Array.isArray(this._containers.top()) && this._indexes.top() > 0;
1004
+ }
1005
+ goToPreviousSibling() {
1006
+ if (!this.hasPreviousSibling()) throw new r("goToPreviousSibling(): node has no previous sibling", n.Internal);
1007
+ this._currentNode = this.previousSibling();
1008
+ let e = this._indexes.pop();
1009
+ this._indexes.push(e - 1);
1010
+ }
1011
+ hasParent() {
1012
+ return this._ancestors.size() !== 0;
1013
+ }
1014
+ goToParent() {
1015
+ if (!this.hasParent()) throw new r("goToParent(): node has no ancestor", n.NotAllowed);
1016
+ for (this._currentNode = this._ancestors.pop(); this._containers.size() && this._containers.top()[this._indexes.top()] !== this._currentNode;) this._containers.pop(), this._indexes.pop();
1017
+ }
1018
+ clone() {
1019
+ let e = new TraversalState(this.root);
1020
+ return e._currentNode = this._currentNode, e._containers = this._containers.clone(), e._indexes = this._indexes.clone(), e._ancestors = this._ancestors.clone(), e;
1021
+ }
1022
+ equals(e) {
1023
+ return this.root === e.root && this._currentNode === e._currentNode && this._containers.equals(e._containers) && this._indexes.equals(e._indexes) && this._ancestors.equals(e._ancestors);
1024
+ }
1025
+ }, $ = class Stack {
1026
+ constructor(e) {
1027
+ this.stack = e ? e.slice(0) : [];
1028
+ }
1029
+ push(e) {
1030
+ this.stack.push(e);
1031
+ }
1032
+ pop() {
1033
+ return this.stack.pop();
1034
+ }
1035
+ top() {
1036
+ return this.stack[this.stack.length - 1];
1037
+ }
1038
+ values() {
1039
+ return this.stack.slice(0);
1040
+ }
1041
+ size() {
1042
+ return this.stack.length;
1043
+ }
1044
+ toString() {
1045
+ return this.stack.toString();
1046
+ }
1047
+ clone() {
1048
+ return new Stack(this.stack);
1049
+ }
1050
+ equals(e) {
1051
+ if (!e || !e.stack || e.stack.length !== this.stack.length) return !1;
1052
+ for (let t = 0; t < this.stack.length; t++) if (this.stack[t] !== e.stack[t]) return !1;
1053
+ return !0;
1054
+ }
1055
+ };
1056
+ //#endregion
1057
+ //#region packages/perseus-linter/src/run-linter.ts
1058
+ function runLinter(e, t, n, r = Z) {
1059
+ let i = [], a = new Q(e);
1060
+ a.traverse((e, t, n) => {
1061
+ if (Q.isTextNode(e)) {
1062
+ let n = t.nextSibling();
1063
+ for (; Q.isTextNode(n);) e.content += n.content, t.removeNextSibling(), n = t.nextSibling();
1064
+ }
1065
+ });
1066
+ let o = [], s = !1;
1067
+ return a.traverse((e, a, c) => {
1068
+ let l = [], u = r.filter((e) => e.applies(t)), d = [...t.stack];
1069
+ d.push(e.type);
1070
+ let f = {
1071
+ ...t,
1072
+ stack: d.join(".")
1073
+ };
1074
+ if (u.forEach((t) => {
1075
+ let r = t.check(e, a, c, f);
1076
+ r && ((r.start || r.end) && (r.target = c.substring(r.start, r.end)), i.push(r), n && l.push(r));
1077
+ }), n && (e.type === "table" ? (o.length && l.push(...o), s = !1, o = []) : s || (s = a.ancestors().some((e) => e.type === "table")), s && l.length > 0 && o.push(...l), l.length > 0)) {
1078
+ if (l.sort((e, t) => e.severity - t.severity), e.type !== "text" || l.length > 1) a.replace({
1079
+ type: "lint",
1080
+ content: e,
1081
+ message: l.map((e) => e.message).join("\n\n"),
1082
+ ruleName: l[0].rule,
1083
+ blockHighlight: f.blockHighlight,
1084
+ insideTable: s,
1085
+ severity: l[0].severity
1086
+ });
1087
+ else {
1088
+ let t = e.content, n = l[0], r = n.start, i = n.end, o = t.substring(0, r), c = t.substring(r, i), u = t.substring(i), d = [];
1089
+ o && d.push({
1090
+ type: "text",
1091
+ content: o
1092
+ }), d.push({
1093
+ type: "lint",
1094
+ content: {
1095
+ type: "text",
1096
+ content: c
1097
+ },
1098
+ message: n.message,
1099
+ ruleName: n.rule,
1100
+ insideTable: s,
1101
+ severity: n.severity
1102
+ }), u && d.push({
1103
+ type: "text",
1104
+ content: u
1105
+ }), a.replace(...d);
1106
+ }
1107
+ }
1108
+ }), i;
1109
+ }
1110
+ //#endregion
1111
+ //#region packages/perseus-linter/src/lint-content.ts
1112
+ function lintPerseusItem(e) {
1113
+ return {
1114
+ question: lintPerseusRenderer(e.question, "exercise"),
1115
+ hints: e.hints.map((e) => lintPerseusRenderer(e, "exercise"))
1116
+ };
1117
+ }
1118
+ function lintPerseusArticle(e) {
1119
+ return (Array.isArray(e) ? e : [e]).map((e) => lintPerseusRenderer(e, "article"));
1120
+ }
1121
+ function lintPerseusRenderer(e, t) {
1122
+ return [...runLinter(s(e.content), {
1123
+ content: e.content,
1124
+ widgets: e.widgets,
1125
+ stack: [],
1126
+ contentType: t
1127
+ }, !1)];
1128
+ }
1129
+ //#endregion
1130
+ //#region packages/perseus-linter/src/index.ts
1131
+ function pushContextStack(e, t) {
1132
+ let n = e.stack || [];
1133
+ return {
1134
+ ...e,
1135
+ stack: n.concat(t)
1136
+ };
1137
+ }
1138
+ //#endregion
1139
+ export { h as Rule, d as libVersion, lintPerseusArticle, lintPerseusItem, lintPerseusRenderer, f as linterContextDefault, pushContextStack, Z as rules, runLinter };
183
1140
 
184
- export { Rule, libVersion, lintPerseusArticle, lintPerseusItem, lintPerseusRenderer, linterContextDefault, pushContextStack, allLintRules as rules, runLinter };
185
- //# sourceMappingURL=index.js.map
1141
+ //# sourceMappingURL=index.js.map