@bascik/language-server 0.1.0-rc.5 → 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 +625 -75
- 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/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
package/dist/analyzer.js
CHANGED
|
@@ -7,10 +7,14 @@ import { findCompatibilityMatches } from "./rules.js";
|
|
|
7
7
|
import { analyzeApiRouteSource } from "./api-rules.js";
|
|
8
8
|
import { findComponentStructureProblems, isKnownBascikAttribute, isKnownBuildValue, unknownBascikAttributeMessage, unknownDirectiveValueMessage, } from "./directive-rules.js";
|
|
9
9
|
import { findModuleSpecifiers } from "./module-specifiers.js";
|
|
10
|
-
import { analyzeServerScriptSource } from "./server-script-rules.js";
|
|
10
|
+
import { analyzeServerScriptSource, } from "./server-script-rules.js";
|
|
11
|
+
import { HAND_WRITTEN_ESCAPER_RULE } from "./hand-written-escaper.js";
|
|
12
|
+
import { normalizeModulePath, scriptModulesOf, } from "./script-modules.js";
|
|
13
|
+
import { parseImportSpecifier } from "./server-script-templates.js";
|
|
11
14
|
import { analyzeComponentSource, } from "./component-metadata.js";
|
|
12
15
|
import { parseIgnoreDirectives, isDiagnosticIgnored, } from "./ignore-comments.js";
|
|
13
16
|
import { loadExtensionConfig } from "./config.js";
|
|
17
|
+
import { countInstancesOnPages, findNameGroups, sharedNameGroupMessage, } from "./name-groups.js";
|
|
14
18
|
export const BUILT_IN_HTML_ELEMENTS = new Set([
|
|
15
19
|
"a",
|
|
16
20
|
"abbr",
|
|
@@ -143,12 +147,12 @@ export const SCRIPT_DIRECTIVES = [
|
|
|
143
147
|
{
|
|
144
148
|
name: "data-bascik-server",
|
|
145
149
|
detail: "Bascik server-side request script",
|
|
146
|
-
documentation: "Executes in Node.js per request on production and dev servers. The default exported handler function replaces this script tag.",
|
|
150
|
+
documentation: "Executes in Node.js per request on production and dev servers. The markup the default exported handler function returns replaces this script tag: a string, an html`...` value, or an array of them, joined with no separator.",
|
|
147
151
|
},
|
|
148
152
|
{
|
|
149
153
|
name: "data-bascik-stream",
|
|
150
154
|
detail: "Bascik server-side streaming script",
|
|
151
|
-
documentation: "Executes in Node.js per request on production servers. Streams chunked HTML responses to the client as data becomes available.",
|
|
155
|
+
documentation: "Executes in Node.js per request on production and dev servers. Streams chunked HTML responses to the client as data becomes available. The handler returns markup as a server script does: a string, an html`...` value, or an array of them, joined with no separator.",
|
|
152
156
|
},
|
|
153
157
|
];
|
|
154
158
|
export const SCRIPT_BLOCK_RE = /(<script(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/script(?:[\t\n\f\r /][^>]*)?>/gi;
|
|
@@ -158,24 +162,45 @@ export function maskHtmlRawTextContents(html) {
|
|
|
158
162
|
export function escapeRegExp(value) {
|
|
159
163
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
160
164
|
}
|
|
165
|
+
/** Lookahead for the end of a tag name, as in the compiler: HTML whitespace, `/` or `>`. */
|
|
166
|
+
const TAG_NAME_END = "(?=[\\t\\n\\f\\r />])";
|
|
161
167
|
export function findMatchingClose(html, tagName, contentStart) {
|
|
162
168
|
const tn = tagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
163
|
-
|
|
164
|
-
|
|
169
|
+
// Tag names end at HTML whitespace, `/` or `>`, and an end tag may carry whitespace or junk before
|
|
170
|
+
// its `>`, the shapes the compiler accepts (component-tags.ts, component-slots.ts).
|
|
171
|
+
// The end tag runs to the first `>` after its name, so it is found as the name, then indexOf(">"): a
|
|
172
|
+
// regex `[^>]*>` rescanned the rest of the document from each `</name` with no `>` (quadratic).
|
|
173
|
+
const openRe = new RegExp(`<${tn}${TAG_NAME_END}`, "gi");
|
|
174
|
+
const closeNameRe = new RegExp(`<\\/${tn}${TAG_NAME_END}`, "gi");
|
|
175
|
+
const closeFrom = (from) => {
|
|
176
|
+
closeNameRe.lastIndex = from;
|
|
177
|
+
const name = closeNameRe.exec(html);
|
|
178
|
+
if (!name)
|
|
179
|
+
return null;
|
|
180
|
+
// No `>` after this end tag means none after any later one either.
|
|
181
|
+
const gt = html.indexOf(">", name.index + name[0].length);
|
|
182
|
+
return gt === -1 ? null : { index: name.index, end: gt + 1 };
|
|
183
|
+
};
|
|
184
|
+
// The next open and end tag at or after `pos`, kept while `pos` has not passed them, so nested or
|
|
185
|
+
// self-closing tags do not search again for the same end tag each time.
|
|
186
|
+
let openMatch;
|
|
187
|
+
let closeMatch;
|
|
165
188
|
let depth = 1;
|
|
166
189
|
let pos = contentStart;
|
|
167
190
|
while (pos < html.length) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const openMatch = openRe.exec(html);
|
|
171
|
-
const closeMatch = closeRe.exec(html);
|
|
191
|
+
if (closeMatch === undefined || (closeMatch && closeMatch.index < pos))
|
|
192
|
+
closeMatch = closeFrom(pos);
|
|
172
193
|
if (!closeMatch)
|
|
173
194
|
return -1;
|
|
195
|
+
if (openMatch === undefined || (openMatch && openMatch.index < pos)) {
|
|
196
|
+
openRe.lastIndex = pos;
|
|
197
|
+
openMatch = openRe.exec(html);
|
|
198
|
+
}
|
|
174
199
|
if (!openMatch || closeMatch.index < openMatch.index) {
|
|
175
200
|
depth--;
|
|
176
201
|
if (depth === 0)
|
|
177
202
|
return closeMatch.index;
|
|
178
|
-
pos = closeMatch.
|
|
203
|
+
pos = closeMatch.end;
|
|
179
204
|
}
|
|
180
205
|
else {
|
|
181
206
|
let inDoubleQuote = false;
|
|
@@ -224,7 +249,7 @@ const isTagNameChar = (code) => isTagNameStart(code) ||
|
|
|
224
249
|
* so its result depends only on where the scan stands; `tagEndFrom` remembers
|
|
225
250
|
* it per position and no position is scanned twice.
|
|
226
251
|
*/
|
|
227
|
-
function* scanTags(source) {
|
|
252
|
+
function* scanTags(source, from = 0) {
|
|
228
253
|
const length = source.length;
|
|
229
254
|
// 0 = not scanned yet, -1 = no closing `>`, otherwise the index after `>`.
|
|
230
255
|
const tagEndFrom = new Int32Array(length + 1);
|
|
@@ -258,7 +283,7 @@ function* scanTags(source) {
|
|
|
258
283
|
tagEndFrom[index] = end;
|
|
259
284
|
return end;
|
|
260
285
|
};
|
|
261
|
-
let cursor =
|
|
286
|
+
let cursor = from;
|
|
262
287
|
while (cursor < length) {
|
|
263
288
|
const open = source.indexOf("<", cursor);
|
|
264
289
|
if (open < 0)
|
|
@@ -281,33 +306,77 @@ function* scanTags(source) {
|
|
|
281
306
|
name: source.slice(nameStart, nameEnd),
|
|
282
307
|
closing,
|
|
283
308
|
text: source.slice(open, end),
|
|
309
|
+
start: open,
|
|
310
|
+
end,
|
|
284
311
|
};
|
|
285
312
|
cursor = end;
|
|
286
313
|
}
|
|
287
314
|
}
|
|
288
315
|
export function findNearestParentComponent(source, componentMap) {
|
|
289
|
-
|
|
290
|
-
|
|
316
|
+
return findNearestParentComponents(source, [source.length], componentMap)[0];
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* For each offset (ascending), the component that `findNearestParentComponent(source.slice(0, offset))`
|
|
320
|
+
* finds, from one scan of `source`. Rescanning the prefix for every offset was quadratic in the number of
|
|
321
|
+
* offsets (one per `data-bascik-slot` tag).
|
|
322
|
+
*
|
|
323
|
+
* The open-element stack carries, per entry, the nearest component at or below it, so each answer is
|
|
324
|
+
* read in constant time. A tag that starts before an offset but ends after it is not a tag in that prefix
|
|
325
|
+
* (its `>` is cut off), so for that offset the prefix scan is continued from just after its `<`, exactly
|
|
326
|
+
* as the prefix scan would, on a copy of the stack.
|
|
327
|
+
*/
|
|
328
|
+
export function findNearestParentComponents(source, offsets, componentMap) {
|
|
329
|
+
const apply = (stack, nearest, tag) => {
|
|
291
330
|
const name = tag.name.toLowerCase();
|
|
292
331
|
if (tag.closing) {
|
|
293
332
|
const matchingIndex = stack.lastIndexOf(name);
|
|
294
|
-
if (matchingIndex >= 0)
|
|
295
|
-
stack.
|
|
333
|
+
if (matchingIndex >= 0) {
|
|
334
|
+
stack.length = matchingIndex;
|
|
335
|
+
nearest.length = matchingIndex;
|
|
336
|
+
}
|
|
296
337
|
}
|
|
297
338
|
else if (!/\/\s*>$/.test(tag.text)) {
|
|
298
339
|
stack.push(name);
|
|
340
|
+
nearest.push(componentMap.has(name) ? name : nearest.at(-1));
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const stack = [];
|
|
344
|
+
const nearest = [];
|
|
345
|
+
const tags = scanTags(source);
|
|
346
|
+
let pending = tags.next();
|
|
347
|
+
const results = [];
|
|
348
|
+
for (const offset of offsets) {
|
|
349
|
+
while (!pending.done && pending.value.end <= offset) {
|
|
350
|
+
apply(stack, nearest, pending.value);
|
|
351
|
+
pending = tags.next();
|
|
352
|
+
}
|
|
353
|
+
if (!pending.done && pending.value.start < offset) {
|
|
354
|
+
// The offset sits inside what the full scan reads as one tag (an unclosed quote can make it long),
|
|
355
|
+
// so the tags before it are read from the source cut at the offset. Each such offset rescans from
|
|
356
|
+
// that tag's start: quadratic only when many slot tags hide inside one long run-on tag, which
|
|
357
|
+
// markup does not do, so the cost is accepted rather than memoized.
|
|
358
|
+
const prefixStack = stack.slice();
|
|
359
|
+
const prefixNearest = nearest.slice();
|
|
360
|
+
for (const tag of scanTags(source.slice(0, offset), pending.value.start + 1))
|
|
361
|
+
apply(prefixStack, prefixNearest, tag);
|
|
362
|
+
results.push(prefixNearest.at(-1));
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
results.push(nearest.at(-1));
|
|
299
366
|
}
|
|
300
367
|
}
|
|
301
|
-
return
|
|
368
|
+
return results;
|
|
302
369
|
}
|
|
303
370
|
export function parseScriptOpenTagAttributes(openTag) {
|
|
304
371
|
const attrs = new Map();
|
|
305
372
|
const insideTag = openTag.replace(/^<script\b/i, "").replace(/>$/, "");
|
|
306
|
-
|
|
373
|
+
// An unquoted value runs to whitespace (quotes, `=` and backticks
|
|
374
|
+
// included), and the first occurrence of a name wins, as in the tokenizer.
|
|
375
|
+
const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
|
|
307
376
|
let match;
|
|
308
377
|
while ((match = attrRe.exec(insideTag)) !== null) {
|
|
309
378
|
const name = match[1]?.toLowerCase();
|
|
310
|
-
if (!name)
|
|
379
|
+
if (!name || attrs.has(name))
|
|
311
380
|
continue;
|
|
312
381
|
const value = match[2] ?? match[3] ?? match[4];
|
|
313
382
|
attrs.set(name, value === undefined ? true : value);
|
|
@@ -319,11 +388,14 @@ export function parseScriptOpenTagAttributes(openTag) {
|
|
|
319
388
|
* maps to `""`, as the DOM reports it. The first occurrence of a name wins, as
|
|
320
389
|
* in the HTML tokenizer, and text inside a quoted value is never read as an
|
|
321
390
|
* attribute. An unquoted value keeps its slashes; a trailing `/>` ends it.
|
|
391
|
+
*
|
|
392
|
+
* @internal Exported for the attribute tokenizer agreement test
|
|
393
|
+
* (skills-tests/tests/attribute-tokenizer-agreement.test.ts).
|
|
322
394
|
*/
|
|
323
|
-
function readOpenTagAttributes(openTag) {
|
|
395
|
+
export function readOpenTagAttributes(openTag) {
|
|
324
396
|
const attrs = new Map();
|
|
325
397
|
const insideTag = openTag.replace(/^<[^\s/>]+/, "").replace(/\/?>$/, "");
|
|
326
|
-
const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'
|
|
398
|
+
const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
|
|
327
399
|
let match;
|
|
328
400
|
while ((match = attrRe.exec(insideTag)) !== null) {
|
|
329
401
|
const name = match[1].toLowerCase();
|
|
@@ -353,12 +425,22 @@ export function leadingSlashSpecifierMessage(specifier) {
|
|
|
353
425
|
`Use '@/${rest}' to resolve against scripts.importRoot, ` +
|
|
354
426
|
`or './${rest}' to resolve relative to this file.`);
|
|
355
427
|
}
|
|
428
|
+
/**
|
|
429
|
+
* The script directives that run in Node and resolve `./`, `../` and `@/` specifiers against the
|
|
430
|
+
* file and `scripts.importRoot`. Leading-slash diagnostics and Go to Definition share this list.
|
|
431
|
+
*/
|
|
432
|
+
const MODULE_RESOLVING_DIRECTIVES = [
|
|
433
|
+
"data-bascik-build",
|
|
434
|
+
"data-bascik-build-once",
|
|
435
|
+
"data-bascik-server",
|
|
436
|
+
"data-bascik-routes",
|
|
437
|
+
"data-bascik-stream",
|
|
438
|
+
];
|
|
439
|
+
function hasModuleResolvingDirective(attrs) {
|
|
440
|
+
return MODULE_RESOLVING_DIRECTIVES.some((name) => attrs.has(name));
|
|
441
|
+
}
|
|
356
442
|
export function collectLeadingSlashDiagnostics(document, openTag, scriptBody, blockStart, attrs) {
|
|
357
|
-
if (!attrs
|
|
358
|
-
!attrs.has("data-bascik-build-once") &&
|
|
359
|
-
!attrs.has("data-bascik-server") &&
|
|
360
|
-
!attrs.has("data-bascik-routes") &&
|
|
361
|
-
!attrs.has("data-bascik-stream")) {
|
|
443
|
+
if (!hasModuleResolvingDirective(attrs)) {
|
|
362
444
|
return [];
|
|
363
445
|
}
|
|
364
446
|
const out = [];
|
|
@@ -439,7 +521,60 @@ export function completionReplacementRange(document, position) {
|
|
|
439
521
|
end: position,
|
|
440
522
|
};
|
|
441
523
|
}
|
|
442
|
-
|
|
524
|
+
/**
|
|
525
|
+
* The `component-name-underscore` message for a component file, or null. The
|
|
526
|
+
* tag is the lowercased file name up to its first dot, as the build derives it
|
|
527
|
+
* (`deriveComponentName` in @bascik/bascik), so `site-nav.my_v2.html` defines
|
|
528
|
+
* `<site-nav>` and gets no warning. An `#id` rule compiles to the class
|
|
529
|
+
* `b_id_<component>_<id>`, so `<a_b>` with `#c` and `<a>` with `#b_c` spell
|
|
530
|
+
* one class, which the build rejects; the example uses the file's own name.
|
|
531
|
+
*/
|
|
532
|
+
export const componentNameUnderscoreMessage = (fileName) => {
|
|
533
|
+
const tag = fileName.split(".")[0].toLowerCase();
|
|
534
|
+
const at = tag.indexOf("_");
|
|
535
|
+
if (at === -1)
|
|
536
|
+
return null;
|
|
537
|
+
const head = tag.slice(0, at);
|
|
538
|
+
const rest = tag.slice(at + 1);
|
|
539
|
+
// The example needs a real pair: a component name and an id that starts
|
|
540
|
+
// with a letter, as an #id selector the build converts does.
|
|
541
|
+
return underscoreMessage(tag, head && /^[a-z]/.test(rest) ? { head, rest } : null);
|
|
542
|
+
};
|
|
543
|
+
const underscoreMessage = (tag, split) => {
|
|
544
|
+
const example = split
|
|
545
|
+
? `: #btn in <${tag}> and #${split.rest}_btn in <${split.head}> both compile to the class b_id_${tag}_btn, which stops the build`
|
|
546
|
+
: "";
|
|
547
|
+
return `Component "${tag}" has an underscore in its name. The name is legal, but underscores can make two components' generated id classes spell the same name${example}. Use hyphens (e.g. "${tag.replace(/_/g, "-")}").`;
|
|
548
|
+
};
|
|
549
|
+
/**
|
|
550
|
+
* createDiagnostics, or one analysis-failed warning when it throws, so one
|
|
551
|
+
* file cannot stop `bascik --check` or end the language server. The
|
|
552
|
+
* template scanners keep their nesting on an explicit stack, so deep
|
|
553
|
+
* nesting does not throw; this is the net for whatever else does.
|
|
554
|
+
*/
|
|
555
|
+
export function createDiagnosticsSafely(...args) {
|
|
556
|
+
try {
|
|
557
|
+
return createDiagnostics(...args);
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
561
|
+
return [
|
|
562
|
+
{
|
|
563
|
+
range: {
|
|
564
|
+
start: { line: 0, character: 0 },
|
|
565
|
+
end: { line: 0, character: 0 },
|
|
566
|
+
},
|
|
567
|
+
message: `Bascik could not analyze this file (${reason}), so it shows no other Bascik diagnostics for it. Please report it with the file, or the smallest part of it that still shows this warning.`,
|
|
568
|
+
severity: DiagnosticSeverity.Warning,
|
|
569
|
+
source: "bascik",
|
|
570
|
+
code: "analysis-failed",
|
|
571
|
+
},
|
|
572
|
+
];
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = [],
|
|
576
|
+
/** The files that run in Node (see script-modules.ts); found from the snapshot when left out. */
|
|
577
|
+
scriptModules) {
|
|
443
578
|
const { languageId } = document;
|
|
444
579
|
if (languageId !== "css" &&
|
|
445
580
|
languageId !== "javascript" &&
|
|
@@ -453,6 +588,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
453
588
|
}
|
|
454
589
|
const text = document.getText();
|
|
455
590
|
const diagnostics = [];
|
|
591
|
+
const earlyExtConfig = snapshot
|
|
592
|
+
? loadExtensionConfig(snapshot.projectRoot)
|
|
593
|
+
: {};
|
|
456
594
|
const isComponentDocument = snapshot !== undefined &&
|
|
457
595
|
isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots);
|
|
458
596
|
// The API folder is `directory.api`, so it is read from the project when there is one. Without a project
|
|
@@ -485,10 +623,18 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
485
623
|
severity = DiagnosticSeverity.Information;
|
|
486
624
|
}
|
|
487
625
|
diagnostics.push({
|
|
488
|
-
range:
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
626
|
+
range: diag.range
|
|
627
|
+
? {
|
|
628
|
+
start: {
|
|
629
|
+
line: diag.range.startLine,
|
|
630
|
+
character: diag.range.startChar,
|
|
631
|
+
},
|
|
632
|
+
end: { line: diag.range.endLine, character: diag.range.endChar },
|
|
633
|
+
}
|
|
634
|
+
: {
|
|
635
|
+
start: { line: 0, character: 0 },
|
|
636
|
+
end: { line: 0, character: Math.min(text.length, 10) },
|
|
637
|
+
},
|
|
492
638
|
message: diag.message,
|
|
493
639
|
severity,
|
|
494
640
|
source: "bascik",
|
|
@@ -496,9 +642,77 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
496
642
|
});
|
|
497
643
|
}
|
|
498
644
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
645
|
+
/** Located diagnostics for a script body at `bodyStart`, with the data its quick fixes need. */
|
|
646
|
+
const pushScriptDiagnostics = (found, bodyStart, bodyLength) => {
|
|
647
|
+
const bodyEnd = bodyStart + bodyLength;
|
|
648
|
+
for (const sd of found) {
|
|
649
|
+
let severity = DiagnosticSeverity.Error;
|
|
650
|
+
if (sd.severity === "warning")
|
|
651
|
+
severity = DiagnosticSeverity.Warning;
|
|
652
|
+
else if (sd.severity === "info")
|
|
653
|
+
severity = DiagnosticSeverity.Information;
|
|
654
|
+
let data;
|
|
655
|
+
if (sd.template)
|
|
656
|
+
data = {
|
|
657
|
+
templateStart: bodyStart + sd.template.start,
|
|
658
|
+
fixable: sd.template.fixable,
|
|
659
|
+
bodyStart,
|
|
660
|
+
bodyEnd,
|
|
661
|
+
};
|
|
662
|
+
else if (sd.code === HAND_WRITTEN_ESCAPER_RULE)
|
|
663
|
+
data = {
|
|
664
|
+
bodyStart,
|
|
665
|
+
bodyEnd,
|
|
666
|
+
...(sd.escaper
|
|
667
|
+
? {
|
|
668
|
+
delegate: {
|
|
669
|
+
...sd.escaper,
|
|
670
|
+
start: bodyStart + sd.escaper.start,
|
|
671
|
+
end: bodyStart + sd.escaper.end,
|
|
672
|
+
},
|
|
673
|
+
}
|
|
674
|
+
: {}),
|
|
675
|
+
};
|
|
676
|
+
diagnostics.push({
|
|
677
|
+
range: {
|
|
678
|
+
start: document.positionAt(bodyStart + sd.start),
|
|
679
|
+
end: document.positionAt(bodyStart + sd.end),
|
|
680
|
+
},
|
|
681
|
+
message: sd.message,
|
|
682
|
+
severity,
|
|
683
|
+
source: "bascik",
|
|
684
|
+
code: sd.code,
|
|
685
|
+
...(data ? { data } : {}),
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
// A .ts or .js file that runs in Node (a directive script's src= file, a
|
|
690
|
+
// module a script imports, an API route) gets the markup and escaper rules
|
|
691
|
+
// that inline directive scripts get. See script-modules.ts.
|
|
692
|
+
const isScriptLanguage = languageId === "typescript" || languageId === "javascript";
|
|
693
|
+
const modules = isScriptLanguage && snapshot !== undefined
|
|
694
|
+
? (scriptModules ?? scriptModulesOf(snapshot, openDocumentTexts))
|
|
695
|
+
: undefined;
|
|
696
|
+
const modulePath = normalizeModulePath(fsPath);
|
|
697
|
+
const isScriptModuleDocument = isScriptLanguage &&
|
|
698
|
+
(isApiRouteDocument || modules?.has(modulePath) === true);
|
|
699
|
+
// API routes, and what server scripts, stream scripts and API routes
|
|
700
|
+
// import, run per request: every sink rule applies.
|
|
701
|
+
const isRequestTimeModule = isApiRouteDocument || modules?.requestTime.has(modulePath) === true;
|
|
702
|
+
// A module browser code imports too is also scoped for the browser.
|
|
703
|
+
const isBrowserModule = modules?.browser.has(modulePath) === true;
|
|
704
|
+
if (isScriptModuleDocument &&
|
|
705
|
+
earlyExtConfig.diagnostics?.serverScriptRules !== false)
|
|
706
|
+
pushScriptDiagnostics(analyzeServerScriptSource(text, {
|
|
707
|
+
hasSrcAttribute: false,
|
|
708
|
+
directive: "module",
|
|
709
|
+
requestTime: isRequestTimeModule,
|
|
710
|
+
escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
|
|
711
|
+
}), 0, text.length);
|
|
712
|
+
// isComponentDocument needs the file inside a resolved (absolute) component root, so an unsaved
|
|
713
|
+
// buffer never matches; no POSIX-only `startsWith("/")` gate, which skipped every Windows path.
|
|
714
|
+
if (languageId === "html") {
|
|
715
|
+
if (isComponentDocument) {
|
|
502
716
|
const fileName = path.basename(normalizedDocumentPath);
|
|
503
717
|
const nameWithoutExt = fileName.replace(/\.html$/i, "").toLowerCase();
|
|
504
718
|
if (!nameWithoutExt.includes("-") &&
|
|
@@ -514,6 +728,19 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
514
728
|
source: "bascik",
|
|
515
729
|
});
|
|
516
730
|
}
|
|
731
|
+
const underscore = componentNameUnderscoreMessage(fileName);
|
|
732
|
+
if (underscore) {
|
|
733
|
+
diagnostics.push({
|
|
734
|
+
range: {
|
|
735
|
+
start: { line: 0, character: 0 },
|
|
736
|
+
end: { line: 0, character: Math.min(text.length, 10) },
|
|
737
|
+
},
|
|
738
|
+
code: "component-name-underscore",
|
|
739
|
+
message: underscore,
|
|
740
|
+
severity: DiagnosticSeverity.Warning,
|
|
741
|
+
source: "bascik",
|
|
742
|
+
});
|
|
743
|
+
}
|
|
517
744
|
}
|
|
518
745
|
}
|
|
519
746
|
// Scoping rules describe what Bascik cannot rewrite, so they apply to component files, the only code it scopes.
|
|
@@ -547,7 +774,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
547
774
|
normalized === "text/javascript" ||
|
|
548
775
|
normalized === "application/javascript" ||
|
|
549
776
|
normalized === "text/ecmascript" ||
|
|
550
|
-
normalized === "application/ecmascript"
|
|
777
|
+
normalized === "application/ecmascript" ||
|
|
778
|
+
// Bascik transpiles inline TypeScript and scopes it like JavaScript (components.ts isJs).
|
|
779
|
+
normalized === "text/typescript");
|
|
551
780
|
};
|
|
552
781
|
const scriptBlockRe = new RegExp(SCRIPT_BLOCK_RE.source, SCRIPT_BLOCK_RE.flags);
|
|
553
782
|
const styleBlockRe = /(<style(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/style(?:[\t\n\f\r /][^>]*)?>/gi;
|
|
@@ -639,9 +868,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
639
868
|
});
|
|
640
869
|
}
|
|
641
870
|
}
|
|
871
|
+
// Field names are renamed only when the project opts in to name scoping; by default they ship as written,
|
|
872
|
+
// so a form that posts elsewhere needs nothing.
|
|
642
873
|
const formOpenTagRegex = /<form\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
|
|
643
874
|
let formMatch;
|
|
644
875
|
while (isComponentDocument &&
|
|
876
|
+
snapshot?.scopesName === true &&
|
|
645
877
|
(formMatch = formOpenTagRegex.exec(text)) !== null) {
|
|
646
878
|
const formAttributes = readOpenTagAttributes(formMatch[0]);
|
|
647
879
|
const action = formAttributes.get("action");
|
|
@@ -668,6 +900,27 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
668
900
|
source: "bascik",
|
|
669
901
|
});
|
|
670
902
|
}
|
|
903
|
+
if (snapshot && isComponentDocument && !snapshot.scopesName) {
|
|
904
|
+
const groups = findNameGroups(text);
|
|
905
|
+
const componentName = normalizeComponentName(fsPath);
|
|
906
|
+
const instances = groups.length > 0
|
|
907
|
+
? countInstancesOnPages(componentName, snapshot, openDocumentTexts)
|
|
908
|
+
: undefined;
|
|
909
|
+
if (instances && instances.count > 1) {
|
|
910
|
+
for (const group of groups) {
|
|
911
|
+
diagnostics.push({
|
|
912
|
+
range: {
|
|
913
|
+
start: document.positionAt(group.attributeStart),
|
|
914
|
+
end: document.positionAt(group.attributeEnd),
|
|
915
|
+
},
|
|
916
|
+
code: "shared-name-group",
|
|
917
|
+
message: sharedNameGroupMessage(group, componentName, instances, snapshot.projectRoot),
|
|
918
|
+
severity: DiagnosticSeverity.Warning,
|
|
919
|
+
source: "bascik",
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
671
924
|
if (snapshot && isComponentDocument) {
|
|
672
925
|
const componentName = normalizeComponentName(fsPath);
|
|
673
926
|
const directiveRegex = /data-bascik-attr-([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([\w-]+)"|'([\w-]+)'|([\w-]+))/gi;
|
|
@@ -676,7 +929,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
676
929
|
const targetName = directiveMatch[1];
|
|
677
930
|
const propName = directiveMatch[2] ?? directiveMatch[3] ?? directiveMatch[4];
|
|
678
931
|
const suppliedInOpen = openDocumentTexts.some(({ text }) => htmlSuppliesComponentProp(text, componentName, propName));
|
|
679
|
-
|
|
932
|
+
// Pages and HTML under src, plus every component file: a component root outside src (shared
|
|
933
|
+
// components in a monorepo) is not in htmlUsageByFile, as Find All References also allows for.
|
|
934
|
+
const suppliedInDisk = [
|
|
935
|
+
...snapshot.htmlUsageByFile.values(),
|
|
936
|
+
...(snapshot.componentSourceByFile?.values() ?? []),
|
|
937
|
+
].some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
|
|
680
938
|
if (suppliedInOpen || suppliedInDisk)
|
|
681
939
|
continue;
|
|
682
940
|
const start = document.positionAt(directiveMatch.index);
|
|
@@ -787,28 +1045,15 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
787
1045
|
? "build"
|
|
788
1046
|
: "routes";
|
|
789
1047
|
const hasSrcAttribute = /\ssrc\s*=/i.test(openTag);
|
|
790
|
-
const serverDiags =
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
let severity = DiagnosticSeverity.Error;
|
|
798
|
-
if (sd.severity === "warning") {
|
|
799
|
-
severity = DiagnosticSeverity.Warning;
|
|
800
|
-
}
|
|
801
|
-
else if (sd.severity === "info") {
|
|
802
|
-
severity = DiagnosticSeverity.Information;
|
|
803
|
-
}
|
|
804
|
-
diagnostics.push({
|
|
805
|
-
range: { start, end },
|
|
806
|
-
message: sd.message,
|
|
807
|
-
severity,
|
|
808
|
-
source: "bascik",
|
|
809
|
-
code: sd.code,
|
|
1048
|
+
const serverDiags = earlyExtConfig.diagnostics?.serverScriptRules === false
|
|
1049
|
+
? []
|
|
1050
|
+
: analyzeServerScriptSource(scriptBody, {
|
|
1051
|
+
hasSrcAttribute,
|
|
1052
|
+
directive,
|
|
1053
|
+
escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
|
|
1054
|
+
lineOffset: document.positionAt(scriptBodyOffset).line,
|
|
810
1055
|
});
|
|
811
|
-
|
|
1056
|
+
pushScriptDiagnostics(serverDiags, scriptBodyOffset, scriptBody.length);
|
|
812
1057
|
}
|
|
813
1058
|
diagnostics.push(...collectLeadingSlashDiagnostics(document, openTag, scriptBody, scriptMatch.index ?? 0, attrs));
|
|
814
1059
|
// A directive script runs in Node, at build time or per request, and never in the browser Bascik scopes.
|
|
@@ -911,6 +1156,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
911
1156
|
// 2. Diagnose data-bascik-slot outside of components, on the component itself, or targeting undeclared slots
|
|
912
1157
|
const slotTagRe = /<([A-Za-z][\w-]*)(?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?\/?>/gi;
|
|
913
1158
|
let slotMatch;
|
|
1159
|
+
const slotTags = [];
|
|
914
1160
|
while ((slotMatch = slotTagRe.exec(maskedText)) !== null) {
|
|
915
1161
|
const openTag = slotMatch[0];
|
|
916
1162
|
const matchStart = slotMatch.index;
|
|
@@ -931,11 +1177,15 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
931
1177
|
break;
|
|
932
1178
|
}
|
|
933
1179
|
}
|
|
934
|
-
if (
|
|
935
|
-
|
|
936
|
-
|
|
1180
|
+
if (slotAttr)
|
|
1181
|
+
slotTags.push({ matchStart, baseOffset, slotAttr });
|
|
1182
|
+
}
|
|
1183
|
+
// One scan finds every slot tag's parent; a prefix rescan per tag was quadratic.
|
|
1184
|
+
const slotParents = findNearestParentComponents(maskedText, slotTags.map(({ matchStart }) => matchStart), componentMap);
|
|
1185
|
+
for (const [slotIndex, slotTag] of slotTags.entries()) {
|
|
1186
|
+
const { matchStart, baseOffset, slotAttr } = slotTag;
|
|
937
1187
|
const slotName = slotAttr.value;
|
|
938
|
-
const parentName =
|
|
1188
|
+
const parentName = slotParents[slotIndex];
|
|
939
1189
|
const isInsideComponentDefinition = isComponentDocument;
|
|
940
1190
|
if (!parentName && !isInsideComponentDefinition) {
|
|
941
1191
|
const start = document.positionAt(matchStart + baseOffset + slotAttr.index);
|
|
@@ -969,7 +1219,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
969
1219
|
if (componentNames.length > 0) {
|
|
970
1220
|
componentNames.sort((a, b) => b.length - a.length);
|
|
971
1221
|
const escapedNames = componentNames.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
972
|
-
const componentTagRe = new RegExp(`<(${escapedNames.join("|")})
|
|
1222
|
+
const componentTagRe = new RegExp(`<(${escapedNames.join("|")})${TAG_NAME_END}`, "gi");
|
|
973
1223
|
let compMatch;
|
|
974
1224
|
while ((compMatch = componentTagRe.exec(maskedText)) !== null) {
|
|
975
1225
|
const tagStartIndex = compMatch.index;
|
|
@@ -1014,7 +1264,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
1014
1264
|
}
|
|
1015
1265
|
if (compMeta.props.length > 0) {
|
|
1016
1266
|
const insideOpenTag = openTagText
|
|
1017
|
-
.replace(new RegExp(`^<${escapeRegExp(tagName)}
|
|
1267
|
+
.replace(new RegExp(`^<${escapeRegExp(tagName)}${TAG_NAME_END}`, "i"), "")
|
|
1018
1268
|
.replace(/\/?>$/, "");
|
|
1019
1269
|
const baseAttrOffset = openTagText.indexOf(insideOpenTag);
|
|
1020
1270
|
const bareAttrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?/gi;
|
|
@@ -1027,7 +1277,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
1027
1277
|
const declaredProp = compMeta.props.find((p) => p.name.toLowerCase() === lowerAttr);
|
|
1028
1278
|
if (!declaredProp)
|
|
1029
1279
|
continue;
|
|
1030
|
-
const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}\\
|
|
1280
|
+
const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}(?![\\w-])`, "i").test(openTagText);
|
|
1031
1281
|
if (alreadySupplied)
|
|
1032
1282
|
continue;
|
|
1033
1283
|
const attrOffset = tagStartIndex + baseAttrOffset + bareMatch.index;
|
|
@@ -1101,11 +1351,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
1101
1351
|
else if (languageId === "css") {
|
|
1102
1352
|
addCompatibilityDiagnostics(text, "css", 0);
|
|
1103
1353
|
}
|
|
1104
|
-
else {
|
|
1354
|
+
else if (!isScriptModuleDocument || isBrowserModule) {
|
|
1355
|
+
// A module that only runs in Node is never scoped for the browser.
|
|
1105
1356
|
addCompatibilityDiagnostics(text, "js", 0);
|
|
1106
1357
|
}
|
|
1107
1358
|
const ignoreRanges = parseIgnoreDirectives(text, languageId);
|
|
1108
|
-
const extConfig =
|
|
1359
|
+
const extConfig = earlyExtConfig;
|
|
1109
1360
|
const disabledRules = new Set(extConfig.diagnostics?.disabledRules?.map((r) => r.toLowerCase()) ?? []);
|
|
1110
1361
|
if (extConfig.diagnostics?.enabled === false) {
|
|
1111
1362
|
return [];
|
|
@@ -1124,7 +1375,19 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
|
|
|
1124
1375
|
extConfig.diagnostics?.unclosedComponents === false) {
|
|
1125
1376
|
return false;
|
|
1126
1377
|
}
|
|
1127
|
-
|
|
1378
|
+
if (isDiagnosticIgnored(line, code, ignoreRanges))
|
|
1379
|
+
return false;
|
|
1380
|
+
// A hole on a later line of a multi-line template: an ignore comment
|
|
1381
|
+
// above the template's first line covers it too.
|
|
1382
|
+
const templateStart = diag.data
|
|
1383
|
+
?.templateStart;
|
|
1384
|
+
if (typeof templateStart === "number") {
|
|
1385
|
+
const templateLine = document.positionAt(templateStart).line;
|
|
1386
|
+
if (templateLine !== line &&
|
|
1387
|
+
isDiagnosticIgnored(templateLine, code, ignoreRanges))
|
|
1388
|
+
return false;
|
|
1389
|
+
}
|
|
1390
|
+
return true;
|
|
1128
1391
|
});
|
|
1129
1392
|
}
|
|
1130
1393
|
export function createCompletions(document, position, snapshot) {
|
|
@@ -1249,7 +1512,7 @@ export function createCompletions(document, position, snapshot) {
|
|
|
1249
1512
|
{
|
|
1250
1513
|
label: "bascik-stream",
|
|
1251
1514
|
detail: "Bascik server-side streaming script block",
|
|
1252
|
-
documentation: "Executes in Node.js per request on production servers. Streams chunked HTML responses to the client as data becomes available.",
|
|
1515
|
+
documentation: "Executes in Node.js per request on production and dev servers. Streams chunked HTML responses to the client as data becomes available.",
|
|
1253
1516
|
insertText: `<script data-bascik-stream>\n export default async function (request, context, { signal }) {\n return \`$0\`;\n }\n</script>`,
|
|
1254
1517
|
},
|
|
1255
1518
|
];
|
|
@@ -1380,10 +1643,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
|
|
|
1380
1643
|
if (offset < blockStart || offset > blockEnd)
|
|
1381
1644
|
continue;
|
|
1382
1645
|
const attrs = parseScriptOpenTagAttributes(openTag);
|
|
1383
|
-
if (!attrs
|
|
1384
|
-
!attrs.has("data-bascik-build-once") &&
|
|
1385
|
-
!attrs.has("data-bascik-server") &&
|
|
1386
|
-
!attrs.has("data-bascik-routes")) {
|
|
1646
|
+
if (!hasModuleResolvingDirective(attrs)) {
|
|
1387
1647
|
return undefined;
|
|
1388
1648
|
}
|
|
1389
1649
|
const baseDir = path.dirname(fsPath);
|
|
@@ -1408,7 +1668,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
|
|
|
1408
1668
|
start: document.positionAt(valueStart),
|
|
1409
1669
|
end: document.positionAt(valueEnd),
|
|
1410
1670
|
},
|
|
1411
|
-
targetUri:
|
|
1671
|
+
targetUri: pathToFileURL(resolved).toString(),
|
|
1412
1672
|
targetRange: {
|
|
1413
1673
|
start: { line: 0, character: 0 },
|
|
1414
1674
|
end: { line: 0, character: 0 },
|
|
@@ -1433,7 +1693,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
|
|
|
1433
1693
|
start: document.positionAt(openTagEnd + start),
|
|
1434
1694
|
end: document.positionAt(openTagEnd + end),
|
|
1435
1695
|
},
|
|
1436
|
-
targetUri:
|
|
1696
|
+
targetUri: pathToFileURL(resolved).toString(),
|
|
1437
1697
|
targetRange: {
|
|
1438
1698
|
start: { line: 0, character: 0 },
|
|
1439
1699
|
end: { line: 0, character: 0 },
|
|
@@ -1469,7 +1729,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
|
|
|
1469
1729
|
start: { line: position.line, character: start },
|
|
1470
1730
|
end: { line: position.line, character: end },
|
|
1471
1731
|
},
|
|
1472
|
-
targetUri:
|
|
1732
|
+
targetUri: pathToFileURL(componentPath).toString(),
|
|
1473
1733
|
targetRange: {
|
|
1474
1734
|
start: { line: 0, character: 0 },
|
|
1475
1735
|
end: { line: 0, character: 0 },
|
|
@@ -1527,6 +1787,269 @@ export function buildAutoFixEdit(document, diag) {
|
|
|
1527
1787
|
}
|
|
1528
1788
|
return undefined;
|
|
1529
1789
|
}
|
|
1790
|
+
const sameEdits = (action, wrap) => JSON.stringify(Object.values(action.edit?.changes ?? {})[0]) ===
|
|
1791
|
+
JSON.stringify(wrap.edits);
|
|
1792
|
+
/**
|
|
1793
|
+
* `body` with string contents, comments and template-literal text replaced
|
|
1794
|
+
* by spaces (offsets kept), and the code inside template holes kept.
|
|
1795
|
+
*/
|
|
1796
|
+
function codeOnly(body) {
|
|
1797
|
+
const out = body.split("");
|
|
1798
|
+
const blank = (from, to) => {
|
|
1799
|
+
for (let k = from; k < to && k < out.length; k++)
|
|
1800
|
+
if (out[k] !== "\n")
|
|
1801
|
+
out[k] = " ";
|
|
1802
|
+
};
|
|
1803
|
+
// A stack of open template literals; each entry is the brace depth of
|
|
1804
|
+
// the hole code that the template sits in.
|
|
1805
|
+
const holes = [];
|
|
1806
|
+
let depth = 0;
|
|
1807
|
+
let i = 0;
|
|
1808
|
+
const template = (from) => {
|
|
1809
|
+
// Scan template text from `from` (just past ` or }) to the end or `${`.
|
|
1810
|
+
let k = from;
|
|
1811
|
+
while (k < body.length) {
|
|
1812
|
+
if (body[k] === "\\")
|
|
1813
|
+
k += 2;
|
|
1814
|
+
else if (body[k] === "`") {
|
|
1815
|
+
blank(from, k);
|
|
1816
|
+
i = k + 1;
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
else if (body[k] === "$" && body[k + 1] === "{") {
|
|
1820
|
+
blank(from, k);
|
|
1821
|
+
holes.push(depth);
|
|
1822
|
+
depth = 0;
|
|
1823
|
+
i = k + 2;
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
else
|
|
1827
|
+
k++;
|
|
1828
|
+
}
|
|
1829
|
+
blank(from, body.length);
|
|
1830
|
+
i = body.length;
|
|
1831
|
+
};
|
|
1832
|
+
while (i < body.length) {
|
|
1833
|
+
const c = body[i];
|
|
1834
|
+
if (c === "/" && body[i + 1] === "/") {
|
|
1835
|
+
const nl = body.indexOf("\n", i);
|
|
1836
|
+
const end = nl === -1 ? body.length : nl;
|
|
1837
|
+
blank(i, end);
|
|
1838
|
+
i = end;
|
|
1839
|
+
}
|
|
1840
|
+
else if (c === "/" && body[i + 1] === "*") {
|
|
1841
|
+
const close = body.indexOf("*/", i + 2);
|
|
1842
|
+
const end = close === -1 ? body.length : close + 2;
|
|
1843
|
+
blank(i, end);
|
|
1844
|
+
i = end;
|
|
1845
|
+
}
|
|
1846
|
+
else if (c === "'" || c === '"') {
|
|
1847
|
+
let k = i + 1;
|
|
1848
|
+
while (k < body.length && body[k] !== c && body[k] !== "\n")
|
|
1849
|
+
k += body[k] === "\\" ? 2 : 1;
|
|
1850
|
+
blank(i + 1, k);
|
|
1851
|
+
i = k + 1;
|
|
1852
|
+
}
|
|
1853
|
+
else if (c === "`")
|
|
1854
|
+
template(i + 1);
|
|
1855
|
+
else if (c === "{") {
|
|
1856
|
+
depth++;
|
|
1857
|
+
i++;
|
|
1858
|
+
}
|
|
1859
|
+
else if (c === "}") {
|
|
1860
|
+
if (depth === 0 && holes.length > 0) {
|
|
1861
|
+
depth = holes.pop();
|
|
1862
|
+
template(i + 1);
|
|
1863
|
+
}
|
|
1864
|
+
else {
|
|
1865
|
+
if (depth > 0)
|
|
1866
|
+
depth--;
|
|
1867
|
+
i++;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
else
|
|
1871
|
+
i++;
|
|
1872
|
+
}
|
|
1873
|
+
return out.join("");
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* The quick fix for server-script-unescaped-markup: put `html` before the
|
|
1877
|
+
* template's backtick and import it from @bascik/bascik/html (after the
|
|
1878
|
+
* script's last import, or merged into an existing import from the module).
|
|
1879
|
+
* When the name html is already used in the script's code (a variable, a
|
|
1880
|
+
* parameter, another import), it imports `html as safeHtml` instead, so the
|
|
1881
|
+
* fix never tags with a binding that means something else; when safeHtml is
|
|
1882
|
+
* taken too, or a hole sits where html would throw, it is not offered.
|
|
1883
|
+
*/
|
|
1884
|
+
export function buildWrapHtmlEdits(document, diag) {
|
|
1885
|
+
if (diag.code !== "server-script-unescaped-markup")
|
|
1886
|
+
return undefined;
|
|
1887
|
+
const data = diag.data;
|
|
1888
|
+
if (!data || !data.fixable)
|
|
1889
|
+
return undefined;
|
|
1890
|
+
const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
|
|
1891
|
+
if (!plan)
|
|
1892
|
+
return undefined;
|
|
1893
|
+
const backtick = document.positionAt(data.templateStart);
|
|
1894
|
+
return {
|
|
1895
|
+
title: "Wrap template in html`...`",
|
|
1896
|
+
edits: [
|
|
1897
|
+
...plan.edits,
|
|
1898
|
+
{ range: { start: backtick, end: backtick }, newText: plan.local },
|
|
1899
|
+
],
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* The local name to use for `exportName` from @bascik/bascik/html in the
|
|
1904
|
+
* script between `bodyStart` and `bodyEnd`, and the edits that import it:
|
|
1905
|
+
* after the script's last import, or merged into an existing import from
|
|
1906
|
+
* the module. When the name is already used in the script's code (a
|
|
1907
|
+
* variable, a parameter, another import), it imports `exportName as alias`
|
|
1908
|
+
* instead, so the edit never uses a binding that means something else;
|
|
1909
|
+
* when the alias is taken too, there is no plan. With `onlyAsTagOrCall`, an
|
|
1910
|
+
* existing import of the name counts only when the name is never shadowed.
|
|
1911
|
+
*/
|
|
1912
|
+
function planHtmlImport(document, bodyStart, bodyEnd, exportName, alias, onlyAsTagOrCall) {
|
|
1913
|
+
const text = document.getText();
|
|
1914
|
+
const body = text.slice(bodyStart, bodyEnd);
|
|
1915
|
+
const at = (offset) => document.positionAt(bodyStart + offset);
|
|
1916
|
+
const edits = [];
|
|
1917
|
+
const existing = /\bimport\s*\{([^}]*)\}\s*from\s*["']@bascik\/bascik\/html["']/.exec(body);
|
|
1918
|
+
// Identifiers in code only: strings, comments and template text blanked,
|
|
1919
|
+
// and the import from the module left out, so `<html>` or "html" is no
|
|
1920
|
+
// clash but a parameter, a variable or another import named html is.
|
|
1921
|
+
const code = codeOnly(existing
|
|
1922
|
+
? body.slice(0, existing.index) +
|
|
1923
|
+
" ".repeat(existing[0].length) +
|
|
1924
|
+
body.slice((existing.index ?? 0) + existing[0].length)
|
|
1925
|
+
: body);
|
|
1926
|
+
const word = (name) => `(?<![\\w$.])${escapeRegExp(name)}(?![\\w$])`;
|
|
1927
|
+
const uses = (name) => new RegExp(word(name)).test(code);
|
|
1928
|
+
// An imported name is safe to tag with when it is only ever a tag or a
|
|
1929
|
+
// callee: anywhere else (a parameter, a variable, a function declaration)
|
|
1930
|
+
// it may be shadowed.
|
|
1931
|
+
const onlyTagOrCall = (name) => !new RegExp(`(?<!\\bfunction\\s*)${word(name)}(?!\\s*[\`(])`).test(code) &&
|
|
1932
|
+
!new RegExp(`\\bfunction\\s*${word(name)}`).test(code);
|
|
1933
|
+
let local;
|
|
1934
|
+
let specifier;
|
|
1935
|
+
const entries = existing
|
|
1936
|
+
? existing[1]
|
|
1937
|
+
.split(",")
|
|
1938
|
+
.map((e) => e.trim())
|
|
1939
|
+
.filter(Boolean)
|
|
1940
|
+
: [];
|
|
1941
|
+
// Names that are not identifiers (a half-typed `html as h(`) bind nothing.
|
|
1942
|
+
const bound = entries
|
|
1943
|
+
.map(parseImportSpecifier)
|
|
1944
|
+
.filter((parts) => parts?.[0] === exportName)
|
|
1945
|
+
.map((parts) => parts[1]);
|
|
1946
|
+
local = bound.find((name) => !onlyAsTagOrCall || onlyTagOrCall(name));
|
|
1947
|
+
if (local === undefined) {
|
|
1948
|
+
if (!bound.includes(exportName) && !uses(exportName)) {
|
|
1949
|
+
local = exportName;
|
|
1950
|
+
specifier = exportName;
|
|
1951
|
+
}
|
|
1952
|
+
else if (!bound.includes(alias) && !uses(alias)) {
|
|
1953
|
+
local = alias;
|
|
1954
|
+
specifier = `${exportName} as ${alias}`;
|
|
1955
|
+
}
|
|
1956
|
+
else
|
|
1957
|
+
return undefined;
|
|
1958
|
+
}
|
|
1959
|
+
if (specifier !== undefined && existing) {
|
|
1960
|
+
const open = (existing.index ?? 0) + existing[0].indexOf("{") + 1;
|
|
1961
|
+
const close = open + existing[1].length;
|
|
1962
|
+
edits.push({
|
|
1963
|
+
range: { start: at(open), end: at(close) },
|
|
1964
|
+
newText: ` ${[...entries, specifier].join(", ")} `,
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
else if (specifier !== undefined) {
|
|
1968
|
+
const statement = `import { ${specifier} } from "@bascik/bascik/html";`;
|
|
1969
|
+
const imports = [
|
|
1970
|
+
...body.matchAll(/^([ \t]*)import\b[^;]*?from\s*["'][^"']+["'][ \t]*;?[ \t]*$/gm),
|
|
1971
|
+
];
|
|
1972
|
+
const last = imports[imports.length - 1];
|
|
1973
|
+
if (last) {
|
|
1974
|
+
const end = (last.index ?? 0) + last[0].length;
|
|
1975
|
+
edits.push({
|
|
1976
|
+
range: { start: at(end), end: at(end) },
|
|
1977
|
+
newText: `\n${last[1]}${statement}`,
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
else {
|
|
1981
|
+
const first = /^([ \t]*)\S/m.exec(body);
|
|
1982
|
+
const lineStart = first?.index ?? 0;
|
|
1983
|
+
edits.push({
|
|
1984
|
+
range: { start: at(lineStart), end: at(lineStart) },
|
|
1985
|
+
newText: `${first?.[1] ?? ""}${statement}\n`,
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
return { local, edits };
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* The code actions for hand-written-html-escaper. A one-return escaper with
|
|
1993
|
+
* one plain parameter gets "Make NAME() call esc()": its body becomes a call
|
|
1994
|
+
* to esc() from @bascik/bascik/html (imported, aliased when the name esc is
|
|
1995
|
+
* taken, as it is when the escaper itself is called esc). The callers keep
|
|
1996
|
+
* working: esc() escapes the same characters and quotes as well. Rewriting
|
|
1997
|
+
* the callers to html`...` is not automatic, since a template's value then
|
|
1998
|
+
* changes from a string to an html value. Every other escaper (a lookup
|
|
1999
|
+
* object, a longer body) gets "Import html from @bascik/bascik/html" when
|
|
2000
|
+
* the script does not import it yet, as a start on rewriting by hand.
|
|
2001
|
+
*/
|
|
2002
|
+
export function buildEscaperActions(document, diag) {
|
|
2003
|
+
if (diag.code !== HAND_WRITTEN_ESCAPER_RULE)
|
|
2004
|
+
return [];
|
|
2005
|
+
const data = diag.data;
|
|
2006
|
+
if (!data)
|
|
2007
|
+
return [];
|
|
2008
|
+
const name = document.getText(diag.range);
|
|
2009
|
+
if (data.delegate) {
|
|
2010
|
+
const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "esc", "escapeValue", true);
|
|
2011
|
+
if (plan) {
|
|
2012
|
+
const { start, end, param, block } = data.delegate;
|
|
2013
|
+
const startPos = document.positionAt(start);
|
|
2014
|
+
const lineStart = document.offsetAt({
|
|
2015
|
+
line: startPos.line,
|
|
2016
|
+
character: 0,
|
|
2017
|
+
});
|
|
2018
|
+
const indent = /^[ \t]*/.exec(document.getText().slice(lineStart, start))?.[0] ?? "";
|
|
2019
|
+
const call = `${plan.local}(${param})`;
|
|
2020
|
+
return [
|
|
2021
|
+
{
|
|
2022
|
+
title: name === "default"
|
|
2023
|
+
? "Make the default export call esc() from @bascik/bascik/html"
|
|
2024
|
+
: `Make ${name}() call esc() from @bascik/bascik/html`,
|
|
2025
|
+
preferred: true,
|
|
2026
|
+
edits: [
|
|
2027
|
+
...plan.edits,
|
|
2028
|
+
{
|
|
2029
|
+
range: { start: startPos, end: document.positionAt(end) },
|
|
2030
|
+
newText: block
|
|
2031
|
+
? `{\n${indent} return ${call};\n${indent}}`
|
|
2032
|
+
: call,
|
|
2033
|
+
},
|
|
2034
|
+
],
|
|
2035
|
+
},
|
|
2036
|
+
];
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
const body = document.getText().slice(data.bodyStart, data.bodyEnd);
|
|
2040
|
+
if (/\bimport\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s*["']@bascik\/bascik\/html["']/.test(body))
|
|
2041
|
+
return [];
|
|
2042
|
+
const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
|
|
2043
|
+
if (!plan || plan.edits.length === 0)
|
|
2044
|
+
return [];
|
|
2045
|
+
return [
|
|
2046
|
+
{
|
|
2047
|
+
title: "Import html from @bascik/bascik/html to build markup safely",
|
|
2048
|
+
preferred: false,
|
|
2049
|
+
edits: plan.edits,
|
|
2050
|
+
},
|
|
2051
|
+
];
|
|
2052
|
+
}
|
|
1530
2053
|
export function createCodeActions(document, range, diagnostics, snapshot, fsPath) {
|
|
1531
2054
|
const activeDiagnostics = diagnostics.length > 0
|
|
1532
2055
|
? diagnostics
|
|
@@ -1537,6 +2060,33 @@ export function createCodeActions(document, range, diagnostics, snapshot, fsPath
|
|
|
1537
2060
|
for (const diag of activeDiagnostics) {
|
|
1538
2061
|
if (!rangesOverlap(diag.range, range))
|
|
1539
2062
|
continue;
|
|
2063
|
+
// Editor only: wrapping changes the value from a string to SafeHtml, so
|
|
2064
|
+
// `bascik --check --fix` (applyAutoFixes) never applies it.
|
|
2065
|
+
const escaperActions = buildEscaperActions(document, diag);
|
|
2066
|
+
if (escaperActions.length > 0) {
|
|
2067
|
+
for (const action of escaperActions)
|
|
2068
|
+
actions.push({
|
|
2069
|
+
title: action.title,
|
|
2070
|
+
kind: CodeActionKind.QuickFix,
|
|
2071
|
+
diagnostics: [diag],
|
|
2072
|
+
isPreferred: action.preferred,
|
|
2073
|
+
edit: { changes: { [document.uri]: action.edits } },
|
|
2074
|
+
});
|
|
2075
|
+
continue;
|
|
2076
|
+
}
|
|
2077
|
+
const wrap = buildWrapHtmlEdits(document, diag);
|
|
2078
|
+
if (wrap) {
|
|
2079
|
+
if (actions.some((a) => a.title === wrap.title && sameEdits(a, wrap)))
|
|
2080
|
+
continue;
|
|
2081
|
+
actions.push({
|
|
2082
|
+
title: wrap.title,
|
|
2083
|
+
kind: CodeActionKind.QuickFix,
|
|
2084
|
+
diagnostics: [diag],
|
|
2085
|
+
isPreferred: true,
|
|
2086
|
+
edit: { changes: { [document.uri]: wrap.edits } },
|
|
2087
|
+
});
|
|
2088
|
+
continue;
|
|
2089
|
+
}
|
|
1540
2090
|
const fix = buildAutoFixEdit(document, diag);
|
|
1541
2091
|
if (!fix)
|
|
1542
2092
|
continue;
|