@bascik/language-server 0.1.0-rc.4 → 0.1.0-rc.6
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/README.md +72 -30
- package/dist/analyzer.d.ts +70 -1
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/analyzer.js +657 -77
- package/dist/analyzer.js.map +1 -1
- package/dist/api-rules.d.ts +7 -0
- package/dist/api-rules.d.ts.map +1 -1
- package/dist/api-rules.js +235 -16
- package/dist/api-rules.js.map +1 -1
- package/dist/bin.js +4 -1
- package/dist/bin.js.map +1 -1
- package/dist/check.d.ts +14 -1
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +116 -10
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +27 -8
- package/dist/cli.js.map +1 -1
- package/dist/compatibility-rules.json +21 -3
- package/dist/component-metadata.d.ts.map +1 -1
- package/dist/component-metadata.js +3 -1
- package/dist/component-metadata.js.map +1 -1
- package/dist/component-usages.d.ts +47 -0
- package/dist/component-usages.d.ts.map +1 -0
- package/dist/component-usages.js +495 -0
- package/dist/component-usages.js.map +1 -0
- package/dist/config-reader.d.ts +41 -0
- package/dist/config-reader.d.ts.map +1 -0
- package/dist/config-reader.js +461 -0
- package/dist/config-reader.js.map +1 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +25 -30
- package/dist/config.js.map +1 -1
- package/dist/directive-rules.d.ts +3 -3
- package/dist/directive-rules.d.ts.map +1 -1
- package/dist/directive-rules.js +6 -6
- package/dist/directive-rules.js.map +1 -1
- package/dist/hand-written-escaper.d.ts +35 -0
- package/dist/hand-written-escaper.d.ts.map +1 -0
- package/dist/hand-written-escaper.js +739 -0
- package/dist/hand-written-escaper.js.map +1 -0
- package/dist/module-specifiers.d.ts +25 -0
- package/dist/module-specifiers.d.ts.map +1 -1
- package/dist/module-specifiers.js +234 -165
- package/dist/module-specifiers.js.map +1 -1
- package/dist/name-groups.d.ts +36 -0
- package/dist/name-groups.d.ts.map +1 -0
- package/dist/name-groups.js +198 -0
- package/dist/name-groups.js.map +1 -0
- package/dist/plain-holes.d.ts +116 -0
- package/dist/plain-holes.d.ts.map +1 -0
- package/dist/plain-holes.js +1970 -0
- package/dist/plain-holes.js.map +1 -0
- package/dist/project.d.ts +58 -1
- package/dist/project.d.ts.map +1 -1
- package/dist/project.js +146 -8
- package/dist/project.js.map +1 -1
- package/dist/references.d.ts +47 -0
- package/dist/references.d.ts.map +1 -0
- package/dist/references.js +241 -0
- package/dist/references.js.map +1 -0
- package/dist/script-modules.d.ts +60 -0
- package/dist/script-modules.d.ts.map +1 -0
- package/dist/script-modules.js +382 -0
- package/dist/script-modules.js.map +1 -0
- package/dist/server-script-rules.d.ts +94 -1
- package/dist/server-script-rules.d.ts.map +1 -1
- package/dist/server-script-rules.js +2572 -230
- package/dist/server-script-rules.js.map +1 -1
- package/dist/server-script-templates.d.ts +250 -0
- package/dist/server-script-templates.d.ts.map +1 -0
- package/dist/server-script-templates.js +1685 -0
- package/dist/server-script-templates.js.map +1 -0
- package/dist/server.d.ts +191 -3
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +822 -50
- package/dist/server.js.map +1 -1
- package/dist/start.d.ts +10 -1
- package/dist/start.d.ts.map +1 -1
- package/dist/start.js +14 -2
- package/dist/start.js.map +1 -1
- package/dist/string-typed-flow.d.ts +26 -0
- package/dist/string-typed-flow.d.ts.map +1 -0
- package/dist/string-typed-flow.js +496 -0
- package/dist/string-typed-flow.js.map +1 -0
- package/dist/typescript-blocks.d.ts +205 -0
- package/dist/typescript-blocks.d.ts.map +1 -0
- package/dist/typescript-blocks.js +464 -0
- package/dist/typescript-blocks.js.map +1 -0
- package/dist/typescript-editor-mode.d.ts +28 -0
- package/dist/typescript-editor-mode.d.ts.map +1 -0
- package/dist/typescript-editor-mode.js +161 -0
- package/dist/typescript-editor-mode.js.map +1 -0
- package/dist/typescript-engine.d.ts +115 -0
- package/dist/typescript-engine.d.ts.map +1 -0
- package/dist/typescript-engine.js +286 -0
- package/dist/typescript-engine.js.map +1 -0
- package/dist/typescript-features.d.ts +136 -0
- package/dist/typescript-features.d.ts.map +1 -0
- package/dist/typescript-features.js +374 -0
- package/dist/typescript-features.js.map +1 -0
- package/dist/typescript-loader.d.ts +55 -0
- package/dist/typescript-loader.d.ts.map +1 -0
- package/dist/typescript-loader.js +202 -0
- package/dist/typescript-loader.js.map +1 -0
- package/dist/typescript-lsp.d.ts +8 -0
- package/dist/typescript-lsp.d.ts.map +1 -0
- package/dist/typescript-lsp.js +115 -0
- package/dist/typescript-lsp.js.map +1 -0
- package/dist/typescript-service.d.ts +350 -0
- package/dist/typescript-service.d.ts.map +1 -0
- package/dist/typescript-service.js +1465 -0
- package/dist/typescript-service.js.map +1 -0
- package/dist/typescript-worker.d.ts +11 -0
- package/dist/typescript-worker.d.ts.map +1 -0
- package/dist/typescript-worker.js +107 -0
- package/dist/typescript-worker.js.map +1 -0
- package/package.json +20 -7
|
@@ -1,130 +1,104 @@
|
|
|
1
|
-
import { findModuleSpecifiers } from "./module-specifiers.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
else if (source[i] === "'" || source[i] === '"') {
|
|
82
|
-
const quote = source[i];
|
|
83
|
-
i++;
|
|
84
|
-
while (i < source.length) {
|
|
85
|
-
if (source[i] === "\\")
|
|
86
|
-
i += 2;
|
|
87
|
-
else if (source[i] === quote) {
|
|
88
|
-
i++;
|
|
89
|
-
break;
|
|
90
|
-
}
|
|
91
|
-
else
|
|
92
|
-
i++;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
else if (source[i] === "/" && source[i + 1] === "/") {
|
|
96
|
-
i += 2;
|
|
97
|
-
while (i < source.length && source[i] !== "\n")
|
|
98
|
-
i++;
|
|
99
|
-
}
|
|
100
|
-
else if (source[i] === "/" && source[i + 1] === "*") {
|
|
101
|
-
i += 2;
|
|
102
|
-
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/"))
|
|
103
|
-
i++;
|
|
104
|
-
i = Math.min(i + 2, source.length);
|
|
105
|
-
}
|
|
106
|
-
else {
|
|
107
|
-
i++;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
return placeholders;
|
|
1
|
+
import { findModuleSpecifiers, scanJavaScript, } from "./module-specifiers.js";
|
|
2
|
+
import { holdsMarkupCharacter, plainHoleChecker } from "./plain-holes.js";
|
|
3
|
+
import { stringTypedFlow } from "./string-typed-flow.js";
|
|
4
|
+
import { HAND_WRITTEN_ESCAPER_RULE, findHandWrittenEscapers, } from "./hand-written-escaper.js";
|
|
5
|
+
import { maskCommentsAndStrings } from "./api-rules.js";
|
|
6
|
+
import { escapeRegExp } from "./analyzer.js";
|
|
7
|
+
import { HTML_MODULE, boundTo, callOf, findBindings, findBindingRanges, findHtmlImports, findTemplateLiterals, htmlExportOf, htmlTagNames, isExempt, isMessageArgument, isPatternArgument, isEscapedJson, newNameMemo, looksLikeMarkup, parseImportSpecifier, markupInCode, markdownFences, scanTemplateHtml, REGEX_AFTER_KEYWORD, skipRegexLiteral, } from "./server-script-templates.js";
|
|
8
|
+
export const UNESCAPED_MARKUP_RULE = "server-script-unescaped-markup";
|
|
9
|
+
/** A server or stream script whose default export returns a Response. */
|
|
10
|
+
export const RETURNS_RESPONSE_RULE = "server-script-returns-response";
|
|
11
|
+
/** Tags that join their values into a string as they are, like no tag at all. */
|
|
12
|
+
const PLAIN_STRING_TAGS = new Set([
|
|
13
|
+
"String.raw",
|
|
14
|
+
"dedent",
|
|
15
|
+
"outdent",
|
|
16
|
+
"stripIndent",
|
|
17
|
+
"stripIndents",
|
|
18
|
+
"oneLine",
|
|
19
|
+
"oneLineTrim",
|
|
20
|
+
"codeBlock",
|
|
21
|
+
]);
|
|
22
|
+
const HTML_THROWS = {
|
|
23
|
+
"server-script-sink-event-handler": "html`...` throws here: an event handler's value is JavaScript. Put the value in a data-* attribute and read it from a component script.",
|
|
24
|
+
"server-script-sink-inline-script": 'html`...` throws here: a <script> body is JavaScript, which escaping cannot make safe. Put the value in a data-* attribute, or in <script type="application/json">${json(value)}</script>.',
|
|
25
|
+
"server-script-sink-style": "html`...` throws here: CSS is not made safe by escaping. Choose between fixed classes in code, or put the value in a data-* attribute.",
|
|
26
|
+
"server-script-sink-unquoted-attribute": 'html`...` throws here: an unquoted attribute value ends at a space. Quote it: attr="${...}".',
|
|
27
|
+
};
|
|
28
|
+
const LONGEST_KEYWORD = 10; // "instanceof"
|
|
29
|
+
// Characters after which an operand, so a regex, follows.
|
|
30
|
+
const OPERAND_FOLLOWS = new Set("(,=:[!&|?{};+-*%<>~^");
|
|
31
|
+
// The same set String.prototype.trimEnd removes.
|
|
32
|
+
const isSpace = (char) => /\s/.test(char);
|
|
33
|
+
const isWordChar = (char) => /[\w$]/.test(char);
|
|
34
|
+
// Index just past the last non-whitespace character before `end`.
|
|
35
|
+
function skipSpaceBack(chars, end) {
|
|
36
|
+
while (end > 0 && isSpace(chars[end - 1]))
|
|
37
|
+
end--;
|
|
38
|
+
return end;
|
|
39
|
+
}
|
|
40
|
+
const isSpreadBefore = (chars, end) => end >= 3 &&
|
|
41
|
+
chars[end - 1] === "." &&
|
|
42
|
+
chars[end - 2] === "." &&
|
|
43
|
+
chars[end - 3] === ".";
|
|
44
|
+
// A `/` starts a regex literal when nothing before it can end an expression.
|
|
45
|
+
// Without this, a quote inside /"/g would open a string that swallows the
|
|
46
|
+
// `export default` after it.
|
|
47
|
+
//
|
|
48
|
+
// It reads only the text just before the `/`, walking back over whitespace
|
|
49
|
+
// and at most one keyword. End-anchored patterns over everything scanned so
|
|
50
|
+
// far cost a pass over the whole prefix for every `/` (as does indexing a
|
|
51
|
+
// string built with +=, which V8 flattens on each read), which made a large
|
|
52
|
+
// minified script quadratic. `cleaned` is a character array, and each walk
|
|
53
|
+
// back stops at the previous token, so the whole scan stays linear.
|
|
54
|
+
function regexCanStart(cleaned) {
|
|
55
|
+
const end = skipSpaceBack(cleaned, cleaned.length);
|
|
56
|
+
if (end === 0)
|
|
57
|
+
return true;
|
|
58
|
+
// `...` is a spread, which an operand follows; a single `.` (or `?.`) is a
|
|
59
|
+
// property access, handled with the keyword check below.
|
|
60
|
+
if (OPERAND_FOLLOWS.has(cleaned[end - 1]))
|
|
61
|
+
return true;
|
|
62
|
+
if (isSpreadBefore(cleaned, end))
|
|
63
|
+
return true;
|
|
64
|
+
let start = end;
|
|
65
|
+
while (start > 0 &&
|
|
66
|
+
end - start <= LONGEST_KEYWORD &&
|
|
67
|
+
isWordChar(cleaned[start - 1]))
|
|
68
|
+
start--;
|
|
69
|
+
// A longer word, or one that continues past the bound, is no keyword.
|
|
70
|
+
if (start > 0 && isWordChar(cleaned[start - 1]))
|
|
71
|
+
return false;
|
|
72
|
+
if (!REGEX_AFTER_KEYWORD.has(cleaned.slice(start, end).join("")))
|
|
73
|
+
return false;
|
|
74
|
+
// `values.of` or `values?.in` is a property name that ends an expression,
|
|
75
|
+
// so a `/` after it is division. A spread before a keyword (`...await`) is
|
|
76
|
+
// not a property access.
|
|
77
|
+
const beforeKeyword = skipSpaceBack(cleaned, start);
|
|
78
|
+
return (beforeKeyword === 0 ||
|
|
79
|
+
cleaned[beforeKeyword - 1] !== "." ||
|
|
80
|
+
isSpreadBefore(cleaned, beforeKeyword));
|
|
111
81
|
}
|
|
112
82
|
function hasDefaultExport(source) {
|
|
113
|
-
|
|
83
|
+
const chars = [];
|
|
114
84
|
let i = 0;
|
|
115
85
|
while (i < source.length) {
|
|
116
86
|
if (source[i] === "/" && source[i + 1] === "/") {
|
|
117
87
|
i += 2;
|
|
118
88
|
while (i < source.length && source[i] !== "\n")
|
|
119
89
|
i++;
|
|
120
|
-
|
|
90
|
+
chars.push(" ");
|
|
121
91
|
}
|
|
122
92
|
else if (source[i] === "/" && source[i + 1] === "*") {
|
|
123
93
|
i += 2;
|
|
124
94
|
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/"))
|
|
125
95
|
i++;
|
|
126
96
|
i = Math.min(i + 2, source.length);
|
|
127
|
-
|
|
97
|
+
chars.push(" ");
|
|
98
|
+
}
|
|
99
|
+
else if (source[i] === "/" && regexCanStart(chars)) {
|
|
100
|
+
i = skipRegexLiteral(source, i);
|
|
101
|
+
chars.push(" ", "0", " ");
|
|
128
102
|
}
|
|
129
103
|
else if (source[i] === '"' || source[i] === "'") {
|
|
130
104
|
const q = source[i];
|
|
@@ -139,7 +113,9 @@ function hasDefaultExport(source) {
|
|
|
139
113
|
else
|
|
140
114
|
i++;
|
|
141
115
|
}
|
|
142
|
-
|
|
116
|
+
// A string is a value: a `/` after it is division, so keep a value token
|
|
117
|
+
// in its place rather than leaving the preceding `=` or `(` exposed.
|
|
118
|
+
chars.push(" ", "0", " ");
|
|
143
119
|
}
|
|
144
120
|
else if (source[i] === "`") {
|
|
145
121
|
i++;
|
|
@@ -162,13 +138,15 @@ function hasDefaultExport(source) {
|
|
|
162
138
|
else
|
|
163
139
|
i++;
|
|
164
140
|
}
|
|
165
|
-
|
|
141
|
+
// Same as a string: a template literal is a value.
|
|
142
|
+
chars.push(" ", "0", " ");
|
|
166
143
|
}
|
|
167
144
|
else {
|
|
168
|
-
|
|
145
|
+
chars.push(source[i]);
|
|
169
146
|
i++;
|
|
170
147
|
}
|
|
171
148
|
}
|
|
149
|
+
const cleaned = chars.join("");
|
|
172
150
|
if (/\bexport\s+default\b/.test(cleaned))
|
|
173
151
|
return true;
|
|
174
152
|
if (/\bexport\s*\*\s*as\s+default\b/.test(cleaned))
|
|
@@ -190,7 +168,9 @@ function hasDefaultExport(source) {
|
|
|
190
168
|
export function analyzeServerScriptSource(body, opts) {
|
|
191
169
|
const diagnostics = [];
|
|
192
170
|
// Rule 2: server-script-missing-default-export
|
|
193
|
-
if (body.trim().length > 0 &&
|
|
171
|
+
if (body.trim().length > 0 &&
|
|
172
|
+
!opts.hasSrcAttribute &&
|
|
173
|
+
opts.directive !== "module") {
|
|
194
174
|
if (!hasDefaultExport(body)) {
|
|
195
175
|
const match = /\S+/.exec(body);
|
|
196
176
|
const start = match ? match.index : 0;
|
|
@@ -216,148 +196,2510 @@ export function analyzeServerScriptSource(body, opts) {
|
|
|
216
196
|
});
|
|
217
197
|
}
|
|
218
198
|
}
|
|
219
|
-
//
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
199
|
+
// Request-time scripts get every rule. Build-time code (build and routes
|
|
200
|
+
// scripts, and the modules scripts import) gets the markup rules too:
|
|
201
|
+
// their output is a page, and a title with & or < breaks it whoever wrote
|
|
202
|
+
// the value. See the sink notes in the template loop.
|
|
203
|
+
const requestTime = opts.directive === "server" ||
|
|
204
|
+
opts.directive === "stream" ||
|
|
205
|
+
(opts.directive === "module" && opts.requestTime === true);
|
|
206
|
+
// server-script-returns-response: the API-route habit, refused at request
|
|
207
|
+
// time. Only a server or stream script's own body: a module is read for its
|
|
208
|
+
// markup, and a build script may return what it likes.
|
|
209
|
+
if (!opts.hasSrcAttribute &&
|
|
210
|
+
(opts.directive === "server" || opts.directive === "stream"))
|
|
211
|
+
for (const { start, end } of findReturnedResponses(body))
|
|
212
|
+
diagnostics.push({
|
|
213
|
+
code: RETURNS_RESPONSE_RULE,
|
|
214
|
+
message: `This data-bascik-${opts.directive} script returns a Response, which Bascik refuses when the page is requested: the script's return value is spliced into the page as markup. Return a string or an html\`...\` value from @bascik/bascik/html. A Response belongs in an API route (src/api/).`,
|
|
215
|
+
severity: "warning",
|
|
216
|
+
start,
|
|
217
|
+
end,
|
|
218
|
+
});
|
|
223
219
|
// server-script-bascik-import
|
|
224
220
|
// An ESM import whose specifier is exactly @bascik/bascik or starts with @bascik/bascik/
|
|
225
|
-
|
|
221
|
+
// Build scripts may import build tooling, so this is for server and stream only.
|
|
222
|
+
const moduleSpecifiers = opts.directive === "server" || opts.directive === "stream"
|
|
223
|
+
? findModuleSpecifiers(body)
|
|
224
|
+
: [];
|
|
226
225
|
for (const { start, end, value } of moduleSpecifiers) {
|
|
226
|
+
if (value === HTML_MODULE)
|
|
227
|
+
continue;
|
|
227
228
|
if (value === "@bascik/bascik" || value.startsWith("@bascik/bascik/")) {
|
|
228
229
|
diagnostics.push({
|
|
229
230
|
code: "server-script-bascik-import",
|
|
230
|
-
message: "
|
|
231
|
+
message: "Only @bascik/bascik/html is meant for server and stream scripts. The rest of @bascik/bascik is build tooling.",
|
|
231
232
|
severity: "error",
|
|
232
233
|
start,
|
|
233
234
|
end,
|
|
234
235
|
});
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
|
-
//
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
238
|
+
// Escapers a comment says are for XML: trusted in this script's holes.
|
|
239
|
+
const xmlEscapers = [];
|
|
240
|
+
if (!opts.hasSrcAttribute)
|
|
241
|
+
for (const escaper of findHandWrittenEscapers(body, xmlEscapers)) {
|
|
242
|
+
if (escaper.xmlName) {
|
|
243
|
+
diagnostics.push({
|
|
244
|
+
code: HAND_WRITTEN_ESCAPER_RULE,
|
|
245
|
+
message: `${escaper.name}() looks like an XML escaper: it turns & and < into entities. If it escapes XML on purpose (a feed, a sitemap, an SVG file), say so in a comment above it. If its output goes into an HTML page, use html\`...\` or esc() from @bascik/bascik/html.`,
|
|
246
|
+
severity: "warning",
|
|
247
|
+
start: escaper.start,
|
|
248
|
+
end: escaper.end,
|
|
249
|
+
...(escaper.delegate ? { escaper: escaper.delegate } : {}),
|
|
250
|
+
});
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const subject = escaper.kind === "map"
|
|
254
|
+
? `${escaper.name} maps & and < to HTML entities, the core of a hand-written HTML escaper.`
|
|
255
|
+
: escaper.defaultExport
|
|
256
|
+
? "The default export is a hand-written HTML escaper: it turns & and < into entities."
|
|
257
|
+
: `${escaper.name}() is a hand-written HTML escaper: it turns & and < into entities.`;
|
|
251
258
|
diagnostics.push({
|
|
252
|
-
code:
|
|
253
|
-
message:
|
|
259
|
+
code: HAND_WRITTEN_ESCAPER_RULE,
|
|
260
|
+
message: `${subject} Build markup with html\`...\` from @bascik/bascik/html, which escapes each value for where it lands, or call esc() from the same module for a plain string. If it escapes XML on purpose, say so in a comment above it.`,
|
|
254
261
|
severity: "warning",
|
|
255
|
-
start:
|
|
256
|
-
end:
|
|
262
|
+
start: escaper.start,
|
|
263
|
+
end: escaper.end,
|
|
264
|
+
...(escaper.delegate ? { escaper: escaper.delegate } : {}),
|
|
257
265
|
});
|
|
258
|
-
continue;
|
|
259
266
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
267
|
+
// Part C: sink rules and server-script-unescaped-markup, per template hole.
|
|
268
|
+
const imports = findHtmlImports(body);
|
|
269
|
+
const htmlTags = htmlTagNames(imports);
|
|
270
|
+
const literals = findTemplateLiterals(body);
|
|
271
|
+
// Every Part C diagnostic is on a template's hole. In build-time code
|
|
272
|
+
// one needs markup, a `<` in the template's text, or an html tag, so a
|
|
273
|
+
// script without either is done here, before the costlier passes.
|
|
274
|
+
if (!requestTime &&
|
|
275
|
+
!literals.some((l) => (l.tag !== null && htmlTags.includes(l.tag)) ||
|
|
276
|
+
l.parts.some((part) => part.includes("<"))))
|
|
277
|
+
return diagnostics;
|
|
278
|
+
// Read once: the exemption checks and markupProducers both use them.
|
|
279
|
+
const bindingRanges = findBindingRanges(body);
|
|
280
|
+
const ctx = {
|
|
281
|
+
imports,
|
|
282
|
+
htmlTags,
|
|
283
|
+
escapeFunctions: [...(opts.escapeFunctions ?? []), ...xmlEscapers],
|
|
284
|
+
bindings: findBindings(body, bindingRanges),
|
|
285
|
+
memo: newNameMemo(),
|
|
286
|
+
};
|
|
287
|
+
/**
|
|
288
|
+
* The callee when a hole is one call `accept` takes (`json(x)`), or a
|
|
289
|
+
* name every value of which is (`const body = json(x)`), or undefined.
|
|
290
|
+
*/
|
|
291
|
+
const boundCallee = (expr, question, accept) => boundTo(expr, ctx, question, (e) => {
|
|
292
|
+
const callee = callOf(e);
|
|
293
|
+
return callee !== undefined && accept(callee) ? callee : undefined;
|
|
294
|
+
});
|
|
295
|
+
const lineStarts = [0];
|
|
296
|
+
for (let i = body.indexOf("\n"); i !== -1; i = body.indexOf("\n", i + 1))
|
|
297
|
+
lineStarts.push(i + 1);
|
|
298
|
+
const lineOf = (offset) => {
|
|
299
|
+
let lo = 0;
|
|
300
|
+
let hi = lineStarts.length - 1;
|
|
301
|
+
while (lo < hi) {
|
|
302
|
+
const mid = (lo + hi + 1) >> 1;
|
|
303
|
+
if (lineStarts[mid] <= offset)
|
|
304
|
+
lo = mid;
|
|
305
|
+
else
|
|
306
|
+
hi = mid - 1;
|
|
307
|
+
}
|
|
308
|
+
return lo + 1 + (opts.lineOffset ?? 0);
|
|
309
|
+
};
|
|
310
|
+
const joined = joinedNames(body);
|
|
311
|
+
const projectNames = projectImportNames(body);
|
|
312
|
+
const literalAt = new Map(literals.map((l) => [l.start, l]));
|
|
313
|
+
const errorClasses = classesBefore(body);
|
|
314
|
+
// Which literals are markup the code writes, read once: the markup
|
|
315
|
+
// rule, local helpers and XML nesting all ask.
|
|
316
|
+
const markupLikeOf = literals.map((literal) => {
|
|
317
|
+
const isHtml = literal.tag !== null && ctx.htmlTags.includes(literal.tag);
|
|
318
|
+
// SQL, URLs and plain text: `WHERE id = ${id}` is not an attribute.
|
|
319
|
+
// Build-time code also holds CLI text and generated TypeScript, so it
|
|
320
|
+
// needs an element name, an end tag or an attribute.
|
|
321
|
+
return (isHtml ||
|
|
322
|
+
(requestTime
|
|
323
|
+
? looksLikeMarkup(literal.parts)
|
|
324
|
+
: markupInCode(literal.parts)));
|
|
325
|
+
});
|
|
326
|
+
const { tokens } = scanJavaScript(body);
|
|
327
|
+
// Build-time lint and CLI code passes messages that name elements to its
|
|
328
|
+
// own reporting functions: finding(..., `<${t.tag} data-testid="..."> is
|
|
329
|
+
// a part of ...`). At request time such a function may write a page.
|
|
330
|
+
const messageCalls = requestTime
|
|
331
|
+
? new Set()
|
|
332
|
+
: messageCallArguments(tokens, literals);
|
|
333
|
+
const markupOf = literals.map((literal, k) => {
|
|
334
|
+
// String.raw and common-tags style tags join their values as they are.
|
|
335
|
+
const plainTag = literal.tag !== null && PLAIN_STRING_TAGS.has(literal.tag);
|
|
336
|
+
return (!opts.hasSrcAttribute &&
|
|
337
|
+
(literal.tag === null || plainTag) &&
|
|
338
|
+
markupLikeOf[k] &&
|
|
339
|
+
!FILE_LINE_MESSAGE.test(literal.parts.slice(0, 4).join("\u0000")) &&
|
|
340
|
+
!messageCalls.has(literal.start) &&
|
|
341
|
+
!isMessageArgument(body, literal.start) &&
|
|
342
|
+
!isPatternArgument(body, literal.start) &&
|
|
343
|
+
!errorSuperArgument(body, literal.start, errorClasses));
|
|
344
|
+
});
|
|
345
|
+
// Literals are in source order, outer before nested, so the literal
|
|
346
|
+
// whose hole holds this one is on a stack of the ones still open.
|
|
347
|
+
const literalStarts = literals.map((l) => l.start);
|
|
348
|
+
const markupCount = [0];
|
|
349
|
+
for (const m of markupOf)
|
|
350
|
+
markupCount.push(markupCount[markupCount.length - 1] + (m ? 1 : 0));
|
|
351
|
+
/** Whether a markup literal starts between `from` and `to`. */
|
|
352
|
+
const markupWithin = (from, to) => markupCount[firstAtOrAfter(literalStarts, to)] -
|
|
353
|
+
markupCount[firstAtOrAfter(literalStarts, from)] >
|
|
354
|
+
0;
|
|
355
|
+
// What may hold markup built as a string: wrapping a template whose hole
|
|
356
|
+
// holds one in html would escape it, so the page would show its tags.
|
|
357
|
+
const functions = localFunctions(body, tokens);
|
|
358
|
+
const markupSources = markupSourceStarts(body, tokens, literals.filter((_, k) => markupOf[k]).map((l) => l.start));
|
|
359
|
+
/** Whether a markup literal (a template or a quoted string) starts between `from` and `to`. */
|
|
360
|
+
const sourceWithin = (from, to) => firstAtOrAfter(markupSources, to) > firstAtOrAfter(markupSources, from);
|
|
361
|
+
// In a module, what other modules can call (exported functions, classes
|
|
362
|
+
// and objects) may be passed markup by any caller: its parameters count
|
|
363
|
+
// as possibly markup, unless typed number, bigint or boolean. A directive
|
|
364
|
+
// script's own default export is called by Bascik, not by other modules.
|
|
365
|
+
const externalParams = new Map();
|
|
366
|
+
if (opts.directive === "module") {
|
|
367
|
+
for (const [name, owners] of exportReachableParameters(body, tokens))
|
|
368
|
+
externalParams.set(name, [...owners]);
|
|
369
|
+
// Callbacks, methods and functions passed on or returned: their
|
|
370
|
+
// callers are out of sight too. An exported owner's label is kept.
|
|
371
|
+
for (const [name, owners] of unseenCallerParameters(body, tokens)) {
|
|
372
|
+
const list = externalParams.get(name) ?? [];
|
|
373
|
+
const known = new Set(list.map((o) => o.at));
|
|
374
|
+
for (const owner of owners)
|
|
375
|
+
if (!known.has(owner.at))
|
|
376
|
+
list.push(owner);
|
|
377
|
+
externalParams.set(name, list);
|
|
378
|
+
}
|
|
379
|
+
// In source order, for reachableOwnerAt's binary search.
|
|
380
|
+
for (const list of externalParams.values())
|
|
381
|
+
list.sort((x, y) => x.at - y.at);
|
|
382
|
+
}
|
|
383
|
+
const producers = markupProducers(tokens, functions, bindingRanges, sourceWithin, projectNames, (name) => htmlExportOf(name, imports) !== undefined ||
|
|
384
|
+
ctx.escapeFunctions.includes(name), externalParams);
|
|
385
|
+
// Local functions that build a markup string: a hole that calls one
|
|
386
|
+
// holds markup, which wrapping the template in html would escape.
|
|
387
|
+
const localHelpers = new Set();
|
|
388
|
+
for (const fn of functions)
|
|
389
|
+
if (producers.markupNames.has(fn.name))
|
|
390
|
+
localHelpers.add(fn.name);
|
|
391
|
+
/** The first call in `from`..`to` whose result this file cannot see into. */
|
|
392
|
+
const opaqueWithin = (from, to) => {
|
|
393
|
+
const k = firstAtOrAfter(producers.opaqueStarts, from);
|
|
394
|
+
return k < producers.opaqueStarts.length && producers.opaqueStarts[k] < to
|
|
395
|
+
? producers.opaqueValues[k]
|
|
396
|
+
: undefined;
|
|
397
|
+
};
|
|
398
|
+
// Untagged templates whose text holds & or <, which html would escape.
|
|
399
|
+
const characterCount = [0];
|
|
400
|
+
for (const l of literals)
|
|
401
|
+
characterCount.push(characterCount[characterCount.length - 1] +
|
|
402
|
+
(l.tag === null && l.parts.some(holdsMarkupCharacter) ? 1 : 0));
|
|
403
|
+
// Untagged templates with holes, which turn an html value in them into text.
|
|
404
|
+
const plainTemplateCount = [0];
|
|
405
|
+
for (const l of literals)
|
|
406
|
+
plainTemplateCount.push(plainTemplateCount[plainTemplateCount.length - 1] +
|
|
407
|
+
((l.tag === null || PLAIN_STRING_TAGS.has(l.tag)) && l.holes.length > 0
|
|
408
|
+
? 1
|
|
409
|
+
: 0));
|
|
410
|
+
// The allowlist: a hole keeps the fix only when it is provably plain data.
|
|
411
|
+
const unprovenIn = plainHoleChecker(body, tokens, {
|
|
412
|
+
requestTime,
|
|
413
|
+
functions,
|
|
414
|
+
holes: literals.flatMap((l) => l.holes.map((h) => [h.start + 2, h.end - 1])),
|
|
415
|
+
markupWithin: sourceWithin,
|
|
416
|
+
markupCharacterTextWithin: (from, to) => characterCount[firstAtOrAfter(literalStarts, to)] -
|
|
417
|
+
characterCount[firstAtOrAfter(literalStarts, from)] >
|
|
418
|
+
0,
|
|
419
|
+
plainTemplateWithin: (from, to) => plainTemplateCount[firstAtOrAfter(literalStarts, to)] -
|
|
420
|
+
plainTemplateCount[firstAtOrAfter(literalStarts, from)] >
|
|
421
|
+
0,
|
|
422
|
+
isHtmlValue: (name) => {
|
|
423
|
+
const exported = htmlExportOf(name, imports);
|
|
424
|
+
return (exported === "html" ||
|
|
425
|
+
exported === "raw" ||
|
|
426
|
+
exported === "safeUrl" ||
|
|
427
|
+
exported === "json");
|
|
428
|
+
},
|
|
429
|
+
htmlTags: ctx.htmlTags,
|
|
430
|
+
templateEndAt: (start) => literalAt.get(start)?.end,
|
|
431
|
+
});
|
|
432
|
+
/** The first name in `from`..`to` that may hold markup, or undefined. */
|
|
433
|
+
const producerWithin = (from, to) => {
|
|
434
|
+
const k = firstAtOrAfter(producers.starts, from);
|
|
435
|
+
return k < producers.starts.length && producers.starts[k] < to
|
|
436
|
+
? producers.values[k]
|
|
437
|
+
: undefined;
|
|
438
|
+
};
|
|
439
|
+
/**
|
|
440
|
+
* Why wrapping this template in html would escape what a hole holds:
|
|
441
|
+
* a hole that may hold markup built as a string, or one escaped with
|
|
442
|
+
* esc() or a listed escaper already. Undefined when every hole is plain
|
|
443
|
+
* data.
|
|
444
|
+
*/
|
|
445
|
+
const withholdReason = (literal, contexts, fenced) => {
|
|
446
|
+
for (const hole of literal.holes) {
|
|
447
|
+
if (contexts[hole.index - 1].kind === "comment")
|
|
448
|
+
continue;
|
|
449
|
+
if (fenced?.has(hole.index))
|
|
450
|
+
continue;
|
|
451
|
+
const shown = `${quoteHole(hole.expr)} (hole ${hole.index})`;
|
|
452
|
+
const callee = boundCallee(hole.expr, "escaper", (c) => htmlExportOf(c, imports) === "esc" || ctx.escapeFunctions.includes(c));
|
|
453
|
+
const at = { hole: hole.index, shown };
|
|
454
|
+
if (callee !== undefined)
|
|
455
|
+
return {
|
|
456
|
+
...at,
|
|
457
|
+
text: `is escaped already, and html would escape it again. Wrap the template in html\`...\` from @bascik/bascik/html and pass that value as it is, without ${callee}().`,
|
|
458
|
+
};
|
|
459
|
+
if (sourceWithin(hole.start + 2, hole.end - 1))
|
|
460
|
+
return {
|
|
461
|
+
...at,
|
|
462
|
+
text: `builds markup as a string, which html would escape, so the page would show its tags as text. Build that markup with html\`...\` first, since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`,
|
|
463
|
+
};
|
|
464
|
+
const opaque = opaqueWithin(hole.start + 2, hole.end - 1);
|
|
465
|
+
if (opaque !== undefined)
|
|
466
|
+
return {
|
|
467
|
+
...at,
|
|
468
|
+
text: opaque === ENV_READ
|
|
469
|
+
? `reads ${ENV_READ}, an environment variable this file cannot see into; if it is markup, html would escape it, so the page would show its tags as text. Make that value an html\`...\` value (raw() for trusted markup), since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`
|
|
470
|
+
: `calls ${opaque}(), whose result this file cannot see into (a callback, a package function, a file or a response); if it is markup, html would escape it, so the page would show its tags as text. Make that value an html\`...\` value (raw() for trusted markup), since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`,
|
|
471
|
+
};
|
|
472
|
+
const name = producerWithin(hole.start + 2, hole.end - 1);
|
|
473
|
+
if (name !== undefined) {
|
|
474
|
+
const seed = producers.fromSeed.get(name);
|
|
475
|
+
if (seed !== undefined && seed !== name)
|
|
476
|
+
return {
|
|
477
|
+
...at,
|
|
478
|
+
text: `reads ${name}, which is taken from ${callerClause(seed, reachableOwnerAt(externalParams, seed, hole.start))}, which html would escape, so the page would show its tags as text. Build the callers' markup with html\`...\` (raw() for fixed markup) and pass html values, since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`,
|
|
479
|
+
};
|
|
480
|
+
const owner = reachableOwnerAt(externalParams, name, hole.start);
|
|
481
|
+
return {
|
|
482
|
+
...at,
|
|
483
|
+
text: owner !== undefined
|
|
484
|
+
? `reads ${callerClause(name, owner)}, which html would escape, so the page would show its tags as text. Build the callers' markup with html\`...\` (raw() for fixed markup) and pass html values, since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`
|
|
485
|
+
: !producers.names.has(name)
|
|
486
|
+
? `reads ${name}, imported from a project module, which may hold markup as a string; html would escape it, so the page would show its tags as text. Make that value an html\`...\` value in its module (raw() for fixed markup), since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`
|
|
487
|
+
: producers.markupNames.has(name)
|
|
488
|
+
? `reads ${name}, which may hold markup built as a string in this file; html would escape it, so the page would show its tags as text. Build that markup with html\`...\` first (raw() for fixed markup), since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`
|
|
489
|
+
: `reads ${name}, which holds what this file cannot see into (a callback, a package function, a file, a response or an environment variable); if it is markup, html would escape it, so the page would show its tags as text. Make that value an html\`...\` value (raw() for trusted markup), since html inserts an html value as it is, then wrap this template in html\`...\` from @bascik/bascik/html.`,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
// Then the allowlist: every hole must be provably plain data.
|
|
494
|
+
for (const hole of literal.holes) {
|
|
495
|
+
if (contexts[hole.index - 1].kind === "comment")
|
|
496
|
+
continue;
|
|
497
|
+
if (fenced?.has(hole.index))
|
|
498
|
+
continue;
|
|
499
|
+
if (isHtmlHole(hole.expr))
|
|
500
|
+
continue;
|
|
501
|
+
const unproven = unprovenIn(hole.start + 2, hole.end - 1);
|
|
502
|
+
if (unproven !== undefined)
|
|
503
|
+
return {
|
|
504
|
+
hole: hole.index,
|
|
505
|
+
shown: `${quoteHole(hole.expr)} (hole ${hole.index})`,
|
|
506
|
+
text: `reads ${unproven.what}, ${unproven.why}, so Bascik ${UNPROVEN_TEXT}`,
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
return undefined;
|
|
510
|
+
};
|
|
511
|
+
/** A hole that is an html value: html inserts it as it is, so wrapping keeps it. */
|
|
512
|
+
const isHtmlHole = (expr) => {
|
|
513
|
+
const e = expr.trim();
|
|
514
|
+
const callee = callOf(e);
|
|
515
|
+
if (callee !== undefined) {
|
|
516
|
+
const exported = htmlExportOf(callee, imports);
|
|
517
|
+
if (exported === "html" ||
|
|
518
|
+
exported === "raw" ||
|
|
519
|
+
exported === "safeUrl" ||
|
|
520
|
+
exported === "json")
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
return ctx.htmlTags.some((tag) => e.startsWith(`${tag}\``) ||
|
|
524
|
+
new RegExp(`=>\\s*${escapeRegExp(tag)}\``).test(e));
|
|
525
|
+
};
|
|
526
|
+
const markupStrings = markupStringNames(body);
|
|
527
|
+
const helperMemo = new Map();
|
|
528
|
+
const localHelperMemo = new Map();
|
|
529
|
+
const builtMemo = new Map();
|
|
530
|
+
/** A hole that holds markup already built as a string: joined, a nested template, or a name bound to one. */
|
|
531
|
+
const holdsBuiltMarkup = (hole) => {
|
|
532
|
+
if (isJoined(hole.expr, joined))
|
|
533
|
+
return true;
|
|
534
|
+
if (markupWithin(hole.start + 1, hole.end))
|
|
535
|
+
return true;
|
|
536
|
+
const name = hole.expr.trim();
|
|
537
|
+
if (!/^[\w$]+$/.test(name))
|
|
538
|
+
return false;
|
|
539
|
+
let known = builtMemo.get(name);
|
|
540
|
+
if (known === undefined) {
|
|
541
|
+
known = (ctx.bindings.get(name) ?? []).some((value) => /^\s*`/.test(value));
|
|
542
|
+
builtMemo.set(name, known);
|
|
543
|
+
}
|
|
544
|
+
return known;
|
|
545
|
+
};
|
|
546
|
+
const stringTypedAt = stringTypedFlow(body, tokens);
|
|
547
|
+
const xmlOf = [];
|
|
548
|
+
const open = [];
|
|
549
|
+
/**
|
|
550
|
+
* The untagged template a hole holds whole (`${`<li>${x}</li>`}`), found
|
|
551
|
+
* by offset: its holes are checked as its own, so the outer hole is fine
|
|
552
|
+
* exactly when the inner template has none. Read this way, templates
|
|
553
|
+
* nested deep in each other's holes are not each rescanned as text.
|
|
554
|
+
*/
|
|
555
|
+
const wholeTemplateIn = (hole) => {
|
|
556
|
+
let k = hole.start + 2;
|
|
557
|
+
while (k < hole.end && /\s/.test(body[k]))
|
|
558
|
+
k++;
|
|
559
|
+
const inner = literalAt.get(k);
|
|
560
|
+
if (!inner || inner.tag !== null)
|
|
561
|
+
return undefined;
|
|
562
|
+
let j = inner.end;
|
|
563
|
+
while (j < hole.end - 1 && /\s/.test(body[j]))
|
|
564
|
+
j++;
|
|
565
|
+
return j === hole.end - 1 && body[j] === "}" ? inner : undefined;
|
|
566
|
+
};
|
|
567
|
+
for (let k = 0; k < literals.length; k++) {
|
|
568
|
+
const literal = literals[k];
|
|
569
|
+
const isHtml = literal.tag !== null && ctx.htmlTags.includes(literal.tag);
|
|
570
|
+
const markupLike = markupLikeOf[k];
|
|
571
|
+
const plainTag = literal.tag !== null && PLAIN_STRING_TAGS.has(literal.tag);
|
|
572
|
+
const markup = markupOf[k];
|
|
573
|
+
while (open.length > 0 &&
|
|
574
|
+
literals[open[open.length - 1]].end <= literal.start)
|
|
575
|
+
open.pop();
|
|
576
|
+
const parent = open.length > 0 ? open[open.length - 1] : -1;
|
|
577
|
+
open.push(k);
|
|
578
|
+
const pending = [];
|
|
579
|
+
// An XML document or fragment (a sitemap, an RSS or Atom feed), or a
|
|
580
|
+
// template nested in one's holes: html builds HTML, so it gets esc()
|
|
581
|
+
// advice and no fix.
|
|
582
|
+
const xml = markup &&
|
|
583
|
+
(XML_TEMPLATE.test(literal.parts[0]) || (parent !== -1 && xmlOf[parent]));
|
|
584
|
+
xmlOf[k] = xml;
|
|
585
|
+
// Where each hole lands, read once for the whole template.
|
|
586
|
+
const scanned = scanTemplateHtml(literal.parts);
|
|
587
|
+
// The fix puts html before the backtick, so a tagged template and one
|
|
588
|
+
// where html would throw (a tag name, an attribute name, a comment) get
|
|
589
|
+
// no fix.
|
|
590
|
+
const throwsAt = scanned.throwsAt;
|
|
591
|
+
let fixable = markup && !plainTag && !xml && throwsAt === -1;
|
|
592
|
+
// Markdown with fenced blocks: a hole in a fence is text the Markdown
|
|
593
|
+
// renderer escapes, and html would escape the fence's code as well.
|
|
594
|
+
const fences = markup && !requestTime ? markdownFences(literal.parts) : undefined;
|
|
595
|
+
if (fences?.hasFence)
|
|
596
|
+
fixable = false;
|
|
597
|
+
const reason = fixable
|
|
598
|
+
? withholdReason(literal, scanned.holes, fences?.fencedHoles)
|
|
599
|
+
: undefined;
|
|
600
|
+
if (reason !== undefined)
|
|
601
|
+
fixable = false;
|
|
602
|
+
// A value typed string (`): string`, `const x: string =`, `as string`):
|
|
603
|
+
// as an html value it would fail type checking, so no fix.
|
|
604
|
+
const typedAs = fixable && literal.tag === null && parent === -1
|
|
605
|
+
? stringTypedAt(literal.start, literal.end)
|
|
606
|
+
: undefined;
|
|
607
|
+
if (typedAs !== undefined)
|
|
608
|
+
fixable = false;
|
|
609
|
+
for (const hole of literal.holes) {
|
|
610
|
+
const context = scanned.holes[hole.index - 1];
|
|
611
|
+
const inner = wholeTemplateIn(hole);
|
|
612
|
+
const holeIsExempt = () => inner !== undefined
|
|
613
|
+
? inner.holes.length === 0
|
|
614
|
+
: isExempt(hole.expr, ctx);
|
|
615
|
+
const shown = quoteHole(hole.expr);
|
|
616
|
+
// A placeholder inside a <!-- --> comment within the literal is skipped.
|
|
617
|
+
if (context.kind === "comment")
|
|
618
|
+
continue;
|
|
619
|
+
if (fences?.fencedHoles.has(hole.index))
|
|
620
|
+
continue;
|
|
621
|
+
// A name set to a markup string in this file (`icon = '<svg>...'`,
|
|
622
|
+
// `shape: '<path ... />'`): wrapping would escape it, fine or not.
|
|
623
|
+
const markupString = !isHtml && !xml && markup
|
|
624
|
+
? markupStringIn(hole.expr, markupStrings)
|
|
625
|
+
: undefined;
|
|
626
|
+
if (markupString !== undefined)
|
|
627
|
+
fixable = false;
|
|
628
|
+
// A fragment that has opened no tag yet (` href="${u}"`) is read the
|
|
629
|
+
// old way, over a bounded stretch of text before the hole.
|
|
630
|
+
const found = context.kind === "text" && !context.sawTag
|
|
631
|
+
? sinkOf(body.slice(Math.max(literal.start + 1, hole.start - FRAGMENT_WINDOW), hole.start))
|
|
632
|
+
: sinkOfContext(context);
|
|
633
|
+
const sink = !markupLike && found === "server-script-sink-unquoted-attribute"
|
|
634
|
+
? null
|
|
635
|
+
: found;
|
|
636
|
+
const at = { start: hole.start, end: hole.end };
|
|
637
|
+
const inAttribute = context.kind === "value";
|
|
638
|
+
if (isHtml) {
|
|
639
|
+
if (sink === "server-script-sink-inline-script") {
|
|
640
|
+
// <script type="application/json">${json(value)}</script> is
|
|
641
|
+
// html's own form, also through a name bound to json(value).
|
|
642
|
+
const isJsonScript = context.kind === "raw" && context.jsonScript;
|
|
643
|
+
if (isJsonScript &&
|
|
644
|
+
boundCallee(hole.expr, "json", (c) => htmlExportOf(c, imports) === "json") !== undefined)
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
if (sink !== null && sink in HTML_THROWS) {
|
|
648
|
+
diagnostics.push({
|
|
649
|
+
code: sink,
|
|
650
|
+
message: HTML_THROWS[sink],
|
|
651
|
+
severity: "error",
|
|
652
|
+
...at,
|
|
653
|
+
});
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
if (sink === null &&
|
|
657
|
+
boundCallee(hole.expr, "esc", (c) => htmlExportOf(c, imports) === "esc") !== undefined)
|
|
658
|
+
diagnostics.push({
|
|
659
|
+
code: "html-escaped-twice",
|
|
660
|
+
message: "esc() inside html`...` escapes twice, so the page shows &lt;. Pass the value as it is: html escapes it.",
|
|
661
|
+
severity: "info",
|
|
662
|
+
...at,
|
|
663
|
+
});
|
|
664
|
+
if (sink === null && !inAttribute && isJoined(hole.expr, joined))
|
|
665
|
+
diagnostics.push({
|
|
666
|
+
code: JOINED_RULE,
|
|
667
|
+
message: 'This hole joins its items into one string, which html escapes, so the page shows <li> as text. Pass the array without .join(""): html inserts each html`...` item as it is.',
|
|
668
|
+
severity: "warning",
|
|
669
|
+
...at,
|
|
670
|
+
});
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
// JSON.stringify(...).replace(/</g, "\\u003c") in a JSON script can
|
|
674
|
+
// never close it: the safe JSON-LD pattern.
|
|
675
|
+
if (sink === "server-script-sink-inline-script" &&
|
|
676
|
+
context.kind === "raw" &&
|
|
677
|
+
context.jsonScript &&
|
|
678
|
+
isEscapedJson(hole.expr, ctx))
|
|
679
|
+
continue;
|
|
680
|
+
if (context.kind === "name") {
|
|
681
|
+
// A tag or attribute name: html throws here, so wrapping cannot
|
|
682
|
+
// help. Build-time names are the site's own (`<h${level}>`,
|
|
683
|
+
// `<th${attributes}>`); a request value here is an injection.
|
|
684
|
+
fixable = false;
|
|
685
|
+
if (requestTime && markup && !holeIsExempt())
|
|
686
|
+
pending.push({
|
|
687
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
688
|
+
message: `This markup template (line ${lineOf(literal.start)}) puts ${shown} (hole ${hole.index}) where a tag or attribute name goes. html\`...\` throws there and escaping cannot make it safe: choose between fixed names in code (for example level === 1 ? "h1" : "h2").`,
|
|
689
|
+
severity: "warning",
|
|
690
|
+
...at,
|
|
691
|
+
});
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
if (sink !== null &&
|
|
695
|
+
sink !== "server-script-sink-url-attribute" &&
|
|
696
|
+
!requestTime) {
|
|
697
|
+
// Build time: html would throw here, so no fix, and no
|
|
698
|
+
// unescaped-markup report either (wrapping would not help). An
|
|
699
|
+
// unquoted value or a <script> body breaks on a space or a
|
|
700
|
+
// </script> in the value, whoever wrote it, so those warn unless the
|
|
701
|
+
// value is exempt. An event handler or style value is the site's
|
|
702
|
+
// own at build time (a CSS custom property from data is common), so
|
|
703
|
+
// those are request-time warnings only.
|
|
704
|
+
fixable = false;
|
|
705
|
+
if (markup &&
|
|
706
|
+
(sink === "server-script-sink-unquoted-attribute" ||
|
|
707
|
+
sink === "server-script-sink-inline-script") &&
|
|
708
|
+
!holeIsExempt())
|
|
709
|
+
diagnostics.push({
|
|
710
|
+
code: sink,
|
|
711
|
+
message: SINK_MESSAGES[sink],
|
|
712
|
+
severity: "warning",
|
|
713
|
+
...at,
|
|
714
|
+
});
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (sink !== null && sink !== "server-script-sink-url-attribute") {
|
|
718
|
+
fixable = false;
|
|
719
|
+
diagnostics.push({
|
|
720
|
+
code: sink,
|
|
721
|
+
message: SINK_MESSAGES[sink],
|
|
722
|
+
severity: "warning",
|
|
723
|
+
...at,
|
|
724
|
+
});
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
const exempt = holeIsExempt();
|
|
728
|
+
if (markup && !exempt) {
|
|
729
|
+
const escaper = inner === undefined ? handEscaper(hole.expr) : undefined;
|
|
730
|
+
if (xml) {
|
|
731
|
+
// Any entity escaper is right for XML text and quoted values.
|
|
732
|
+
if (escaper !== undefined)
|
|
733
|
+
continue;
|
|
734
|
+
// Markup built already (a joined list of <item>s, a nested
|
|
735
|
+
// template, a name bound to one): its own templates are checked
|
|
736
|
+
// as XML, and escaping it again would show its tags as text.
|
|
737
|
+
if (holdsBuiltMarkup(hole))
|
|
738
|
+
continue;
|
|
739
|
+
pending.push({
|
|
740
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
741
|
+
message: `This XML template (line ${lineOf(literal.start)}) interpolates ${shown} (hole ${hole.index}) without escaping. html\`...\` builds HTML, not XML, so escape the value with esc() from @bascik/bascik/html (its entities are valid XML too), or with an XML escaper that has a comment saying it is for XML.`,
|
|
742
|
+
severity: "warning",
|
|
743
|
+
...at,
|
|
744
|
+
});
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
const head = `This markup template (line ${lineOf(literal.start)}) interpolates ${shown} (hole ${hole.index}) without html.`;
|
|
748
|
+
// The quick fix would escape twice: the escaper's output, or the
|
|
749
|
+
// markup in a joined string, would show as text.
|
|
750
|
+
if (escaper !== undefined ||
|
|
751
|
+
(inner === undefined && isJoined(hole.expr, joined)))
|
|
752
|
+
fixable = false;
|
|
753
|
+
// A project helper may return a markup string (a card, a list),
|
|
754
|
+
// which html would escape: the page would show its tags as text.
|
|
755
|
+
const helper = escaper === undefined && inner === undefined
|
|
756
|
+
? projectHelperIn(hole.expr, projectNames, ctx.bindings, helperMemo)
|
|
757
|
+
: undefined;
|
|
758
|
+
if (helper !== undefined) {
|
|
759
|
+
fixable = false;
|
|
760
|
+
pending.push({
|
|
761
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
762
|
+
message: `${head} ${helper}() comes from a project module: if it returns markup as a string, wrapping this template in html would show its tags as text. Build that function's markup with html\`...\` first, since html inserts an html value as it is, then wrap this template.`,
|
|
763
|
+
severity: "warning",
|
|
764
|
+
...at,
|
|
765
|
+
});
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
const localHelper = escaper === undefined && inner === undefined
|
|
769
|
+
? projectHelperIn(hole.expr, localHelpers, ctx.bindings, localHelperMemo)
|
|
770
|
+
: undefined;
|
|
771
|
+
if (localHelper !== undefined) {
|
|
772
|
+
fixable = false;
|
|
773
|
+
pending.push({
|
|
774
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
775
|
+
message: `${head} ${localHelper}() builds markup as a string in this file, so wrapping this template in html would show its tags as text. Build that function's markup with html\`...\` first, since html inserts an html value as it is, then wrap this template.`,
|
|
776
|
+
severity: "warning",
|
|
777
|
+
...at,
|
|
778
|
+
});
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
if (markupString !== undefined) {
|
|
782
|
+
pending.push({
|
|
783
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
784
|
+
message: `${head} ${markupString} is set to a markup string in this file, so wrapping this template in html would show its tags as text. Make that value an html\`...\` value first (raw() for fixed markup), since html inserts an html value as it is, then wrap this template.`,
|
|
785
|
+
severity: "warning",
|
|
786
|
+
...at,
|
|
787
|
+
});
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
// html would throw on this template, so the advice is esc().
|
|
791
|
+
const throwsReason = throwsAt > 0
|
|
792
|
+
? `hole ${throwsAt} sits where html throws`
|
|
793
|
+
: throwsAt === 0
|
|
794
|
+
? "it ends inside a tag"
|
|
795
|
+
: undefined;
|
|
796
|
+
let message;
|
|
797
|
+
if (fences?.hasFence && escaper === undefined)
|
|
798
|
+
message = `${head} The template also holds a Markdown code fence, whose code html would escape as well, so build the markup outside the fence with html\`...\` from @bascik/bascik/html, or escape the value with esc() from the same module.`;
|
|
799
|
+
else if (throwsReason !== undefined)
|
|
800
|
+
message =
|
|
801
|
+
escaper !== undefined
|
|
802
|
+
? `${head} ${escaper.name}() looks like a hand-written escaper. html\`...\` cannot build this template as it is (${throwsReason}), so call esc() from @bascik/bascik/html in its place, or list ${escaper.name}() in diagnostics.escapeFunctions if it is a trusted escaper.`
|
|
803
|
+
: `${head} html\`...\` cannot build this template as it is (${throwsReason}), so escape the value with esc() from @bascik/bascik/html.`;
|
|
804
|
+
else
|
|
805
|
+
message =
|
|
806
|
+
escaper !== undefined
|
|
807
|
+
? `${head} ${escaper.name}() looks like a hand-written escaper, and html escapes too, so wrapping this template in html would show &lt; on the page. Wrap it in html\`...\` and pass the value as it is: \${${escaper.args}}. If ${escaper.name}() is a trusted escaper, list it in diagnostics.escapeFunctions.`
|
|
808
|
+
: inner === undefined && isJoined(hole.expr, joined)
|
|
809
|
+
? `${head} It joins markup into one string, which html would escape, so wrapping only this template would show the inner tags as text. Wrap the inner templates in html\`...\`, drop .join(""), and pass the array; then wrap this template in html\`...\` from @bascik/bascik/html.`
|
|
810
|
+
: typedAs !== undefined
|
|
811
|
+
? `${head} Wrapping this template in html is not offered as a fix: its value goes where the code declares \`: ${typedAs}\`, and html makes a SafeHtml value, so type checking would fail. Change that type to SafeHtml (import type { SafeHtml } from "@bascik/bascik/html"), then wrap the template in html\`...\` from @bascik/bascik/html yourself.`
|
|
812
|
+
: reason === undefined
|
|
813
|
+
? `${head} Wrap the template in html\`...\` from @bascik/bascik/html, which escapes each value for where it lands.`
|
|
814
|
+
: reason.hole === hole.index
|
|
815
|
+
? `${head} It ${reason.text}`
|
|
816
|
+
: `${head} Wrapping this template in html is not offered as a fix: ${reason.shown} ${reason.text}`;
|
|
817
|
+
pending.push({
|
|
818
|
+
code: UNESCAPED_MARKUP_RULE,
|
|
819
|
+
message,
|
|
820
|
+
severity: "warning",
|
|
821
|
+
...at,
|
|
822
|
+
});
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
// A checked value in a URL attribute and request values in text are
|
|
826
|
+
// request-time concerns: build-time values are the site's own.
|
|
827
|
+
if (!requestTime)
|
|
828
|
+
continue;
|
|
829
|
+
if (sink === "server-script-sink-url-attribute") {
|
|
830
|
+
// safeUrl() in the hole, or in every value of a name it reads.
|
|
831
|
+
const importsSafeUrl = [...ctx.imports.named.values()].includes("safeUrl");
|
|
832
|
+
const checked = boundTo(hole.expr, ctx, "safeUrl", (e) => {
|
|
833
|
+
const callee = callOf(e);
|
|
834
|
+
return (importsSafeUrl &&
|
|
835
|
+
/\bsafeUrl\s*\(|\.safeUrl\s*\(/.test(e)) ||
|
|
836
|
+
(callee !== undefined &&
|
|
837
|
+
htmlExportOf(callee, imports) === "safeUrl")
|
|
838
|
+
? "safeUrl"
|
|
839
|
+
: undefined;
|
|
840
|
+
}) !== undefined;
|
|
841
|
+
if (!checked)
|
|
842
|
+
diagnostics.push({
|
|
843
|
+
code: sink,
|
|
844
|
+
message: SINK_MESSAGES[sink],
|
|
845
|
+
severity: "warning",
|
|
846
|
+
...at,
|
|
847
|
+
});
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
// Text: a request value with no escaping call around it (info). A
|
|
851
|
+
// whole inner template's own holes are checked as its own.
|
|
852
|
+
if (inner !== undefined)
|
|
853
|
+
continue;
|
|
854
|
+
const trimmedExpr = hole.expr.trim();
|
|
855
|
+
const referencesRequestData = trimmedExpr.includes("request.") ||
|
|
856
|
+
trimmedExpr.includes("context.") ||
|
|
857
|
+
trimmedExpr.includes("searchParams") ||
|
|
858
|
+
trimmedExpr.includes(".headers.get(") ||
|
|
859
|
+
trimmedExpr.includes("URL(request.url)");
|
|
860
|
+
// Direct request/context access like `request.headers.get(...)` or
|
|
861
|
+
// `new URL(...)` reads request data; it is not an escaping wrapper.
|
|
862
|
+
const isEscapingCall = /^[A-Za-z_$][\w$]*\s*\(/.test(trimmedExpr) &&
|
|
863
|
+
!trimmedExpr.startsWith("request.") &&
|
|
864
|
+
!trimmedExpr.startsWith("context.") &&
|
|
865
|
+
!trimmedExpr.startsWith("new URL(");
|
|
866
|
+
if (!isEscapingCall && referencesRequestData && !exempt && markupLike)
|
|
867
|
+
diagnostics.push({
|
|
868
|
+
code: "server-script-sink-text-unescaped",
|
|
869
|
+
message: "Untrusted request value interpolated without escaping. Build the markup with html`...` from @bascik/bascik/html, or wrap the value in esc().",
|
|
870
|
+
severity: "info",
|
|
871
|
+
...at,
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
for (const diagnostic of pending)
|
|
264
875
|
diagnostics.push({
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
severity: "warning",
|
|
268
|
-
start: placeholderStart,
|
|
269
|
-
end: placeholderEnd,
|
|
876
|
+
...diagnostic,
|
|
877
|
+
template: { start: literal.start, fixable },
|
|
270
878
|
});
|
|
879
|
+
}
|
|
880
|
+
return diagnostics;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The local names a script imports from its project's own modules (a
|
|
884
|
+
* `./`, `../` or `@/` specifier): default, named (`a as b`) and namespace
|
|
885
|
+
* imports. Type-only imports bind no value and are left out. The import
|
|
886
|
+
* clause is bounded, so the scan stays linear.
|
|
887
|
+
*/
|
|
888
|
+
const MAX_IMPORT_CLAUSE = 1000;
|
|
889
|
+
function projectImportNames(body) {
|
|
890
|
+
const names = new Set();
|
|
891
|
+
// Each `import` is read forward to its `from` by hand: a single regular expression with a bounded clause before
|
|
892
|
+
// `\s+from` backtracks quadratically on a long clause, and `\s+from` alone does so on a run of white space, so
|
|
893
|
+
// the white space before `from` is checked by hand too.
|
|
894
|
+
const from = /\bfrom\s*["'](?:\.\.?\/|@\/)/g;
|
|
895
|
+
for (const m of body.matchAll(/\bimport\s+(?!type\s)/g)) {
|
|
896
|
+
const start = m.index + m[0].length;
|
|
897
|
+
// Only as far as a clause can reach, so many imports stay linear in the script.
|
|
898
|
+
const reach = body.slice(start, start + MAX_IMPORT_CLAUSE + 16);
|
|
899
|
+
from.lastIndex = 0;
|
|
900
|
+
const end = from.exec(reach);
|
|
901
|
+
if (!end)
|
|
902
|
+
continue;
|
|
903
|
+
const clause = reach.slice(0, end.index).trimEnd();
|
|
904
|
+
if (clause.length === 0 ||
|
|
905
|
+
clause.length === end.index ||
|
|
906
|
+
clause.length > MAX_IMPORT_CLAUSE ||
|
|
907
|
+
/[;'"`]/.test(clause))
|
|
271
908
|
continue;
|
|
909
|
+
const brace = /\{([^}]*)\}/.exec(clause);
|
|
910
|
+
if (brace)
|
|
911
|
+
for (const entry of brace[1].split(",")) {
|
|
912
|
+
if (/^\s*type\s/.test(entry))
|
|
913
|
+
continue;
|
|
914
|
+
const specifier = parseImportSpecifier(entry);
|
|
915
|
+
if (specifier)
|
|
916
|
+
names.add(specifier[1]);
|
|
917
|
+
}
|
|
918
|
+
const rest = brace ? clause.replace(brace[0], "") : clause;
|
|
919
|
+
const namespace = /\*\s*as\s+([\w$]+)/.exec(rest);
|
|
920
|
+
if (namespace)
|
|
921
|
+
names.add(namespace[1]);
|
|
922
|
+
const defaultName = /^\s*([\w$]+)\s*(?:,|$)/.exec(rest);
|
|
923
|
+
if (defaultName)
|
|
924
|
+
names.add(defaultName[1]);
|
|
925
|
+
}
|
|
926
|
+
return names;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* The first project-imported function a hole calls or passes as a
|
|
930
|
+
* callback (`card(p)`, `items.map(card)`; not a member, `x.card`), looking
|
|
931
|
+
* one step through a name bound in the script (`const first = card(p)`),
|
|
932
|
+
* or undefined.
|
|
933
|
+
*/
|
|
934
|
+
function projectHelperIn(expr, names, bindings, memo) {
|
|
935
|
+
if (names.size === 0)
|
|
936
|
+
return undefined;
|
|
937
|
+
const find = (text) => {
|
|
938
|
+
for (const m of text.matchAll(/(?<![\w$.])([\w$]+)(?:\.[\w$]+)*/g)) {
|
|
939
|
+
if (!names.has(m[1]))
|
|
940
|
+
continue;
|
|
941
|
+
const after = text.slice(m.index + m[0].length, m.index + m[0].length + 16);
|
|
942
|
+
// Called (`card(p)`), or passed as a callback (`.map(card)`).
|
|
943
|
+
if (/^\s*\(/.test(after))
|
|
944
|
+
return m[0];
|
|
945
|
+
const before = text.slice(Math.max(0, m.index - 16), m.index);
|
|
946
|
+
if (/[(,]\s*$/.test(before) && /^\s*[,)]/.test(after))
|
|
947
|
+
return m[0];
|
|
272
948
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
if (
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
949
|
+
return undefined;
|
|
950
|
+
};
|
|
951
|
+
const direct = find(expr);
|
|
952
|
+
if (direct !== undefined)
|
|
953
|
+
return direct;
|
|
954
|
+
const name = expr.trim();
|
|
955
|
+
if (!/^[\w$]+$/.test(name))
|
|
956
|
+
return undefined;
|
|
957
|
+
// Read once per name: a name declared in many functions is not rescanned per hole.
|
|
958
|
+
if (memo.has(name))
|
|
959
|
+
return memo.get(name);
|
|
960
|
+
let found;
|
|
961
|
+
for (const value of bindings.get(name) ?? []) {
|
|
962
|
+
found = find(value);
|
|
963
|
+
if (found !== undefined)
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
memo.set(name, found);
|
|
967
|
+
return found;
|
|
968
|
+
}
|
|
969
|
+
/** Index of the first value in ascending `values` that is at least `at`. */
|
|
970
|
+
function firstAtOrAfter(values, at) {
|
|
971
|
+
let lo = 0;
|
|
972
|
+
let hi = values.length;
|
|
973
|
+
while (lo < hi) {
|
|
974
|
+
const mid = (lo + hi) >> 1;
|
|
975
|
+
if (values[mid] < at)
|
|
976
|
+
lo = mid + 1;
|
|
977
|
+
else
|
|
978
|
+
hi = mid;
|
|
979
|
+
}
|
|
980
|
+
return lo;
|
|
981
|
+
}
|
|
982
|
+
/** Each `class` keyword's offset, and whether that class extends an Error (`extends Error`, `extends errors.BuildError`). */
|
|
983
|
+
function classesBefore(body) {
|
|
984
|
+
const classes = [];
|
|
985
|
+
for (const m of body.matchAll(/\bclass\b(?:\s+[\w$]+)?(?:\s+extends\s+([\w$.]+))?/g))
|
|
986
|
+
classes.push({ at: m.index, error: /Error$/.test(m[1] ?? "") });
|
|
987
|
+
return classes;
|
|
988
|
+
}
|
|
989
|
+
/** Whether a literal is the argument of super() in the class (the last one before it) that extends an Error. */
|
|
990
|
+
function errorSuperArgument(body, start, classes) {
|
|
991
|
+
if (!/\bsuper\s*\(\s*$/.test(body.slice(Math.max(0, start - 40), start)))
|
|
992
|
+
return false;
|
|
993
|
+
const k = firstAtOrAfter(classes.map((c) => c.at), start);
|
|
994
|
+
return k > 0 && classes[k - 1].error;
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Names set to a string with a tag in it, as a binding or a property
|
|
998
|
+
* (`const icon = '<svg>...'`, `shape: '<path d="..." />'`).
|
|
999
|
+
*/
|
|
1000
|
+
function markupStringNames(body) {
|
|
1001
|
+
const names = new Set();
|
|
1002
|
+
for (const m of body.matchAll(/(?<![\w$.])([\w$]+)\s*(?::|=(?![=>]))\s*(["'`])\s*<[a-zA-Z]/g))
|
|
1003
|
+
names.add(m[1]);
|
|
1004
|
+
return names;
|
|
1005
|
+
}
|
|
1006
|
+
/** The name a hole reads (`shape`, `statuses[m].shape`) when it is set to a markup string, or undefined. */
|
|
1007
|
+
function markupStringIn(expr, names) {
|
|
1008
|
+
if (names.size === 0)
|
|
1009
|
+
return undefined;
|
|
1010
|
+
const e = expr.trim();
|
|
1011
|
+
if (!/^[\w$]+(?:\??\.[\w$]+|\[[^\]\[]*\])*$/.test(e))
|
|
1012
|
+
return undefined;
|
|
1013
|
+
const last = /([\w$]+)$/.exec(e);
|
|
1014
|
+
return last && names.has(last[1]) ? e : undefined;
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* The functions defined in a script with the span of their code: function
|
|
1018
|
+
* declarations, methods, and functions or arrows bound to a name or a
|
|
1019
|
+
* property. An arrow with an expression body runs to the next `;` or `,`
|
|
1020
|
+
* at its own depth, or the bracket around it. One pass over the tokens.
|
|
1021
|
+
*/
|
|
1022
|
+
function localFunctions(body, tokens = scanJavaScript(body).tokens) {
|
|
1023
|
+
const n = tokens.length;
|
|
1024
|
+
const punct = (k, v) => k >= 0 &&
|
|
1025
|
+
k < n &&
|
|
1026
|
+
tokens[k].type === "punctuation" &&
|
|
1027
|
+
tokens[k].value === v;
|
|
1028
|
+
const word = (k, v) => k >= 0 &&
|
|
1029
|
+
k < n &&
|
|
1030
|
+
tokens[k].type === "identifier" &&
|
|
1031
|
+
(v === undefined || tokens[k].value === v);
|
|
1032
|
+
// Bracket partners, and where each expression-bodied arrow stops.
|
|
1033
|
+
const partner = new Int32Array(n).fill(-1);
|
|
1034
|
+
const stack = [];
|
|
1035
|
+
for (let k = 0; k < n; k++) {
|
|
1036
|
+
const t = tokens[k];
|
|
1037
|
+
if (t.type !== "punctuation")
|
|
295
1038
|
continue;
|
|
1039
|
+
if (t.value === "(" || t.value === "[" || t.value === "{")
|
|
1040
|
+
stack.push(k);
|
|
1041
|
+
else if ((t.value === ")" || t.value === "]" || t.value === "}") &&
|
|
1042
|
+
stack.length > 0) {
|
|
1043
|
+
const o = stack.pop();
|
|
1044
|
+
partner[o] = k;
|
|
1045
|
+
partner[k] = o;
|
|
296
1046
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
1047
|
+
}
|
|
1048
|
+
const found = [];
|
|
1049
|
+
/** After `)` of a parameter list at `close`: the body's `{`, or the token after `=>` (arrow). */
|
|
1050
|
+
const bodyAfter = (close, arrow) => {
|
|
1051
|
+
// Past a short return type: `): string {`, `): Promise<string> =>`.
|
|
1052
|
+
for (let k = close + 1; k < n && k <= close + 24; k++) {
|
|
1053
|
+
if (arrow && punct(k, "=") && punct(k + 1, ">"))
|
|
1054
|
+
return { at: k + 2, arrow: true };
|
|
1055
|
+
if (!arrow && punct(k, "{"))
|
|
1056
|
+
return { at: k, arrow: false };
|
|
1057
|
+
if (punct(k, ";") || punct(k, "}") || punct(k, "="))
|
|
1058
|
+
return undefined;
|
|
1059
|
+
}
|
|
1060
|
+
return undefined;
|
|
1061
|
+
};
|
|
1062
|
+
/**
|
|
1063
|
+
* For `const|let|var NAME: Type =` at NAME (`k`), the `=` token's index,
|
|
1064
|
+
* the annotation's brackets skipped; -1 otherwise. Read for at most 200
|
|
1065
|
+
* tokens, so the pass stays linear.
|
|
1066
|
+
*/
|
|
1067
|
+
const typedBindingEquals = (k) => {
|
|
1068
|
+
if (!punct(k + 1, ":") ||
|
|
1069
|
+
!(word(k - 1, "const") || word(k - 1, "let") || word(k - 1, "var")))
|
|
1070
|
+
return -1;
|
|
1071
|
+
let angle = 0;
|
|
1072
|
+
for (let j = k + 2; j < n && j <= k + 200; j++) {
|
|
1073
|
+
if (tokens[j].type !== "punctuation")
|
|
1074
|
+
continue;
|
|
1075
|
+
const v = tokens[j].value;
|
|
1076
|
+
if (v === "(" || v === "[" || v === "{") {
|
|
1077
|
+
if (partner[j] === -1)
|
|
1078
|
+
return -1;
|
|
1079
|
+
j = partner[j];
|
|
1080
|
+
}
|
|
1081
|
+
else if (v === "<")
|
|
1082
|
+
angle++;
|
|
1083
|
+
else if (v === ">")
|
|
1084
|
+
angle = Math.max(0, angle - 1);
|
|
1085
|
+
else if (v === "=") {
|
|
1086
|
+
if (punct(j + 1, ">"))
|
|
1087
|
+
j++;
|
|
1088
|
+
else if (punct(j + 1, "="))
|
|
1089
|
+
return -1;
|
|
1090
|
+
else if (angle === 0)
|
|
1091
|
+
return j;
|
|
1092
|
+
}
|
|
1093
|
+
else if (v === ";" || v === ")" || v === "]" || v === "}")
|
|
1094
|
+
return -1;
|
|
1095
|
+
}
|
|
1096
|
+
return -1;
|
|
1097
|
+
};
|
|
1098
|
+
for (let k = 0; k < n; k++) {
|
|
1099
|
+
if (word(k, "function") && word(k + 1) && punct(k + 2, "(")) {
|
|
1100
|
+
const close = partner[k + 2];
|
|
1101
|
+
const b = close === -1 ? undefined : bodyAfter(close, false);
|
|
1102
|
+
if (b)
|
|
1103
|
+
found.push({
|
|
1104
|
+
name: tokens[k + 1].value,
|
|
1105
|
+
nameAt: k + 1,
|
|
1106
|
+
body: b.at,
|
|
1107
|
+
arrow: false,
|
|
1108
|
+
params: k + 2,
|
|
1109
|
+
});
|
|
321
1110
|
continue;
|
|
322
1111
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
1112
|
+
if (!word(k))
|
|
1113
|
+
continue;
|
|
1114
|
+
// NAME = ..., NAME: Type = ..., NAME: ... (a property), or a method
|
|
1115
|
+
// NAME(...) {.
|
|
1116
|
+
const typedEq = typedBindingEquals(k);
|
|
1117
|
+
const isBinding = (punct(k + 1, "=") && !punct(k + 2, "=") && !punct(k + 2, ">")) ||
|
|
1118
|
+
typedEq !== -1;
|
|
1119
|
+
const isProperty = punct(k + 1, ":") && (punct(k - 1, "{") || punct(k - 1, ","));
|
|
1120
|
+
if (isBinding || isProperty) {
|
|
1121
|
+
let v = typedEq !== -1 ? typedEq + 1 : k + 2;
|
|
1122
|
+
if (word(v, "async"))
|
|
1123
|
+
v++;
|
|
1124
|
+
if (word(v, "function")) {
|
|
1125
|
+
const paren = word(v + 1) ? v + 2 : v + 1;
|
|
1126
|
+
if (!punct(paren, "(") || partner[paren] === -1)
|
|
1127
|
+
continue;
|
|
1128
|
+
const b = bodyAfter(partner[paren], false);
|
|
1129
|
+
if (b)
|
|
1130
|
+
found.push({
|
|
1131
|
+
name: tokens[k].value,
|
|
1132
|
+
nameAt: k,
|
|
1133
|
+
body: b.at,
|
|
1134
|
+
arrow: false,
|
|
1135
|
+
params: paren,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
else if (punct(v, "(") && partner[v] !== -1) {
|
|
1139
|
+
const b = bodyAfter(partner[v], true);
|
|
1140
|
+
if (b)
|
|
1141
|
+
found.push({
|
|
1142
|
+
name: tokens[k].value,
|
|
1143
|
+
nameAt: k,
|
|
1144
|
+
body: b.at,
|
|
1145
|
+
arrow: true,
|
|
1146
|
+
params: v,
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
else if (word(v) && punct(v + 1, "=") && punct(v + 2, ">"))
|
|
1150
|
+
found.push({
|
|
1151
|
+
name: tokens[k].value,
|
|
1152
|
+
nameAt: k,
|
|
1153
|
+
body: v + 3,
|
|
1154
|
+
arrow: true,
|
|
1155
|
+
params: v,
|
|
1156
|
+
});
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
if (punct(k + 1, "(") &&
|
|
1160
|
+
!punct(k - 1, ".") &&
|
|
1161
|
+
partner[k + 1] !== -1 &&
|
|
1162
|
+
!CONTROL_WORDS.has(tokens[k].value) &&
|
|
1163
|
+
(punct(k - 1, "{") ||
|
|
1164
|
+
punct(k - 1, "}") ||
|
|
1165
|
+
punct(k - 1, ";") ||
|
|
1166
|
+
punct(k - 1, ",") ||
|
|
1167
|
+
(word(k - 1) && METHOD_MODIFIERS.has(tokens[k - 1].value)))) {
|
|
1168
|
+
const b = bodyAfter(partner[k + 1], false);
|
|
1169
|
+
if (b)
|
|
1170
|
+
found.push({
|
|
1171
|
+
name: tokens[k].value,
|
|
1172
|
+
nameAt: k,
|
|
1173
|
+
body: b.at,
|
|
1174
|
+
arrow: false,
|
|
1175
|
+
params: k + 1,
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
// An expression body ends at the next `;` or `,` at its depth, or at the
|
|
1180
|
+
// bracket that closes around it: one pass with the open arrows pending
|
|
1181
|
+
// per depth.
|
|
1182
|
+
const stopOf = new Map();
|
|
1183
|
+
const pendingStarts = new Set(found.filter((f) => f.arrow && !punct(f.body, "{")).map((f) => f.body));
|
|
1184
|
+
const pending = [[]];
|
|
1185
|
+
for (let k = 0; k < n; k++) {
|
|
1186
|
+
if (pendingStarts.has(k))
|
|
1187
|
+
pending[pending.length - 1].push(k);
|
|
1188
|
+
const t = tokens[k];
|
|
1189
|
+
if (t.type !== "punctuation")
|
|
1190
|
+
continue;
|
|
1191
|
+
if (t.value === "(" || t.value === "[" || t.value === "{")
|
|
1192
|
+
pending.push([]);
|
|
1193
|
+
else if (t.value === ")" || t.value === "]" || t.value === "}") {
|
|
1194
|
+
if (pending.length > 1) {
|
|
1195
|
+
for (const s of pending.pop())
|
|
1196
|
+
stopOf.set(s, k);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
else if (t.value === ";" || t.value === ",") {
|
|
1200
|
+
for (const s of pending[pending.length - 1])
|
|
1201
|
+
stopOf.set(s, k);
|
|
1202
|
+
pending[pending.length - 1] = [];
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Each parameter's names, by position: `a`, `a = 1` and `...a` give a;
|
|
1207
|
+
* a pattern (`{ icon, t }`) gives every name in it before its type or
|
|
1208
|
+
* default. Types after `:` are left out.
|
|
1209
|
+
*/
|
|
1210
|
+
const parameterNames = (at) => {
|
|
1211
|
+
if (!punct(at, "("))
|
|
1212
|
+
return word(at) ? [[tokens[at].value]] : [];
|
|
1213
|
+
const close = partner[at];
|
|
1214
|
+
const params = [];
|
|
1215
|
+
let current = [];
|
|
1216
|
+
let skipping = false;
|
|
1217
|
+
for (let j = at + 1; j < close; j++) {
|
|
1218
|
+
const t = tokens[j];
|
|
1219
|
+
if (t.type === "punctuation") {
|
|
1220
|
+
if (t.value === ",") {
|
|
1221
|
+
params.push(current);
|
|
1222
|
+
current = [];
|
|
1223
|
+
skipping = false;
|
|
1224
|
+
}
|
|
1225
|
+
else if (t.value === ":" || t.value === "=")
|
|
1226
|
+
skipping = true;
|
|
1227
|
+
else if (t.value === "{" || t.value === "[" || t.value === "(") {
|
|
1228
|
+
if (skipping)
|
|
1229
|
+
j = partner[j] === -1 ? close : partner[j];
|
|
1230
|
+
// A pattern: the names in it, keys (followed by `:`) left out.
|
|
1231
|
+
else if (t.value !== "(")
|
|
1232
|
+
for (let q = j + 1; q < partner[j]; q++)
|
|
1233
|
+
if (tokens[q].type === "identifier" &&
|
|
1234
|
+
!punct(q + 1, ":") &&
|
|
1235
|
+
!punct(q - 1, "."))
|
|
1236
|
+
current.push(tokens[q].value);
|
|
1237
|
+
if (!skipping && partner[j] !== -1)
|
|
1238
|
+
j = partner[j];
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
else if (t.type === "identifier" && !skipping) {
|
|
1242
|
+
if (!METHOD_MODIFIERS.has(t.value) ||
|
|
1243
|
+
punct(j + 1, ",") ||
|
|
1244
|
+
punct(j + 1, ":") ||
|
|
1245
|
+
punct(j + 1, ")"))
|
|
1246
|
+
current.push(t.value);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
if (current.length > 0 || params.length > 0)
|
|
1250
|
+
params.push(current);
|
|
1251
|
+
return params;
|
|
1252
|
+
};
|
|
1253
|
+
return found.map((f) => {
|
|
1254
|
+
const start = tokens[f.nameAt].start;
|
|
1255
|
+
let end;
|
|
1256
|
+
if (punct(f.body, "{")) {
|
|
1257
|
+
const close = partner[f.body];
|
|
1258
|
+
end = close === -1 ? body.length : tokens[close].end;
|
|
1259
|
+
}
|
|
1260
|
+
else {
|
|
1261
|
+
const stop = stopOf.get(f.body);
|
|
1262
|
+
end = stop === undefined ? body.length : tokens[stop].start;
|
|
1263
|
+
}
|
|
1264
|
+
const expression = !punct(f.body, "{");
|
|
1265
|
+
return {
|
|
1266
|
+
name: f.name,
|
|
1267
|
+
start,
|
|
1268
|
+
end,
|
|
1269
|
+
params: parameterNames(f.params),
|
|
1270
|
+
body: f.body < n ? tokens[f.body].start : body.length,
|
|
1271
|
+
expression,
|
|
1272
|
+
};
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* A template that starts like a lint or compiler message: `${file}:${line}: `
|
|
1277
|
+
* or `${file}:${line}:${column}: ` (the parts joined with \u0000 for holes).
|
|
1278
|
+
*/
|
|
1279
|
+
const FILE_LINE_MESSAGE = /^\u0000:\u0000(?::\u0000)?:\s/;
|
|
1280
|
+
/** Words in a callee's name that make it a reporting function. */
|
|
1281
|
+
const MESSAGE_WORDS = new Set("diagnostic diagnostics error errors fail failure finding findings info issue issues lint log logs message messages notice problem problems report warn warning warnings".split(" "));
|
|
1282
|
+
/**
|
|
1283
|
+
* The template literals (by start) passed straight to a function whose
|
|
1284
|
+
* name has a reporting word in it, split at camelCase and `.`: finding(),
|
|
1285
|
+
* addWarning(), ctx.report(), logger.warn(), unless it starts with a tag
|
|
1286
|
+
* and holds an end tag (writeReport("r.html", `<html>...</html>`) saves a
|
|
1287
|
+
* page). The innermost open bracket
|
|
1288
|
+
* around each literal is read in one sweep over the tokens, so a literal
|
|
1289
|
+
* nested in an arrow's body (`items.map((p) => \`...\`)`) belongs to that
|
|
1290
|
+
* call (map) and not to one further out.
|
|
1291
|
+
*/
|
|
1292
|
+
function messageCallArguments(tokens, literals) {
|
|
1293
|
+
const found = new Set();
|
|
1294
|
+
const open = [];
|
|
1295
|
+
let t = 0;
|
|
1296
|
+
for (const literal of literals) {
|
|
1297
|
+
for (; t < tokens.length && tokens[t].start < literal.start; t++) {
|
|
1298
|
+
const token = tokens[t];
|
|
1299
|
+
if (token.type !== "punctuation")
|
|
1300
|
+
continue;
|
|
1301
|
+
if (token.value === "(" || token.value === "[" || token.value === "{")
|
|
1302
|
+
open.push(t);
|
|
1303
|
+
else if ((token.value === ")" || token.value === "]" || token.value === "}") &&
|
|
1304
|
+
open.length > 0)
|
|
1305
|
+
open.pop();
|
|
1306
|
+
}
|
|
1307
|
+
// A whole document or element (`<html>...</html>`) is markup a
|
|
1308
|
+
// report writer saves, not a message that names a tag.
|
|
1309
|
+
if (/^\s*</.test(literal.parts[0]) &&
|
|
1310
|
+
literal.parts.some((p) => p.includes("</")))
|
|
1311
|
+
continue;
|
|
1312
|
+
const paren = open.length > 0 ? open[open.length - 1] : -1;
|
|
1313
|
+
if (paren < 1 || tokens[paren].value !== "(")
|
|
1314
|
+
continue;
|
|
1315
|
+
const callee = tokens[paren - 1];
|
|
1316
|
+
if (callee.type !== "identifier")
|
|
1317
|
+
continue;
|
|
1318
|
+
const words = callee.value
|
|
1319
|
+
.replace(/([a-z\d])([A-Z])/g, "$1 $2")
|
|
1320
|
+
.toLowerCase()
|
|
1321
|
+
.split(/[\s_$]+/);
|
|
1322
|
+
if (words.some((w) => MESSAGE_WORDS.has(w)))
|
|
1323
|
+
found.add(literal.start);
|
|
1324
|
+
}
|
|
1325
|
+
return found;
|
|
1326
|
+
}
|
|
1327
|
+
/** A quoted string that holds a tag, or a lone `<` or `</` that starts one. */
|
|
1328
|
+
const MARKUP_STRING = /<[a-zA-Z!/]|^\s*<\s*$/;
|
|
1329
|
+
/**
|
|
1330
|
+
* The offsets, ascending, where markup built as a string starts: the
|
|
1331
|
+
* markup templates given, and each quoted string that holds a tag (`'<svg
|
|
1332
|
+
* class="ok"></svg>'`, `"<b>"`), messages and search patterns left out.
|
|
1333
|
+
*/
|
|
1334
|
+
function markupSourceStarts(body, tokens, templateStarts) {
|
|
1335
|
+
const starts = [...templateStarts];
|
|
1336
|
+
for (const t of tokens)
|
|
1337
|
+
if (t.type === "string" &&
|
|
1338
|
+
MARKUP_STRING.test(t.value) &&
|
|
1339
|
+
!isMessageArgument(body, t.start - 1) &&
|
|
1340
|
+
!isPatternArgument(body, t.start - 1))
|
|
1341
|
+
starts.push(t.start - 1);
|
|
1342
|
+
return starts.sort((x, y) => x - y);
|
|
1343
|
+
}
|
|
1344
|
+
/** Parameter types that cannot hold markup: number, bigint, boolean and unions of them. */
|
|
1345
|
+
const PLAIN_PARAMETER_TYPE = /^\s*\|?\s*(?:number|bigint|boolean|true|false)(?:\s*\|\s*(?:number|bigint|boolean|true|false))*\s*$/;
|
|
1346
|
+
/** Words before a class member's or parameter's name that are not its name. */
|
|
1347
|
+
const MEMBER_MODIFIERS = new Set([
|
|
1348
|
+
"async",
|
|
1349
|
+
"static",
|
|
1350
|
+
"get",
|
|
1351
|
+
"set",
|
|
1352
|
+
"public",
|
|
1353
|
+
"private",
|
|
1354
|
+
"protected",
|
|
1355
|
+
"override",
|
|
1356
|
+
"readonly",
|
|
1357
|
+
"abstract",
|
|
1358
|
+
"declare",
|
|
1359
|
+
"accessor",
|
|
1360
|
+
]);
|
|
1361
|
+
/**
|
|
1362
|
+
* The names of the parameter list at token `at` (a `(`, or the lone
|
|
1363
|
+
* parameter of `x => ...`) that may hold markup: every name, patterns and
|
|
1364
|
+
* rest parameters included, except those whose declared type is number,
|
|
1365
|
+
* bigint or boolean (or a union of those). `partner` maps each bracket to
|
|
1366
|
+
* its partner.
|
|
1367
|
+
*/
|
|
1368
|
+
function possiblyMarkupParameters(body, tokens, partner, at) {
|
|
1369
|
+
const n = tokens.length;
|
|
1370
|
+
const punct = (k, v) => k >= 0 &&
|
|
1371
|
+
k < n &&
|
|
1372
|
+
tokens[k].type === "punctuation" &&
|
|
1373
|
+
tokens[k].value === v;
|
|
1374
|
+
const word = (k) => k >= 0 && k < n && tokens[k].type === "identifier";
|
|
1375
|
+
if (!punct(at, "(")) {
|
|
1376
|
+
return word(at) ? [tokens[at].value] : [];
|
|
1377
|
+
}
|
|
1378
|
+
const close = partner[at];
|
|
1379
|
+
if (close === -1)
|
|
1380
|
+
return [];
|
|
1381
|
+
const out = [];
|
|
1382
|
+
let names = [];
|
|
1383
|
+
let typeFrom = -1;
|
|
1384
|
+
let typeTo = -1;
|
|
1385
|
+
const finish = () => {
|
|
1386
|
+
const type = typeFrom !== -1 && typeTo >= typeFrom
|
|
1387
|
+
? body.slice(tokens[typeFrom].start, tokens[typeTo].end)
|
|
1388
|
+
: undefined;
|
|
1389
|
+
if (type === undefined || !PLAIN_PARAMETER_TYPE.test(type))
|
|
1390
|
+
for (const name of names)
|
|
1391
|
+
if (name !== "this")
|
|
1392
|
+
out.push(name);
|
|
1393
|
+
names = [];
|
|
1394
|
+
typeFrom = typeTo = -1;
|
|
1395
|
+
};
|
|
1396
|
+
// 0: the name or pattern, 1: the type, 2: the default value.
|
|
1397
|
+
let part = 0;
|
|
1398
|
+
for (let j = at + 1; j < close; j++) {
|
|
1399
|
+
const t = tokens[j];
|
|
1400
|
+
if (t.type === "punctuation") {
|
|
1401
|
+
if (t.value === ",") {
|
|
1402
|
+
finish();
|
|
1403
|
+
part = 0;
|
|
1404
|
+
continue;
|
|
1405
|
+
}
|
|
1406
|
+
if (part === 0 && t.value === ":") {
|
|
1407
|
+
part = 1;
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (part !== 2 && t.value === "=" && !punct(j + 1, ">")) {
|
|
1411
|
+
part = 2;
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
if (t.value === "(" || t.value === "[" || t.value === "{") {
|
|
1415
|
+
const end = partner[j] === -1 ? close : partner[j];
|
|
1416
|
+
if (part === 0)
|
|
1417
|
+
for (let q = j + 1; q < end; q++)
|
|
1418
|
+
if (tokens[q].type === "identifier" &&
|
|
1419
|
+
!punct(q + 1, ":") &&
|
|
1420
|
+
!punct(q - 1, "."))
|
|
1421
|
+
names.push(tokens[q].value);
|
|
1422
|
+
if (part === 1) {
|
|
1423
|
+
if (typeFrom === -1)
|
|
1424
|
+
typeFrom = j;
|
|
1425
|
+
typeTo = end;
|
|
1426
|
+
}
|
|
1427
|
+
j = end;
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
if (part === 0 && t.type === "identifier") {
|
|
1432
|
+
if (!MEMBER_MODIFIERS.has(t.value) ||
|
|
1433
|
+
punct(j + 1, ",") ||
|
|
1434
|
+
punct(j + 1, ":") ||
|
|
1435
|
+
punct(j + 1, "?") ||
|
|
1436
|
+
punct(j + 1, "=") ||
|
|
1437
|
+
j + 1 === close)
|
|
1438
|
+
names.push(t.value);
|
|
1439
|
+
}
|
|
1440
|
+
else if (part === 1 && !(t.type === "punctuation" && t.value === "?")) {
|
|
1441
|
+
if (typeFrom === -1)
|
|
1442
|
+
typeFrom = j;
|
|
1443
|
+
typeTo = j;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
finish();
|
|
1447
|
+
return out;
|
|
1448
|
+
}
|
|
1449
|
+
/** How a message names the function a parameter belongs to. */
|
|
1450
|
+
function ownerLabel(path) {
|
|
1451
|
+
if (path === "default")
|
|
1452
|
+
return "the default export";
|
|
1453
|
+
const constructor = /^(.*)\.constructor$/.exec(path);
|
|
1454
|
+
if (constructor)
|
|
1455
|
+
return `new ${ownerLabel(constructor[1]).replace(/\(\)$/, "")}()`;
|
|
1456
|
+
if (path.startsWith("default."))
|
|
1457
|
+
return `the default export's ${path.slice(8)}()`;
|
|
1458
|
+
return `${path}()`;
|
|
1459
|
+
}
|
|
1460
|
+
/** The owner of a parameter named `name` read at `offset`: the nearest function before it with such a parameter. */
|
|
1461
|
+
function reachableOwnerAt(owners, name, offset) {
|
|
1462
|
+
// Each list is sorted by `at`, so a binary search finds it.
|
|
1463
|
+
const list = owners.get(name);
|
|
1464
|
+
if (list === undefined || list.length === 0)
|
|
1465
|
+
return undefined;
|
|
1466
|
+
let lo = 0;
|
|
1467
|
+
let hi = list.length - 1;
|
|
1468
|
+
if (list[0].at > offset)
|
|
1469
|
+
return list[0];
|
|
1470
|
+
while (lo < hi) {
|
|
1471
|
+
const mid = (lo + hi + 1) >> 1;
|
|
1472
|
+
if (list[mid].at <= offset)
|
|
1473
|
+
lo = mid;
|
|
1474
|
+
else
|
|
1475
|
+
hi = mid - 1;
|
|
1476
|
+
}
|
|
1477
|
+
return list[lo];
|
|
1478
|
+
}
|
|
1479
|
+
/** How a message says where a parameter's value comes from and why html may escape it. */
|
|
1480
|
+
function callerClause(name, owner) {
|
|
1481
|
+
switch (owner?.kind) {
|
|
1482
|
+
case "this":
|
|
1483
|
+
return "this, whose fields a constructor or method may have filled from a caller's arguments: the value may be markup from a caller";
|
|
1484
|
+
case "arguments":
|
|
1485
|
+
return "arguments, which holds what the function's callers pass: the value may be markup from a caller";
|
|
1486
|
+
case "unseen":
|
|
1487
|
+
return `${name}, a parameter of ${owner.label}, whose callers this file cannot all see (a callback, a method, or a function passed on or returned): the value may be markup from a caller`;
|
|
1488
|
+
default:
|
|
1489
|
+
return `${name}, a parameter of ${owner?.label ?? "a function"}, which other modules can call: the value may be markup from a caller`;
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* The parameters of everything this module lets other modules call, each
|
|
1494
|
+
* with the functions it belongs to and how a message names them: exported functions (named, or a
|
|
1495
|
+
* default export named or anonymous), every method and constructor of an
|
|
1496
|
+
* exported class, the methods and function members of an exported object
|
|
1497
|
+
* (nested objects too), local functions exported by name or named in an
|
|
1498
|
+
* exported object, and the same through module.exports and exports.x.
|
|
1499
|
+
* Another module may pass any of them markup, so they count as possibly
|
|
1500
|
+
* markup, except a parameter whose declared type is number, bigint or
|
|
1501
|
+
* boolean (or a union of those). Each declaration is read once, so the
|
|
1502
|
+
* pass stays linear in the tokens.
|
|
1503
|
+
*/
|
|
1504
|
+
export function exportReachableParameters(body, tokens = scanJavaScript(body).tokens) {
|
|
1505
|
+
const out = new Map();
|
|
1506
|
+
const n = tokens.length;
|
|
1507
|
+
/** Records that `name` is a parameter of the function whose list starts at token `at`. */
|
|
1508
|
+
const own = (name, at, label) => {
|
|
1509
|
+
const list = out.get(name) ?? [];
|
|
1510
|
+
list.push({ at: tokens[at].start, label, kind: "exported" });
|
|
1511
|
+
out.set(name, list);
|
|
1512
|
+
};
|
|
1513
|
+
const punct = (k, v) => k >= 0 &&
|
|
1514
|
+
k < n &&
|
|
1515
|
+
tokens[k].type === "punctuation" &&
|
|
1516
|
+
tokens[k].value === v;
|
|
1517
|
+
const word = (k, v) => k >= 0 &&
|
|
1518
|
+
k < n &&
|
|
1519
|
+
tokens[k].type === "identifier" &&
|
|
1520
|
+
(v === undefined || tokens[k].value === v);
|
|
1521
|
+
const partner = new Int32Array(n).fill(-1);
|
|
1522
|
+
const stack = [];
|
|
1523
|
+
for (let k = 0; k < n; k++) {
|
|
1524
|
+
const t = tokens[k];
|
|
1525
|
+
if (t.type !== "punctuation")
|
|
1526
|
+
continue;
|
|
1527
|
+
if (t.value === "(" || t.value === "[" || t.value === "{")
|
|
1528
|
+
stack.push(k);
|
|
1529
|
+
else if ((t.value === ")" || t.value === "]" || t.value === "}") &&
|
|
1530
|
+
stack.length > 0) {
|
|
1531
|
+
const o = stack.pop();
|
|
1532
|
+
partner[o] = k;
|
|
1533
|
+
partner[k] = o;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
/** After `const|let|var NAME` at `k`: the token after its `=`, past a type annotation; -1 when there is none. */
|
|
1537
|
+
const initializerAfter = (k) => {
|
|
1538
|
+
let j = k + 1;
|
|
1539
|
+
if (!punct(j, ":"))
|
|
1540
|
+
return punct(j, "=") && !punct(j + 1, "=") ? j + 1 : -1;
|
|
1541
|
+
for (let angle = 0; j < n && j <= k + 200; j++) {
|
|
1542
|
+
if (tokens[j].type !== "punctuation")
|
|
1543
|
+
continue;
|
|
1544
|
+
const v = tokens[j].value;
|
|
1545
|
+
if (v === "(" || v === "[" || v === "{") {
|
|
1546
|
+
if (partner[j] === -1)
|
|
1547
|
+
return -1;
|
|
1548
|
+
j = partner[j];
|
|
1549
|
+
}
|
|
1550
|
+
else if (v === "<")
|
|
1551
|
+
angle++;
|
|
1552
|
+
else if (v === ">")
|
|
1553
|
+
angle = Math.max(0, angle - 1);
|
|
1554
|
+
else if (v === "=" && !punct(j - 1, "=")) {
|
|
1555
|
+
if (punct(j + 1, ">"))
|
|
1556
|
+
j++;
|
|
1557
|
+
else if (punct(j + 1, "="))
|
|
1558
|
+
return -1;
|
|
1559
|
+
else if (angle === 0)
|
|
1560
|
+
return j + 1;
|
|
1561
|
+
}
|
|
1562
|
+
else if (v === ";" || v === ")" || v === "]" || v === "}")
|
|
1563
|
+
return -1;
|
|
1564
|
+
}
|
|
1565
|
+
return -1;
|
|
1566
|
+
};
|
|
1567
|
+
// Where each name is declared: function NAME, class NAME, NAME = value.
|
|
1568
|
+
const declarations = new Map();
|
|
1569
|
+
const declare = (name, at) => {
|
|
1570
|
+
const list = declarations.get(name) ?? [];
|
|
1571
|
+
list.push(at);
|
|
1572
|
+
declarations.set(name, list);
|
|
1573
|
+
};
|
|
1574
|
+
for (let k = 0; k + 1 < n; k++) {
|
|
1575
|
+
if ((word(k, "function") || word(k, "class")) && word(k + 1))
|
|
1576
|
+
declare(tokens[k + 1].value, k);
|
|
1577
|
+
else if ((word(k - 1, "const") || word(k - 1, "let") || word(k - 1, "var")) &&
|
|
1578
|
+
word(k)) {
|
|
1579
|
+
const v = initializerAfter(k);
|
|
1580
|
+
if (v !== -1 && v < n)
|
|
1581
|
+
declare(tokens[k].value, v);
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
/** Records the parameters of the list at `at` (a `(`, or the lone parameter of `x => ...`). */
|
|
1585
|
+
const addParameters = (at, path) => {
|
|
1586
|
+
const label = ownerLabel(path);
|
|
1587
|
+
for (const name of possiblyMarkupParameters(body, tokens, partner, at))
|
|
1588
|
+
own(name, at, label);
|
|
1589
|
+
};
|
|
1590
|
+
const visited = new Set();
|
|
1591
|
+
/** The members of the class or object whose `{` is at `open`. */
|
|
1592
|
+
const members = (open, base, isClass) => {
|
|
1593
|
+
const close = partner[open];
|
|
1594
|
+
if (close === -1)
|
|
1595
|
+
return;
|
|
1596
|
+
for (let j = open + 1; j < close; j++) {
|
|
1597
|
+
const t = tokens[j];
|
|
1598
|
+
if (t.type === "punctuation" &&
|
|
1599
|
+
(t.value === "(" || t.value === "[" || t.value === "{")) {
|
|
1600
|
+
// A method: KEY(...) {, its key an identifier, a string or [computed].
|
|
1601
|
+
if (t.value === "(" && partner[j] !== -1) {
|
|
1602
|
+
const k = j - 1;
|
|
1603
|
+
const keyed = (word(k) || tokens[k]?.type === "string" || punct(k, "]")) &&
|
|
1604
|
+
!punct(k - 1, ".");
|
|
1605
|
+
const after = partner[j] + 1;
|
|
1606
|
+
if (keyed &&
|
|
1607
|
+
(punct(after, "{") || punct(after, ":")) &&
|
|
1608
|
+
!(word(k) && CONTROL_WORDS.has(tokens[k].value))) {
|
|
1609
|
+
const key = tokens[k].type === "punctuation" ? "[computed]" : tokens[k].value;
|
|
1610
|
+
addParameters(j, `${base}.${key}`);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
if (partner[j] !== -1)
|
|
1614
|
+
j = partner[j];
|
|
1615
|
+
continue;
|
|
1616
|
+
}
|
|
1617
|
+
// KEY: value (objects) and KEY = value (class fields).
|
|
1618
|
+
const valueSign = isClass
|
|
1619
|
+
? punct(j, "=") &&
|
|
1620
|
+
!punct(j + 1, "=") &&
|
|
1621
|
+
!punct(j + 1, ">") &&
|
|
1622
|
+
!punct(j - 1, "=") &&
|
|
1623
|
+
!punct(j - 1, "!") &&
|
|
1624
|
+
!punct(j - 1, "<") &&
|
|
1625
|
+
!punct(j - 1, ">")
|
|
1626
|
+
: punct(j, ":");
|
|
1627
|
+
if (valueSign) {
|
|
1628
|
+
let k = j - 1;
|
|
1629
|
+
if (isClass) {
|
|
1630
|
+
// Back past a type annotation to the field's name.
|
|
1631
|
+
while (k > open &&
|
|
1632
|
+
k > j - 64 &&
|
|
1633
|
+
!((word(k) || tokens[k].type === "string") &&
|
|
1634
|
+
(punct(k - 1, ";") ||
|
|
1635
|
+
punct(k - 1, "}") ||
|
|
1636
|
+
punct(k - 1, "{") ||
|
|
1637
|
+
punct(k + 1, ":") ||
|
|
1638
|
+
punct(k + 1, "?") ||
|
|
1639
|
+
punct(k + 1, "!") ||
|
|
1640
|
+
punct(k + 1, "="))))
|
|
1641
|
+
k--;
|
|
1642
|
+
}
|
|
1643
|
+
const key = k > open && k > j - 64 ? tokens[k].value : "[computed]";
|
|
1644
|
+
collect(j + 1, `${base}.${key}`);
|
|
1645
|
+
continue;
|
|
1646
|
+
}
|
|
1647
|
+
if (!isClass && word(j)) {
|
|
1648
|
+
// { page } and { ...parts }: a local name, read like its declaration.
|
|
1649
|
+
if ((punct(j - 1, "{") || punct(j - 1, ",") || punct(j - 1, ".")) &&
|
|
1650
|
+
(punct(j + 1, ",") || j + 1 === close))
|
|
1651
|
+
resolve(tokens[j].value, `${base}.${tokens[j].value}`);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
};
|
|
1655
|
+
/** A local name another module can reach: what its declarations hold. */
|
|
1656
|
+
const resolved = new Set();
|
|
1657
|
+
const resolve = (name, path) => {
|
|
1658
|
+
// Each name once: its declarations are the same whoever names it.
|
|
1659
|
+
if (resolved.has(name))
|
|
1660
|
+
return;
|
|
1661
|
+
resolved.add(name);
|
|
1662
|
+
for (const at of declarations.get(name) ?? [])
|
|
1663
|
+
collect(at, path);
|
|
1664
|
+
};
|
|
1665
|
+
// Values still to read, as a queue, so a long alias chain cannot
|
|
1666
|
+
// overflow the call stack.
|
|
1667
|
+
const work = [];
|
|
1668
|
+
/** Queues the value that starts at token `v`, which another module can reach as `path`. */
|
|
1669
|
+
const collect = (v, path) => {
|
|
1670
|
+
if (v < 0 || v >= n || visited.has(v))
|
|
1671
|
+
return;
|
|
1672
|
+
visited.add(v);
|
|
1673
|
+
work.push({ at: v, path });
|
|
1674
|
+
};
|
|
1675
|
+
/** Reads one queued value. */
|
|
1676
|
+
const read = (v, path) => {
|
|
1677
|
+
// A token in a template's hole is not the value itself.
|
|
1678
|
+
if (v > 0 && body.slice(tokens[v - 1].end, tokens[v].start).includes("`"))
|
|
1679
|
+
return;
|
|
1680
|
+
let k = v;
|
|
1681
|
+
while (word(k, "async"))
|
|
1682
|
+
k++;
|
|
1683
|
+
if (word(k, "function")) {
|
|
1684
|
+
let j = k + 1;
|
|
1685
|
+
if (punct(j, "*"))
|
|
1686
|
+
j++;
|
|
1687
|
+
if (word(j))
|
|
1688
|
+
j++;
|
|
1689
|
+
if (punct(j, "("))
|
|
1690
|
+
addParameters(j, path);
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
if (word(k, "class")) {
|
|
1694
|
+
let j = k + 1;
|
|
1695
|
+
if (word(j) && !word(j, "extends"))
|
|
1696
|
+
j++;
|
|
1697
|
+
for (; j < n && j <= k + 400 && !punct(j, "{"); j++) {
|
|
1698
|
+
if (punct(j, ";") || punct(j, "}"))
|
|
1699
|
+
return;
|
|
1700
|
+
if ((punct(j, "(") || punct(j, "[")) && partner[j] !== -1)
|
|
1701
|
+
j = partner[j];
|
|
1702
|
+
}
|
|
1703
|
+
if (punct(j, "{"))
|
|
1704
|
+
members(j, path, true);
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
if (punct(k, "(") && partner[k] !== -1) {
|
|
1708
|
+
// An arrow's parameter list, past a short return type.
|
|
1709
|
+
for (let j = partner[k] + 1; j < n && j <= partner[k] + 24; j++) {
|
|
1710
|
+
if (punct(j, "=") && punct(j + 1, ">")) {
|
|
1711
|
+
addParameters(k, path);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
if (punct(j, ";") || punct(j, "{") || punct(j, ",") || punct(j, ")"))
|
|
1715
|
+
break;
|
|
1716
|
+
}
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
if (word(k) && punct(k + 1, "=") && punct(k + 2, ">")) {
|
|
1720
|
+
addParameters(k, path);
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
if (punct(k, "{")) {
|
|
1724
|
+
members(k, path, false);
|
|
1725
|
+
return;
|
|
1726
|
+
}
|
|
1727
|
+
// A name: export default frame, export const lib = lg.
|
|
1728
|
+
if (word(k) &&
|
|
1729
|
+
!punct(k + 1, "(") &&
|
|
1730
|
+
!punct(k + 1, ".") &&
|
|
1731
|
+
!punct(k + 1, "["))
|
|
1732
|
+
resolve(tokens[k].value, path);
|
|
1733
|
+
};
|
|
1734
|
+
for (let k = 0; k < n; k++) {
|
|
1735
|
+
if (word(k, "export") && !punct(k - 1, ".")) {
|
|
1736
|
+
let j = k + 1;
|
|
1737
|
+
if (word(j, "default")) {
|
|
1738
|
+
let f = j + 1;
|
|
1739
|
+
while (word(f, "async"))
|
|
1740
|
+
f++;
|
|
1741
|
+
// export default function name / class name: messages name it.
|
|
1742
|
+
const named = (word(f, "function") || word(f, "class")) &&
|
|
1743
|
+
word(f + 1) &&
|
|
1744
|
+
!word(f + 1, "extends")
|
|
1745
|
+
? tokens[f + 1].value
|
|
1746
|
+
: undefined;
|
|
1747
|
+
collect(j + 1, named ?? "default");
|
|
1748
|
+
continue;
|
|
1749
|
+
}
|
|
1750
|
+
if (punct(j, "=")) {
|
|
1751
|
+
collect(j + 1, "default");
|
|
1752
|
+
continue;
|
|
1753
|
+
}
|
|
1754
|
+
while (word(j, "declare") || word(j, "abstract"))
|
|
1755
|
+
j++;
|
|
1756
|
+
let f = j;
|
|
1757
|
+
while (word(f, "async"))
|
|
1758
|
+
f++;
|
|
1759
|
+
if ((word(f, "function") || word(f, "class")) && word(f + 1)) {
|
|
1760
|
+
collect(j, tokens[f + 1].value);
|
|
1761
|
+
continue;
|
|
1762
|
+
}
|
|
1763
|
+
if ((word(j, "const") || word(j, "let") || word(j, "var")) &&
|
|
1764
|
+
word(j + 1)) {
|
|
1765
|
+
const v = initializerAfter(j + 1);
|
|
1766
|
+
if (v !== -1)
|
|
1767
|
+
collect(v, tokens[j + 1].value);
|
|
1768
|
+
continue;
|
|
1769
|
+
}
|
|
1770
|
+
if (punct(j, "{") && partner[j] !== -1) {
|
|
1771
|
+
const close = partner[j];
|
|
1772
|
+
if (word(close + 1, "from"))
|
|
1773
|
+
continue;
|
|
1774
|
+
for (let q = j + 1; q < close; q++) {
|
|
1775
|
+
if (!word(q) || word(q, "type") || word(q, "as"))
|
|
1776
|
+
continue;
|
|
1777
|
+
if (!(punct(q - 1, "{") || punct(q - 1, ",") || word(q - 1, "type")))
|
|
1778
|
+
continue;
|
|
1779
|
+
const exported = word(q + 1, "as") && word(q + 2)
|
|
1780
|
+
? tokens[q + 2].value
|
|
1781
|
+
: tokens[q].value;
|
|
1782
|
+
resolve(tokens[q].value, exported);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
// module.exports = ..., module.exports.page = ..., exports.page = ...
|
|
1788
|
+
if (word(k, "exports") && !punct(k - 1, ".")) {
|
|
1789
|
+
if (punct(k + 1, ".") &&
|
|
1790
|
+
word(k + 2) &&
|
|
1791
|
+
punct(k + 3, "=") &&
|
|
1792
|
+
!punct(k + 4, "="))
|
|
1793
|
+
collect(k + 4, tokens[k + 2].value);
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
if (word(k, "module") &&
|
|
1797
|
+
!punct(k - 1, ".") &&
|
|
1798
|
+
punct(k + 1, ".") &&
|
|
1799
|
+
word(k + 2, "exports")) {
|
|
1800
|
+
if (punct(k + 3, "=") && !punct(k + 4, "="))
|
|
1801
|
+
collect(k + 4, "default");
|
|
1802
|
+
else if (punct(k + 3, ".") &&
|
|
1803
|
+
word(k + 4) &&
|
|
1804
|
+
punct(k + 5, "=") &&
|
|
1805
|
+
!punct(k + 6, "="))
|
|
1806
|
+
collect(k + 6, tokens[k + 4].value);
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
for (let w = 0; w < work.length; w++)
|
|
1810
|
+
read(work[w].at, work[w].path);
|
|
1811
|
+
return out;
|
|
1812
|
+
}
|
|
1813
|
+
/**
|
|
1814
|
+
* The parameters in a module whose callers this file cannot all see, with
|
|
1815
|
+
* the functions they belong to: every callback and function expression,
|
|
1816
|
+
* every method and constructor, generators, and named functions that are
|
|
1817
|
+
* exported or used as a value (returned, passed, stored, wrapped) rather
|
|
1818
|
+
* than only called by name. A local function declared with `function` or
|
|
1819
|
+
* bound to a `const`, `let` or `var`, and only ever called by name, is left
|
|
1820
|
+
* out: its parameters hold what those calls pass, which markupProducers
|
|
1821
|
+
* follows. Types count as for exported functions: a number, bigint or
|
|
1822
|
+
* boolean parameter is plain data. `this` and `arguments` are included as
|
|
1823
|
+
* well, since callers fill them. One pass over the tokens, each lookback
|
|
1824
|
+
* bounded, so the pass stays linear.
|
|
1825
|
+
*/
|
|
1826
|
+
export function unseenCallerParameters(body, tokens = scanJavaScript(body).tokens) {
|
|
1827
|
+
const n = tokens.length;
|
|
1828
|
+
const punct = (k, v) => k >= 0 &&
|
|
1829
|
+
k < n &&
|
|
1830
|
+
tokens[k].type === "punctuation" &&
|
|
1831
|
+
tokens[k].value === v;
|
|
1832
|
+
const word = (k, v) => k >= 0 &&
|
|
1833
|
+
k < n &&
|
|
1834
|
+
tokens[k].type === "identifier" &&
|
|
1835
|
+
(v === undefined || tokens[k].value === v);
|
|
1836
|
+
const partner = new Int32Array(n).fill(-1);
|
|
1837
|
+
// The innermost bracket each token is in.
|
|
1838
|
+
const enclosing = new Int32Array(n).fill(-1);
|
|
1839
|
+
const stack = [];
|
|
1840
|
+
for (let k = 0; k < n; k++) {
|
|
1841
|
+
const t = tokens[k];
|
|
1842
|
+
if (stack.length > 0)
|
|
1843
|
+
enclosing[k] = stack[stack.length - 1];
|
|
1844
|
+
if (t.type !== "punctuation")
|
|
1845
|
+
continue;
|
|
1846
|
+
if (t.value === "(" || t.value === "[" || t.value === "{")
|
|
1847
|
+
stack.push(k);
|
|
1848
|
+
else if ((t.value === ")" || t.value === "]" || t.value === "}") &&
|
|
1849
|
+
stack.length > 0) {
|
|
1850
|
+
const o = stack.pop();
|
|
1851
|
+
partner[o] = k;
|
|
1852
|
+
partner[k] = o;
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
const declarationKeyword = (k) => word(k, "const") || word(k, "let") || word(k, "var");
|
|
1856
|
+
// Names used other than as a direct call or their own declaration: a
|
|
1857
|
+
// function named this way may be called where this file cannot see.
|
|
1858
|
+
const usedAsValue = new Set();
|
|
1859
|
+
for (let k = 0; k < n; k++) {
|
|
1860
|
+
if (!word(k) || punct(k - 1, ".") || punct(k - 1, "#"))
|
|
1861
|
+
continue;
|
|
1862
|
+
const name = tokens[k].value;
|
|
1863
|
+
// A key: { name: value }.
|
|
1864
|
+
if (punct(k + 1, ":") && (punct(k - 1, "{") || punct(k - 1, ",")))
|
|
1865
|
+
continue;
|
|
1866
|
+
const isFunctionName = word(k - 1, "function") || (punct(k - 1, "*") && word(k - 2, "function"));
|
|
1867
|
+
if (isFunctionName || declarationKeyword(k - 1)) {
|
|
1868
|
+
let b = isFunctionName ? (word(k - 1) ? k - 2 : k - 3) : k - 2;
|
|
1869
|
+
while (word(b, "async"))
|
|
1870
|
+
b--;
|
|
1871
|
+
if (word(b, "export") || word(b, "default"))
|
|
1872
|
+
usedAsValue.add(name);
|
|
1873
|
+
continue;
|
|
1874
|
+
}
|
|
1875
|
+
if (!punct(k + 1, "("))
|
|
1876
|
+
usedAsValue.add(name);
|
|
1877
|
+
}
|
|
1878
|
+
/** Before a function head ending at token `j`: the `NAME` of `const|let|var NAME =`, if any. */
|
|
1879
|
+
const boundName = (j) => {
|
|
1880
|
+
while (word(j, "async"))
|
|
1881
|
+
j--;
|
|
1882
|
+
if (!punct(j, "=") || punct(j - 1, "="))
|
|
1883
|
+
return undefined;
|
|
1884
|
+
if (word(j - 1) && declarationKeyword(j - 2))
|
|
1885
|
+
return tokens[j - 1].value;
|
|
1886
|
+
// const NAME: Type = ...: back past the annotation.
|
|
1887
|
+
for (let q = j - 1; q >= 0 && q > j - 64; q--) {
|
|
1888
|
+
if ((punct(q, ")") || punct(q, "]") || punct(q, "}")) &&
|
|
1889
|
+
partner[q] !== -1)
|
|
1890
|
+
q = partner[q];
|
|
1891
|
+
else if (punct(q, ":"))
|
|
1892
|
+
return word(q - 1) && declarationKeyword(q - 2)
|
|
1893
|
+
? tokens[q - 1].value
|
|
1894
|
+
: undefined;
|
|
1895
|
+
else if (punct(q, ";") ||
|
|
1896
|
+
punct(q, "{") ||
|
|
1897
|
+
(punct(q, "=") && !punct(q + 1, ">")))
|
|
1898
|
+
break;
|
|
1899
|
+
}
|
|
1900
|
+
return undefined;
|
|
1901
|
+
};
|
|
1902
|
+
/**
|
|
1903
|
+
* Whether the parameter list whose head ends at token `head` is a
|
|
1904
|
+
* function type in an annotation, not a function: `const f: (s: string)
|
|
1905
|
+
* => string`, `(): (s: string) => string`, `(render: () => string)`.
|
|
1906
|
+
*/
|
|
1907
|
+
const inAnnotation = (head) => {
|
|
1908
|
+
if (!punct(head, ":"))
|
|
1909
|
+
return false;
|
|
1910
|
+
if (punct(head - 1, ")"))
|
|
1911
|
+
return true;
|
|
1912
|
+
let name = head - 1;
|
|
1913
|
+
if (punct(name, "?"))
|
|
1914
|
+
name--;
|
|
1915
|
+
if (!word(name))
|
|
1916
|
+
return false;
|
|
1917
|
+
if (declarationKeyword(name - 1))
|
|
1918
|
+
return true;
|
|
1919
|
+
return ((punct(name - 1, "(") || punct(name - 1, ",")) &&
|
|
1920
|
+
enclosing[head] !== -1 &&
|
|
1921
|
+
punct(enclosing[head], "("));
|
|
1922
|
+
};
|
|
1923
|
+
/** The token before a parameter list at `k`, past type parameters (`<T>`). */
|
|
1924
|
+
const beforeHead = (k) => {
|
|
1925
|
+
let j = k - 1;
|
|
1926
|
+
if (!punct(j, ">"))
|
|
1927
|
+
return j;
|
|
1928
|
+
for (let depth = 0; j >= 0 && j >= k - 64; j--) {
|
|
1929
|
+
if (punct(j, ">"))
|
|
1930
|
+
depth++;
|
|
1931
|
+
else if (punct(j, "<") && --depth === 0)
|
|
1932
|
+
return j - 1;
|
|
1933
|
+
}
|
|
1934
|
+
return k - 1;
|
|
1935
|
+
};
|
|
1936
|
+
/** After a parameter list's `)` at `close`: the token past a return type (`: string`, `: { a: string }`). */
|
|
1937
|
+
const pastReturnType = (close) => {
|
|
1938
|
+
let j = close + 1;
|
|
1939
|
+
if (!punct(j, ":"))
|
|
1940
|
+
return j;
|
|
1941
|
+
for (j++; j < n && j <= close + 64; j++) {
|
|
1942
|
+
if (punct(j, "=") && punct(j + 1, ">"))
|
|
1943
|
+
return j;
|
|
1944
|
+
if (punct(j, "{") && !punct(j - 1, ":") && !punct(j - 1, "|"))
|
|
1945
|
+
return j;
|
|
1946
|
+
if ((punct(j, "(") || punct(j, "[") || punct(j, "{")) && partner[j] > j)
|
|
1947
|
+
j = partner[j];
|
|
1948
|
+
else if (punct(j, ";") || punct(j, ",") || punct(j, ")"))
|
|
1949
|
+
return j;
|
|
1950
|
+
}
|
|
1951
|
+
return j;
|
|
1952
|
+
};
|
|
1953
|
+
const isArrow = (j) => punct(j, "=") && punct(j + 1, ">");
|
|
1954
|
+
const out = new Map();
|
|
1955
|
+
const add = (at, label) => {
|
|
1956
|
+
for (const name of possiblyMarkupParameters(body, tokens, partner, at)) {
|
|
1957
|
+
const list = out.get(name) ?? [];
|
|
1958
|
+
list.push({ at: tokens[at].start, label, kind: "unseen" });
|
|
1959
|
+
out.set(name, list);
|
|
1960
|
+
}
|
|
1961
|
+
};
|
|
1962
|
+
/** Whether a function bound or declared as `name` is only ever called by name. */
|
|
1963
|
+
const onlyCalled = (name) => name !== undefined && !usedAsValue.has(name);
|
|
1964
|
+
/** The parameter lists of `function` heads, read with their head. */
|
|
1965
|
+
const functionLists = new Set();
|
|
1966
|
+
for (let k = 0; k < n; k++) {
|
|
1967
|
+
if (word(k, "function") && !punct(k - 1, ".")) {
|
|
1968
|
+
let j = k + 1;
|
|
1969
|
+
if (punct(j, "*"))
|
|
1970
|
+
j++;
|
|
1971
|
+
const generator = j > k + 1;
|
|
1972
|
+
const name = word(j) ? tokens[j++].value : undefined;
|
|
1973
|
+
if (punct(j, "<"))
|
|
1974
|
+
for (let depth = 0, q = j; q < n && q <= j + 64; q++) {
|
|
1975
|
+
if (punct(q, "<"))
|
|
1976
|
+
depth++;
|
|
1977
|
+
else if (punct(q, ">") && --depth === 0) {
|
|
1978
|
+
j = q + 1;
|
|
1979
|
+
break;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
if (!punct(j, "("))
|
|
1983
|
+
continue;
|
|
1984
|
+
functionLists.add(j);
|
|
1985
|
+
const bound = boundName(k - 1);
|
|
1986
|
+
let b = k - 1;
|
|
1987
|
+
while (word(b, "async"))
|
|
1988
|
+
b--;
|
|
1989
|
+
const statement = b < 0 || punct(b, ";") || punct(b, "{") || punct(b, "}");
|
|
1990
|
+
const owner = bound ?? (statement ? name : undefined);
|
|
1991
|
+
if (!generator && onlyCalled(owner))
|
|
1992
|
+
continue;
|
|
1993
|
+
add(j, (owner ?? name) ? `${owner ?? name}()` : "a callback");
|
|
1994
|
+
continue;
|
|
1995
|
+
}
|
|
1996
|
+
if (punct(k, "(") && partner[k] > k && !functionLists.has(k)) {
|
|
1997
|
+
const after = pastReturnType(partner[k]);
|
|
1998
|
+
const head = beforeHead(k);
|
|
1999
|
+
if (isArrow(after)) {
|
|
2000
|
+
if (inAnnotation(head))
|
|
2001
|
+
continue;
|
|
2002
|
+
const bound = boundName(head);
|
|
2003
|
+
if (onlyCalled(bound))
|
|
2004
|
+
continue;
|
|
2005
|
+
add(k, bound ? `${bound}()` : "a callback");
|
|
2006
|
+
continue;
|
|
2007
|
+
}
|
|
2008
|
+
// A method: KEY(...) {, its key a name, a string, #name or [computed].
|
|
2009
|
+
if (punct(after, "{") &&
|
|
2010
|
+
((word(head) && !CONTROL_WORDS.has(tokens[head].value)) ||
|
|
2011
|
+
tokens[head]?.type === "string" ||
|
|
2012
|
+
punct(head, "]")) &&
|
|
2013
|
+
!punct(head - 1, ".")) {
|
|
2014
|
+
add(k, word(head) ? `${tokens[head].value}()` : "a method");
|
|
2015
|
+
continue;
|
|
2016
|
+
}
|
|
2017
|
+
continue;
|
|
2018
|
+
}
|
|
2019
|
+
if (word(k) && isArrow(k + 1) && !punct(k - 1, ".")) {
|
|
2020
|
+
const bound = boundName(k - 1);
|
|
2021
|
+
if (onlyCalled(bound))
|
|
2022
|
+
continue;
|
|
2023
|
+
add(k, bound ? `${bound}()` : "a callback");
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
out.set("this", [{ at: 0, label: "this", kind: "this" }]);
|
|
2027
|
+
out.set("arguments", [{ at: 0, label: "arguments", kind: "arguments" }]);
|
|
2028
|
+
return out;
|
|
2029
|
+
}
|
|
2030
|
+
/** Globals that return plain data, and syntax that looks like a call. */
|
|
2031
|
+
const PLAIN_CALLEES = new Set("String Number Boolean BigInt Symbol Array Object Date RegExp Map Set WeakMap WeakSet Promise Error TypeError RangeError URL URLSearchParams parseInt parseFloat isNaN isFinite encodeURIComponent encodeURI decodeURIComponent decodeURI structuredClone setTimeout clearTimeout setInterval clearInterval queueMicrotask require import super if for while switch catch with function return typeof void delete await yield new async in of instanceof case do else".split(" "));
|
|
2032
|
+
/** How an environment variable read (`process.env.NAME`) is named among the opaque values. */
|
|
2033
|
+
const ENV_READ = "process.env";
|
|
2034
|
+
/** An environment variable whose name says it holds markup: FOOTER_MARKUP, BANNER_HTML, ANALYTICS_SNIPPET. */
|
|
2035
|
+
const MARKUP_ENV = /markup|html|svg|snippet|partial|fragment|banner|footer|header|template|embed/i;
|
|
2036
|
+
/** Calls that read a file or a response: what they return may be markup. */
|
|
2037
|
+
const READER_METHODS = new Set(["readFileSync", "readFile", "text"]);
|
|
2038
|
+
/**
|
|
2039
|
+
* A callee whose name says it returns markup: marked(), md.render(),
|
|
2040
|
+
* DOMPurify.sanitize(), hljs.highlight(), renderToString(). Other package
|
|
2041
|
+
* and global functions (slugify(), format()) are taken to return text.
|
|
2042
|
+
*/
|
|
2043
|
+
const MARKUP_CALLEE = /render|markdown|marked|markup|html|sanitize|highlight|svg/i;
|
|
2044
|
+
/**
|
|
2045
|
+
* The names that may hold or return markup built as a string: a local
|
|
2046
|
+
* function, a binding (`let out = ""; out += \`<li>...\``), an array
|
|
2047
|
+
* filled with .push() or .unshift(), or a parameter of a local function
|
|
2048
|
+
* that a call in this file passes such a value, whose code holds a markup
|
|
2049
|
+
* literal, calls a project import, or reads another such name. A region
|
|
2050
|
+
* that calls a function this file cannot see into and that may return
|
|
2051
|
+
* markup (a callback parameter, a function named for markup such as
|
|
2052
|
+
* marked() or md.render(), a file read or a response's text()) may hold
|
|
2053
|
+
* markup too. Names
|
|
2054
|
+
* are merged across scopes, so a name that holds markup anywhere counts
|
|
2055
|
+
* everywhere: the fix is withheld when unsure. Each identifier counts for
|
|
2056
|
+
* the innermost region around it, and a region counts for the ones around
|
|
2057
|
+
* it, so the pass stays linear in the tokens.
|
|
2058
|
+
*/
|
|
2059
|
+
function markupProducers(tokens, functions, bindings, sourceWithin, projectNames, isTrustedCallee, seeds = new Map()) {
|
|
2060
|
+
const n = tokens.length;
|
|
2061
|
+
const isPunct = (k, v) => k >= 0 &&
|
|
2062
|
+
k < n &&
|
|
2063
|
+
tokens[k].type === "punctuation" &&
|
|
2064
|
+
tokens[k].value === v;
|
|
2065
|
+
/** An identifier read as a value: not a property (`x.name`) or a key (`{ name: x }`). */
|
|
2066
|
+
const reads = (k) => tokens[k].type === "identifier" &&
|
|
2067
|
+
!isPunct(k - 1, ".") &&
|
|
2068
|
+
!(isPunct(k + 1, ":") && (isPunct(k - 1, "{") || isPunct(k - 1, ",")));
|
|
2069
|
+
const regions = [
|
|
2070
|
+
...functions,
|
|
2071
|
+
...bindings.map((b) => ({ name: b.name, start: b.from, end: b.end })),
|
|
2072
|
+
];
|
|
2073
|
+
const opens = [];
|
|
2074
|
+
const partner = new Int32Array(n).fill(-1);
|
|
2075
|
+
for (let k = 0; k < n; k++) {
|
|
2076
|
+
if (tokens[k].type !== "punctuation")
|
|
2077
|
+
continue;
|
|
2078
|
+
const v = tokens[k].value;
|
|
2079
|
+
if (v === "(" || v === "[" || v === "{")
|
|
2080
|
+
opens.push(k);
|
|
2081
|
+
else if ((v === ")" || v === "]" || v === "}") && opens.length > 0)
|
|
2082
|
+
partner[opens.pop()] = k;
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* Each top-level argument of the call whose `(` is at `open`, as source
|
|
2086
|
+
* offsets between its separators (a template argument has no token of
|
|
2087
|
+
* its own, only its holes do).
|
|
2088
|
+
*/
|
|
2089
|
+
const argumentsOf = (open) => {
|
|
2090
|
+
const close = partner[open];
|
|
2091
|
+
const spans = [];
|
|
2092
|
+
let from = tokens[open].end;
|
|
2093
|
+
for (let j = open + 1; j <= close; j++) {
|
|
2094
|
+
if (j === close || isPunct(j, ",")) {
|
|
2095
|
+
spans.push([from, tokens[j].start]);
|
|
2096
|
+
from = tokens[j].end;
|
|
2097
|
+
}
|
|
2098
|
+
else if (partner[j] !== -1)
|
|
2099
|
+
j = partner[j];
|
|
2100
|
+
}
|
|
2101
|
+
return spans;
|
|
2102
|
+
};
|
|
2103
|
+
// for (const NAME of VALUE) and for (const [k, v] in VALUE): each name
|
|
2104
|
+
// holds what VALUE holds.
|
|
2105
|
+
for (let k = 0; k + 3 < n; k++) {
|
|
2106
|
+
if (!(tokens[k].type === "identifier" && tokens[k].value === "for") ||
|
|
2107
|
+
!isPunct(k + 1, "(") ||
|
|
2108
|
+
partner[k + 1] === -1 ||
|
|
2109
|
+
!(tokens[k + 2].type === "identifier" &&
|
|
2110
|
+
/^(?:const|let|var)$/.test(tokens[k + 2].value)))
|
|
2111
|
+
continue;
|
|
2112
|
+
const close = partner[k + 1];
|
|
2113
|
+
let j = k + 3;
|
|
2114
|
+
const names = [];
|
|
2115
|
+
if (isPunct(j, "[") || isPunct(j, "{")) {
|
|
2116
|
+
const end = partner[j];
|
|
2117
|
+
if (end === -1 || end >= close)
|
|
2118
|
+
continue;
|
|
2119
|
+
for (let q = j + 1; q < end; q++)
|
|
2120
|
+
if (tokens[q].type === "identifier" &&
|
|
2121
|
+
!isPunct(q + 1, ":") &&
|
|
2122
|
+
!isPunct(q - 1, "."))
|
|
2123
|
+
names.push(tokens[q].value);
|
|
2124
|
+
j = end + 1;
|
|
2125
|
+
}
|
|
2126
|
+
else if (tokens[j].type === "identifier")
|
|
2127
|
+
names.push(tokens[j++].value);
|
|
2128
|
+
if (j >= close ||
|
|
2129
|
+
tokens[j].type !== "identifier" ||
|
|
2130
|
+
(tokens[j].value !== "of" && tokens[j].value !== "in"))
|
|
2131
|
+
continue;
|
|
2132
|
+
for (const name of names)
|
|
2133
|
+
regions.push({
|
|
2134
|
+
name,
|
|
2135
|
+
start: tokens[j].end,
|
|
2136
|
+
end: tokens[close].start,
|
|
333
2137
|
});
|
|
2138
|
+
}
|
|
2139
|
+
const paramsOf = new Map();
|
|
2140
|
+
for (const fn of functions)
|
|
2141
|
+
if (fn.params.length > 0) {
|
|
2142
|
+
const list = paramsOf.get(fn.name) ?? [];
|
|
2143
|
+
// Appended in place: copying the list for every function of the same name made a script of many
|
|
2144
|
+
// same-named helpers quadratic.
|
|
2145
|
+
fn.params.forEach((names, i) => (list[i] ??= []).push(...names));
|
|
2146
|
+
paramsOf.set(fn.name, list);
|
|
2147
|
+
}
|
|
2148
|
+
const localNames = new Set(functions.map((f) => f.name));
|
|
2149
|
+
/** Every local function's parameter names: a call of one runs a callback. */
|
|
2150
|
+
const parameters = new Set(functions.flatMap((f) => f.params.flat()));
|
|
2151
|
+
const opaqueStarts = [];
|
|
2152
|
+
const opaqueValues = [];
|
|
2153
|
+
for (let k = 0; k + 1 < n; k++) {
|
|
2154
|
+
// process.env.FOOTER_HTML: an environment variable named for markup.
|
|
2155
|
+
// Others (SITE_URL, NAME) are taken to hold text, as package functions
|
|
2156
|
+
// not named for markup are.
|
|
2157
|
+
if (tokens[k].type === "identifier" &&
|
|
2158
|
+
tokens[k].value === "process" &&
|
|
2159
|
+
!isPunct(k - 1, ".") &&
|
|
2160
|
+
isPunct(k + 1, ".") &&
|
|
2161
|
+
k + 4 < n &&
|
|
2162
|
+
tokens[k + 2].value === "env" &&
|
|
2163
|
+
(isPunct(k + 3, ".") || isPunct(k + 3, "[")) &&
|
|
2164
|
+
MARKUP_ENV.test(tokens[k + 4].value)) {
|
|
2165
|
+
opaqueStarts.push(tokens[k].start);
|
|
2166
|
+
opaqueValues.push(ENV_READ);
|
|
334
2167
|
continue;
|
|
335
2168
|
}
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
2169
|
+
if (tokens[k].type !== "identifier" || !isPunct(k + 1, "("))
|
|
2170
|
+
continue;
|
|
2171
|
+
if (partner[k + 1] === -1)
|
|
2172
|
+
continue;
|
|
2173
|
+
const name = tokens[k].value;
|
|
2174
|
+
const after = partner[k + 1] + 1;
|
|
2175
|
+
// A definition, not a call: function name(...) {, a method name(...) {.
|
|
2176
|
+
const before = k > 0 ? tokens[k - 1] : undefined;
|
|
2177
|
+
if ((before?.type === "identifier" &&
|
|
2178
|
+
(before.value === "function" || METHOD_MODIFIERS.has(before.value))) ||
|
|
2179
|
+
isPunct(after, "{") ||
|
|
2180
|
+
(isPunct(after, ":") &&
|
|
2181
|
+
(before === undefined ||
|
|
2182
|
+
isPunct(k - 1, "{") ||
|
|
2183
|
+
isPunct(k - 1, "}") ||
|
|
2184
|
+
isPunct(k - 1, ";") ||
|
|
2185
|
+
isPunct(k - 1, ","))))
|
|
2186
|
+
continue;
|
|
2187
|
+
if (isPunct(k - 1, ".")) {
|
|
2188
|
+
// fs.readFileSync(...), res.text(): a file or a response; md.render().
|
|
2189
|
+
if (READER_METHODS.has(name) || MARKUP_CALLEE.test(name)) {
|
|
2190
|
+
opaqueStarts.push(tokens[k].start);
|
|
2191
|
+
opaqueValues.push(name);
|
|
2192
|
+
}
|
|
2193
|
+
// NAME.push(...) and NAME.unshift(...): the arguments fill NAME.
|
|
2194
|
+
if ((name === "push" || name === "unshift") &&
|
|
2195
|
+
k >= 2 &&
|
|
2196
|
+
tokens[k - 2].type === "identifier" &&
|
|
2197
|
+
!isPunct(k - 3, "."))
|
|
2198
|
+
regions.push({
|
|
2199
|
+
name: tokens[k - 2].value,
|
|
2200
|
+
start: tokens[k + 1].start,
|
|
2201
|
+
end: tokens[partner[k + 1]].end,
|
|
2202
|
+
});
|
|
2203
|
+
continue;
|
|
2204
|
+
}
|
|
2205
|
+
if (k > 0 &&
|
|
2206
|
+
tokens[k - 1].type === "identifier" &&
|
|
2207
|
+
tokens[k - 1].value === "new")
|
|
2208
|
+
continue;
|
|
2209
|
+
// A local function's parameters hold what its callers pass them.
|
|
2210
|
+
const params = paramsOf.get(name);
|
|
2211
|
+
if (params)
|
|
2212
|
+
argumentsOf(k + 1).forEach(([start, end], i) => {
|
|
2213
|
+
for (const param of params[i] ?? [])
|
|
2214
|
+
regions.push({ name: param, start, end });
|
|
358
2215
|
});
|
|
2216
|
+
if (!localNames.has(name) &&
|
|
2217
|
+
!projectNames.has(name) &&
|
|
2218
|
+
!PLAIN_CALLEES.has(name) &&
|
|
2219
|
+
!isTrustedCallee(name) &&
|
|
2220
|
+
(parameters.has(name) ||
|
|
2221
|
+
MARKUP_CALLEE.test(name) ||
|
|
2222
|
+
(READER_METHODS.has(name) && name !== "text"))) {
|
|
2223
|
+
opaqueStarts.push(tokens[k].start);
|
|
2224
|
+
opaqueValues.push(name);
|
|
359
2225
|
}
|
|
360
2226
|
}
|
|
361
|
-
|
|
2227
|
+
regions.sort((x, y) => x.start - y.start || y.end - x.end);
|
|
2228
|
+
const names = new Set();
|
|
2229
|
+
const markupNames = new Set();
|
|
2230
|
+
const usedBy = new Map();
|
|
2231
|
+
const queue = [];
|
|
2232
|
+
const markupQueue = [];
|
|
2233
|
+
const mark = (name) => {
|
|
2234
|
+
if (names.has(name))
|
|
2235
|
+
return;
|
|
2236
|
+
names.add(name);
|
|
2237
|
+
queue.push(name);
|
|
2238
|
+
};
|
|
2239
|
+
const markMarkup = (name) => {
|
|
2240
|
+
mark(name);
|
|
2241
|
+
if (markupNames.has(name))
|
|
2242
|
+
return;
|
|
2243
|
+
markupNames.add(name);
|
|
2244
|
+
markupQueue.push(name);
|
|
2245
|
+
};
|
|
2246
|
+
const edge = (from, to) => {
|
|
2247
|
+
if (from === to)
|
|
2248
|
+
return;
|
|
2249
|
+
let set = usedBy.get(from);
|
|
2250
|
+
if (!set)
|
|
2251
|
+
usedBy.set(from, (set = new Set()));
|
|
2252
|
+
set.add(to);
|
|
2253
|
+
};
|
|
2254
|
+
const opaqueAt = new Set(opaqueStarts);
|
|
2255
|
+
const stack = [];
|
|
2256
|
+
let r = 0;
|
|
2257
|
+
for (let k = 0; k <= n; k++) {
|
|
2258
|
+
const at = k < n ? tokens[k].start : Infinity;
|
|
2259
|
+
while (r < regions.length && regions[r].start <= at) {
|
|
2260
|
+
const region = regions[r++];
|
|
2261
|
+
while (stack.length > 0 && stack[stack.length - 1].end <= region.start)
|
|
2262
|
+
stack.pop();
|
|
2263
|
+
if (sourceWithin(region.start, region.end))
|
|
2264
|
+
markMarkup(region.name);
|
|
2265
|
+
if (stack.length > 0)
|
|
2266
|
+
edge(region.name, stack[stack.length - 1].name);
|
|
2267
|
+
stack.push(region);
|
|
2268
|
+
}
|
|
2269
|
+
if (k === n)
|
|
2270
|
+
break;
|
|
2271
|
+
while (stack.length > 0 && stack[stack.length - 1].end <= at)
|
|
2272
|
+
stack.pop();
|
|
2273
|
+
if (stack.length === 0)
|
|
2274
|
+
continue;
|
|
2275
|
+
const owner = stack[stack.length - 1].name;
|
|
2276
|
+
if (opaqueAt.has(at))
|
|
2277
|
+
mark(owner);
|
|
2278
|
+
if (!reads(k))
|
|
2279
|
+
continue;
|
|
2280
|
+
const value = tokens[k].value;
|
|
2281
|
+
// A project import that is called or passed on may return markup.
|
|
2282
|
+
if (projectNames.has(value))
|
|
2283
|
+
markMarkup(owner);
|
|
2284
|
+
else
|
|
2285
|
+
edge(value, owner);
|
|
2286
|
+
}
|
|
2287
|
+
while (markupQueue.length > 0)
|
|
2288
|
+
for (const next of usedBy.get(markupQueue.pop()) ?? [])
|
|
2289
|
+
markMarkup(next);
|
|
2290
|
+
// Seeds last, so a name they alone reach is known to hold a caller's
|
|
2291
|
+
// value rather than markup built in this file.
|
|
2292
|
+
const fromSeed = new Map();
|
|
2293
|
+
for (const seed of seeds.keys()) {
|
|
2294
|
+
if (markupNames.has(seed))
|
|
2295
|
+
continue;
|
|
2296
|
+
markMarkup(seed);
|
|
2297
|
+
fromSeed.set(seed, seed);
|
|
2298
|
+
while (markupQueue.length > 0) {
|
|
2299
|
+
const from = markupQueue.pop();
|
|
2300
|
+
for (const next of usedBy.get(from) ?? [])
|
|
2301
|
+
if (!markupNames.has(next)) {
|
|
2302
|
+
fromSeed.set(next, seed);
|
|
2303
|
+
markMarkup(next);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
while (queue.length > 0)
|
|
2308
|
+
for (const next of usedBy.get(queue.pop()) ?? [])
|
|
2309
|
+
mark(next);
|
|
2310
|
+
const starts = [];
|
|
2311
|
+
const values = [];
|
|
2312
|
+
// A project import read as a value (ICON_OK, icons.ok) may hold markup
|
|
2313
|
+
// built as a string in its module; one that is called is a project
|
|
2314
|
+
// helper, which projectHelperIn reports.
|
|
2315
|
+
for (let k = 0; k < n; k++)
|
|
2316
|
+
if (reads(k) &&
|
|
2317
|
+
(names.has(tokens[k].value) ||
|
|
2318
|
+
(projectNames.has(tokens[k].value) && !isPunct(k + 1, "(")))) {
|
|
2319
|
+
starts.push(tokens[k].start);
|
|
2320
|
+
values.push(tokens[k].value);
|
|
2321
|
+
}
|
|
2322
|
+
return {
|
|
2323
|
+
names,
|
|
2324
|
+
markupNames,
|
|
2325
|
+
starts,
|
|
2326
|
+
values,
|
|
2327
|
+
opaqueStarts,
|
|
2328
|
+
opaqueValues,
|
|
2329
|
+
fromSeed,
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2332
|
+
const CONTROL_WORDS = new Set([
|
|
2333
|
+
"if",
|
|
2334
|
+
"for",
|
|
2335
|
+
"while",
|
|
2336
|
+
"switch",
|
|
2337
|
+
"catch",
|
|
2338
|
+
"with",
|
|
2339
|
+
"function",
|
|
2340
|
+
"return",
|
|
2341
|
+
"typeof",
|
|
2342
|
+
"await",
|
|
2343
|
+
"new",
|
|
2344
|
+
]);
|
|
2345
|
+
const METHOD_MODIFIERS = new Set([
|
|
2346
|
+
"async",
|
|
2347
|
+
"static",
|
|
2348
|
+
"get",
|
|
2349
|
+
"set",
|
|
2350
|
+
"public",
|
|
2351
|
+
"private",
|
|
2352
|
+
"protected",
|
|
2353
|
+
"override",
|
|
2354
|
+
]);
|
|
2355
|
+
/** A template whose first tag is an XML prolog or the root of a sitemap or a feed. */
|
|
2356
|
+
const XML_TEMPLATE = /^\s*<(?:\?xml\b|(?:rss|feed|urlset|sitemapindex|sitemap|url|loc|channel|item|entry)(?=[\s/>]))/;
|
|
2357
|
+
/** How a message quotes a hole: `${expr}`, cut short when the expression is long. */
|
|
2358
|
+
function quoteHole(expr) {
|
|
2359
|
+
const e = expr.trim();
|
|
2360
|
+
return `\${${e.length > 60 ? `${e.slice(0, 57)}...` : e}}`;
|
|
2361
|
+
}
|
|
2362
|
+
/** How a withheld fix explains the allowlist. */
|
|
2363
|
+
const UNPROVEN_TEXT = "cannot prove it is plain text. The fix is offered only when every hole is a literal with no & or < in its value, request data, an environment variable, a date, a Math result, a number, bigint or boolean parameter of a local function only called by name, an html value, or a const or local helper built only from those. If the value is text, wrap the template in html`...` from @bascik/bascik/html yourself; if it is markup, make it an html`...` value first (raw() for trusted markup).";
|
|
2364
|
+
/** A .join() of html values inside html: the joined string is escaped. */
|
|
2365
|
+
export const JOINED_RULE = "html-joined-string";
|
|
2366
|
+
/**
|
|
2367
|
+
* A hole that is one call to a function named like an escaper (escape,
|
|
2368
|
+
* escapeHtml, sanitize, encodeEntities, utils.esc) that is not trusted.
|
|
2369
|
+
* encodeURI and encodeURIComponent encode URLs, not markup.
|
|
2370
|
+
*/
|
|
2371
|
+
function handEscaper(expr) {
|
|
2372
|
+
const callee = callOf(expr);
|
|
2373
|
+
if (callee === undefined)
|
|
2374
|
+
return undefined;
|
|
2375
|
+
const last = callee.slice(callee.lastIndexOf(".") + 1);
|
|
2376
|
+
if (/^encodeURI(?:Component)?$/.test(last))
|
|
2377
|
+
return undefined;
|
|
2378
|
+
if (!/^(?:esc|escape|sanitize|sanitise|encode)/i.test(last) &&
|
|
2379
|
+
!/(?:Escape|Sanitize|Sanitise|Entities)/.test(last))
|
|
2380
|
+
return undefined;
|
|
2381
|
+
const e = expr.trim();
|
|
2382
|
+
return { name: callee, args: e.slice(e.indexOf("(") + 1, -1).trim() };
|
|
2383
|
+
}
|
|
2384
|
+
/** Names bound (up to the next ;) to a value that ends in .join(...). */
|
|
2385
|
+
function joinedNames(body) {
|
|
2386
|
+
const names = new Set();
|
|
2387
|
+
for (const m of body.matchAll(/\b(?:const|let|var)\s+([\w$]+)\s*=(?![=>])/g)) {
|
|
2388
|
+
const from = (m.index ?? 0) + m[0].length;
|
|
2389
|
+
const semicolon = body.indexOf(";", from);
|
|
2390
|
+
// A bounded look: a declaration with no ; is cut at 500 characters.
|
|
2391
|
+
const end = semicolon === -1 || semicolon - from > 500 ? from + 500 : semicolon;
|
|
2392
|
+
if (/\.join\s*\([^()]*\)\s*$/.test(body.slice(from, end)))
|
|
2393
|
+
names.add(m[1]);
|
|
2394
|
+
}
|
|
2395
|
+
return names;
|
|
2396
|
+
}
|
|
2397
|
+
/** Whether a hole is a .join(...) call, or a name bound to one. */
|
|
2398
|
+
function isJoined(expr, joined) {
|
|
2399
|
+
const e = expr.trim();
|
|
2400
|
+
return /\.join\s*\([^()]*\)$/.test(e) || joined.has(e);
|
|
2401
|
+
}
|
|
2402
|
+
const SINK_MESSAGES = {
|
|
2403
|
+
"server-script-sink-url-attribute": "URL attribute. Entity escaping does not stop a `javascript:` or `data:` URL. Build the markup with html`...` from @bascik/bascik/html, which checks URLs, or pass the value through safeUrl() and esc().",
|
|
2404
|
+
"server-script-sink-event-handler": "Event handler attribute. There is no safe way to interpolate untrusted data here. Move the value to a `data-*` attribute and read it from a static client script.",
|
|
2405
|
+
"server-script-sink-inline-script": 'Inline `<script>` body. Entity escaping does not apply in JavaScript context. Serialize to a `data-*` attribute or a `<script type="application/json">` filled with json(value) from @bascik/bascik/html.',
|
|
2406
|
+
"server-script-sink-style": "CSS context. Do not interpolate untrusted data into styles.",
|
|
2407
|
+
"server-script-sink-unquoted-attribute": 'Unquoted attribute. A space in the value breaks out of the attribute. Quote it: `attr="${...}"`.',
|
|
2408
|
+
};
|
|
2409
|
+
/** How far back a fragment's hole is read when the template opens no tag. */
|
|
2410
|
+
const FRAGMENT_WINDOW = 256;
|
|
2411
|
+
const URL_ATTRIBUTE = /\b(?:href|src|action|formaction|poster|data|srcset|xlink:href)$/;
|
|
2412
|
+
/** Which sink rule a hole falls under, from where it lands, or null for text and names. */
|
|
2413
|
+
function sinkOfContext(context) {
|
|
2414
|
+
if (context.kind === "value") {
|
|
2415
|
+
if (URL_ATTRIBUTE.test(context.attr))
|
|
2416
|
+
return "server-script-sink-url-attribute";
|
|
2417
|
+
if (/\bon[a-z]+$/.test(context.attr))
|
|
2418
|
+
return "server-script-sink-event-handler";
|
|
2419
|
+
if (/\bstyle$/.test(context.attr))
|
|
2420
|
+
return "server-script-sink-style";
|
|
2421
|
+
return null;
|
|
2422
|
+
}
|
|
2423
|
+
if (context.kind === "raw") {
|
|
2424
|
+
if (context.tag === "script")
|
|
2425
|
+
return "server-script-sink-inline-script";
|
|
2426
|
+
if (context.tag === "style")
|
|
2427
|
+
return "server-script-sink-style";
|
|
2428
|
+
return null;
|
|
2429
|
+
}
|
|
2430
|
+
if (context.kind === "unquoted")
|
|
2431
|
+
return "server-script-sink-unquoted-attribute";
|
|
2432
|
+
return null;
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Which sink rule a hole after `precedingInLiteral` falls under, or null for
|
|
2436
|
+
* text. For a fragment that opens no tag; the caller bounds the text.
|
|
2437
|
+
*/
|
|
2438
|
+
function sinkOf(precedingInLiteral) {
|
|
2439
|
+
// Inside a quoted URL attribute value.
|
|
2440
|
+
if (/\b(?:href|src|action|formaction|poster|data|srcset|xlink:href)\s*=\s*["'][^"']*$/i.test(precedingInLiteral))
|
|
2441
|
+
return "server-script-sink-url-attribute";
|
|
2442
|
+
// Inside a quoted on* attribute value.
|
|
2443
|
+
if (/\bon[a-z]+\s*=\s*["'][^"']*$/i.test(precedingInLiteral))
|
|
2444
|
+
return "server-script-sink-event-handler";
|
|
2445
|
+
// An unclosed <script> before the hole.
|
|
2446
|
+
if (lastOpenAfterClose(precedingInLiteral, "script"))
|
|
2447
|
+
return "server-script-sink-inline-script";
|
|
2448
|
+
// A quoted style attribute or an unclosed <style>.
|
|
2449
|
+
if (/\bstyle\s*=\s*["'][^"']*$/i.test(precedingInLiteral) ||
|
|
2450
|
+
lastOpenAfterClose(precedingInLiteral, "style"))
|
|
2451
|
+
return "server-script-sink-style";
|
|
2452
|
+
// An = with no opening quote.
|
|
2453
|
+
if (/\s[a-zA-Z_:][-a-zA-Z0-9_:.]*\s*=\s*$/.test(precedingInLiteral))
|
|
2454
|
+
return "server-script-sink-unquoted-attribute";
|
|
2455
|
+
return null;
|
|
2456
|
+
}
|
|
2457
|
+
/** Whether the last `<name ...>` in `text` comes after its last `</name>`. */
|
|
2458
|
+
function lastOpenAfterClose(text, name) {
|
|
2459
|
+
const opens = [
|
|
2460
|
+
...text.matchAll(new RegExp(`<${name}(?=[\\t\\n\\f\\r />])(?:[^>"']|"[^"]*"|'[^']*')*>`, "gi")),
|
|
2461
|
+
];
|
|
2462
|
+
if (opens.length === 0)
|
|
2463
|
+
return false;
|
|
2464
|
+
const closes = [
|
|
2465
|
+
...text.matchAll(new RegExp(`<\\/${name}(?:[\\t\\n\\f\\r /][^>]*)?>`, "gi")),
|
|
2466
|
+
];
|
|
2467
|
+
const lastOpen = opens[opens.length - 1].index ?? -1;
|
|
2468
|
+
const lastClose = closes.length
|
|
2469
|
+
? (closes[closes.length - 1].index ?? -1)
|
|
2470
|
+
: -1;
|
|
2471
|
+
return lastOpen > lastClose;
|
|
2472
|
+
}
|
|
2473
|
+
/** Keywords whose `(...)` is followed by a block, not a function body. */
|
|
2474
|
+
const BLOCK_KEYWORDS = new Set([
|
|
2475
|
+
"if",
|
|
2476
|
+
"for",
|
|
2477
|
+
"while",
|
|
2478
|
+
"switch",
|
|
2479
|
+
"catch",
|
|
2480
|
+
"with",
|
|
2481
|
+
"case",
|
|
2482
|
+
]);
|
|
2483
|
+
/**
|
|
2484
|
+
* A returned Response, matched where `skipResponsePrefix` stops: `new
|
|
2485
|
+
* Response(` or `Response.json(` / `.redirect(` / `.error(`. Group 1 is what
|
|
2486
|
+
* gets marked. The prefix is skipped by a loop rather than a leading
|
|
2487
|
+
* `(?:\(|\bawait\b|\s)*`, which CodeQL reports as a polynomial regex (alert
|
|
2488
|
+
* 207).
|
|
2489
|
+
*/
|
|
2490
|
+
const RESPONSE_VALUE = /(new\s+Response|Response\s*\.\s*(?:json|redirect|error))\s*\(/y;
|
|
2491
|
+
const isRegexWordChar = (char) => char !== undefined && /\w/.test(char);
|
|
2492
|
+
/**
|
|
2493
|
+
* Past the parentheses, whole-word `await`s and whitespace at `i`: what may
|
|
2494
|
+
* come between `return` (or an arrow) and the Response it returns.
|
|
2495
|
+
*/
|
|
2496
|
+
function skipResponsePrefix(code, i) {
|
|
2497
|
+
for (;;) {
|
|
2498
|
+
if (code[i] === "(" || (i < code.length && isSpace(code[i])))
|
|
2499
|
+
i++;
|
|
2500
|
+
else if (code.startsWith("await", i) &&
|
|
2501
|
+
!isRegexWordChar(code[i - 1]) &&
|
|
2502
|
+
!isRegexWordChar(code[i + 5]))
|
|
2503
|
+
i += 5;
|
|
2504
|
+
else
|
|
2505
|
+
return i;
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
function skipSpace(code, i) {
|
|
2509
|
+
while (i < code.length && isSpace(code[i]))
|
|
2510
|
+
i++;
|
|
2511
|
+
return i;
|
|
2512
|
+
}
|
|
2513
|
+
function wordAt(code, i) {
|
|
2514
|
+
let end = i;
|
|
2515
|
+
while (end < code.length && isWordChar(code[end]))
|
|
2516
|
+
end++;
|
|
2517
|
+
return code.slice(i, end);
|
|
2518
|
+
}
|
|
2519
|
+
/** The word just before `i` (past whitespace), or "" when none. */
|
|
2520
|
+
function wordBefore(code, i) {
|
|
2521
|
+
let end = i;
|
|
2522
|
+
while (end > 0 && isSpace(code[end - 1]))
|
|
2523
|
+
end--;
|
|
2524
|
+
let start = end;
|
|
2525
|
+
while (start > 0 && isWordChar(code[start - 1]))
|
|
2526
|
+
start--;
|
|
2527
|
+
return code.slice(start, end);
|
|
2528
|
+
}
|
|
2529
|
+
/** Index of the `)` that closes the `(` at `open`, or -1. */
|
|
2530
|
+
function closeParen(code, open) {
|
|
2531
|
+
let depth = 0;
|
|
2532
|
+
for (let i = open; i < code.length; i++) {
|
|
2533
|
+
if (code[i] === "(")
|
|
2534
|
+
depth++;
|
|
2535
|
+
else if (code[i] === ")" && --depth === 0)
|
|
2536
|
+
return i;
|
|
2537
|
+
}
|
|
2538
|
+
return -1;
|
|
2539
|
+
}
|
|
2540
|
+
/**
|
|
2541
|
+
* The body of the function that starts at `i` in masked code: a function
|
|
2542
|
+
* declaration or expression, or an arrow function. A TypeScript return type
|
|
2543
|
+
* is skipped. Anything else (a call such as `withAuth(...)`, a class) is not
|
|
2544
|
+
* read, so the rule stays quiet.
|
|
2545
|
+
*/
|
|
2546
|
+
function functionBodyAt(code, i) {
|
|
2547
|
+
i = skipSpace(code, i);
|
|
2548
|
+
if (wordAt(code, i) === "async")
|
|
2549
|
+
i = skipSpace(code, i + 5);
|
|
2550
|
+
let isArrow = true;
|
|
2551
|
+
if (wordAt(code, i) === "function") {
|
|
2552
|
+
isArrow = false;
|
|
2553
|
+
i = skipSpace(code, i + 8);
|
|
2554
|
+
if (code[i] === "*")
|
|
2555
|
+
i = skipSpace(code, i + 1);
|
|
2556
|
+
i = skipSpace(code, i + wordAt(code, i).length);
|
|
2557
|
+
}
|
|
2558
|
+
if (code[i] === "(") {
|
|
2559
|
+
const close = closeParen(code, i);
|
|
2560
|
+
if (close < 0)
|
|
2561
|
+
return undefined;
|
|
2562
|
+
i = close + 1;
|
|
2563
|
+
}
|
|
2564
|
+
else if (isArrow && wordAt(code, i).length > 0) {
|
|
2565
|
+
i += wordAt(code, i).length;
|
|
2566
|
+
}
|
|
2567
|
+
else
|
|
2568
|
+
return undefined;
|
|
2569
|
+
if (!isArrow) {
|
|
2570
|
+
const open = code.indexOf("{", i);
|
|
2571
|
+
return open < 0 ? undefined : { block: open };
|
|
2572
|
+
}
|
|
2573
|
+
const arrow = code.indexOf("=>", i);
|
|
2574
|
+
// Only a return type may sit between the parameters and the arrow.
|
|
2575
|
+
if (arrow < 0 ||
|
|
2576
|
+
(code.slice(i, arrow).trim() !== "" && code[skipSpace(code, i)] !== ":"))
|
|
2577
|
+
return undefined;
|
|
2578
|
+
const body = skipSpace(code, arrow + 2);
|
|
2579
|
+
return code[body] === "{" ? { block: body } : { expression: body };
|
|
2580
|
+
}
|
|
2581
|
+
/** The body of the function a name is declared as, if it is one. */
|
|
2582
|
+
function declaredFunctionBody(code, name) {
|
|
2583
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name))
|
|
2584
|
+
return undefined;
|
|
2585
|
+
const escaped = name.replace(/\$/g, () => "\\$");
|
|
2586
|
+
const declared = new RegExp(`\\b(?:async\\s+)?function\\s*\\*?\\s*${escaped}(?![\\w$])|\\b(?:const|let|var)\\s+${escaped}(?![\\w$])[^=;]*=(?![=>])`).exec(code);
|
|
2587
|
+
if (declared === null)
|
|
2588
|
+
return undefined;
|
|
2589
|
+
return declared[0].endsWith("=")
|
|
2590
|
+
? functionBodyAt(code, declared.index + declared[0].length)
|
|
2591
|
+
: functionBodyAt(code, declared.index);
|
|
2592
|
+
}
|
|
2593
|
+
/** The default export's function body, from `export default` or `export { name as default }`. */
|
|
2594
|
+
function defaultExportBody(code) {
|
|
2595
|
+
const exported = /\bexport\s+default\b/.exec(code);
|
|
2596
|
+
if (exported !== null) {
|
|
2597
|
+
const at = skipSpace(code, exported.index + exported[0].length);
|
|
2598
|
+
const word = wordAt(code, at);
|
|
2599
|
+
const afterWord = skipSpace(code, at + word.length);
|
|
2600
|
+
if (word.length > 0 &&
|
|
2601
|
+
word !== "async" &&
|
|
2602
|
+
word !== "function" &&
|
|
2603
|
+
code.slice(afterWord, afterWord + 2) !== "=>")
|
|
2604
|
+
// `export default withAuth(...)` is a call: what it returns is not read.
|
|
2605
|
+
return code[afterWord] === "(" || code[afterWord] === "."
|
|
2606
|
+
? undefined
|
|
2607
|
+
: declaredFunctionBody(code, word);
|
|
2608
|
+
return functionBodyAt(code, at);
|
|
2609
|
+
}
|
|
2610
|
+
for (const clause of code.matchAll(/\bexport\s*\{([^{}]*)\}/g)) {
|
|
2611
|
+
for (const spec of clause[1].split(",")) {
|
|
2612
|
+
const named = /^\s*([\w$]+)\s+as\s+default\s*$/.exec(spec);
|
|
2613
|
+
if (named !== null)
|
|
2614
|
+
return declaredFunctionBody(code, named[1]);
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
return undefined;
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Each `new Response(...)` or `Response.json(...)` (`.redirect`, `.error`)
|
|
2621
|
+
* the default export returns, as offsets into `body`. Comments and strings are
|
|
2622
|
+
* masked first, so the words in either never count, and a `return` inside a
|
|
2623
|
+
* nested function (a helper, a callback, a method) belongs to that function.
|
|
2624
|
+
* One pass over the default export's body.
|
|
2625
|
+
*/
|
|
2626
|
+
export function findReturnedResponses(body) {
|
|
2627
|
+
const code = maskCommentsAndStrings(body);
|
|
2628
|
+
const fn = defaultExportBody(code);
|
|
2629
|
+
if (fn === undefined)
|
|
2630
|
+
return [];
|
|
2631
|
+
const found = [];
|
|
2632
|
+
const responseAt = (at) => {
|
|
2633
|
+
RESPONSE_VALUE.lastIndex = skipResponsePrefix(code, at);
|
|
2634
|
+
const m = RESPONSE_VALUE.exec(code);
|
|
2635
|
+
if (m === null)
|
|
2636
|
+
return;
|
|
2637
|
+
found.push({ start: m.index, end: m.index + m[1].length });
|
|
2638
|
+
};
|
|
2639
|
+
if ("expression" in fn) {
|
|
2640
|
+
responseAt(fn.expression);
|
|
2641
|
+
return found;
|
|
2642
|
+
}
|
|
2643
|
+
// true for a `{` that opens a function body, false for a block or object.
|
|
2644
|
+
const frames = [];
|
|
2645
|
+
let functionDepth = 0;
|
|
2646
|
+
const parenWords = [];
|
|
2647
|
+
let lastClose = { at: -1, word: "" };
|
|
2648
|
+
// Set when `: Type` follows a `)`, so `function f(): T {` still reads as a function.
|
|
2649
|
+
let annotatedClose;
|
|
2650
|
+
for (let i = fn.block + 1; i < code.length; i++) {
|
|
2651
|
+
const c = code[i];
|
|
2652
|
+
if (c === "(")
|
|
2653
|
+
parenWords.push(wordBefore(code, i));
|
|
2654
|
+
else if (c === ")") {
|
|
2655
|
+
lastClose = { at: i, word: parenWords.pop() ?? "" };
|
|
2656
|
+
annotatedClose = undefined;
|
|
2657
|
+
}
|
|
2658
|
+
else if (c === ":") {
|
|
2659
|
+
if (wordBefore(code, i) === "" &&
|
|
2660
|
+
code[skipSpaceBackIn(code, i) - 1] === ")")
|
|
2661
|
+
annotatedClose = lastClose;
|
|
2662
|
+
}
|
|
2663
|
+
else if (c === ";" || (c === "=" && code[i + 1] !== ">")) {
|
|
2664
|
+
annotatedClose = undefined;
|
|
2665
|
+
}
|
|
2666
|
+
else if (c === "{") {
|
|
2667
|
+
// A function body follows `=>`, or the `)` of a parameter list (with
|
|
2668
|
+
// or without a return type), but not the `)` of `if (...)` and the like.
|
|
2669
|
+
const prev = skipSpaceBackIn(code, i);
|
|
2670
|
+
const close = prev - 1 === lastClose.at ? lastClose : annotatedClose;
|
|
2671
|
+
const isFunction = (code[prev - 1] === ">" && code[prev - 2] === "=") ||
|
|
2672
|
+
(close !== undefined && !BLOCK_KEYWORDS.has(close.word));
|
|
2673
|
+
annotatedClose = undefined;
|
|
2674
|
+
frames.push(isFunction);
|
|
2675
|
+
if (isFunction)
|
|
2676
|
+
functionDepth++;
|
|
2677
|
+
}
|
|
2678
|
+
else if (c === "}") {
|
|
2679
|
+
if (frames.length === 0)
|
|
2680
|
+
break;
|
|
2681
|
+
if (frames.pop())
|
|
2682
|
+
functionDepth--;
|
|
2683
|
+
}
|
|
2684
|
+
else if (functionDepth === 0 &&
|
|
2685
|
+
c === "r" &&
|
|
2686
|
+
code.startsWith("return", i) &&
|
|
2687
|
+
!isWordChar(code[i - 1] ?? "") &&
|
|
2688
|
+
!isWordChar(code[i + 6] ?? "")) {
|
|
2689
|
+
// `return` then a line break returns undefined (automatic semicolon insertion).
|
|
2690
|
+
let j = i + 6;
|
|
2691
|
+
while (code[j] === " " || code[j] === "\t")
|
|
2692
|
+
j++;
|
|
2693
|
+
if (code[j] !== "\n" && code[j] !== "\r")
|
|
2694
|
+
responseAt(j);
|
|
2695
|
+
i += 5;
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
return found;
|
|
2699
|
+
}
|
|
2700
|
+
function skipSpaceBackIn(code, end) {
|
|
2701
|
+
while (end > 0 && isSpace(code[end - 1]))
|
|
2702
|
+
end--;
|
|
2703
|
+
return end;
|
|
362
2704
|
}
|
|
363
2705
|
//# sourceMappingURL=server-script-rules.js.map
|