@bascik/language-server 0.1.0-rc.5 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +74 -30
  2. package/dist/analyzer.d.ts +75 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/analyzer.js +727 -76
  5. package/dist/analyzer.js.map +1 -1
  6. package/dist/api-rules.d.ts +7 -0
  7. package/dist/api-rules.d.ts.map +1 -1
  8. package/dist/api-rules.js +282 -17
  9. package/dist/api-rules.js.map +1 -1
  10. package/dist/bin-args.d.ts +11 -0
  11. package/dist/bin-args.d.ts.map +1 -0
  12. package/dist/bin-args.js +21 -0
  13. package/dist/bin-args.js.map +1 -0
  14. package/dist/bin.js +17 -5
  15. package/dist/bin.js.map +1 -1
  16. package/dist/check.d.ts +14 -1
  17. package/dist/check.d.ts.map +1 -1
  18. package/dist/check.js +116 -10
  19. package/dist/check.js.map +1 -1
  20. package/dist/cli.d.ts.map +1 -1
  21. package/dist/cli.js +27 -8
  22. package/dist/cli.js.map +1 -1
  23. package/dist/compatibility-rules.json +21 -3
  24. package/dist/component-metadata.d.ts.map +1 -1
  25. package/dist/component-metadata.js +3 -1
  26. package/dist/component-metadata.js.map +1 -1
  27. package/dist/component-usages.d.ts +47 -0
  28. package/dist/component-usages.d.ts.map +1 -0
  29. package/dist/component-usages.js +495 -0
  30. package/dist/component-usages.js.map +1 -0
  31. package/dist/config-reader.d.ts +41 -0
  32. package/dist/config-reader.d.ts.map +1 -0
  33. package/dist/config-reader.js +461 -0
  34. package/dist/config-reader.js.map +1 -0
  35. package/dist/config.d.ts +10 -0
  36. package/dist/config.d.ts.map +1 -1
  37. package/dist/config.js +25 -30
  38. package/dist/config.js.map +1 -1
  39. package/dist/css-brace-balance.d.ts +33 -0
  40. package/dist/css-brace-balance.d.ts.map +1 -0
  41. package/dist/css-brace-balance.js +99 -0
  42. package/dist/css-brace-balance.js.map +1 -0
  43. package/dist/hand-written-escaper.d.ts +35 -0
  44. package/dist/hand-written-escaper.d.ts.map +1 -0
  45. package/dist/hand-written-escaper.js +739 -0
  46. package/dist/hand-written-escaper.js.map +1 -0
  47. package/dist/module-specifiers.d.ts +25 -0
  48. package/dist/module-specifiers.d.ts.map +1 -1
  49. package/dist/module-specifiers.js +234 -165
  50. package/dist/module-specifiers.js.map +1 -1
  51. package/dist/name-groups.d.ts +36 -0
  52. package/dist/name-groups.d.ts.map +1 -0
  53. package/dist/name-groups.js +198 -0
  54. package/dist/name-groups.js.map +1 -0
  55. package/dist/plain-holes.d.ts +116 -0
  56. package/dist/plain-holes.d.ts.map +1 -0
  57. package/dist/plain-holes.js +1970 -0
  58. package/dist/plain-holes.js.map +1 -0
  59. package/dist/preserved-targets.d.ts +50 -0
  60. package/dist/preserved-targets.d.ts.map +1 -0
  61. package/dist/preserved-targets.js +358 -0
  62. package/dist/preserved-targets.js.map +1 -0
  63. package/dist/project.d.ts +68 -1
  64. package/dist/project.d.ts.map +1 -1
  65. package/dist/project.js +157 -8
  66. package/dist/project.js.map +1 -1
  67. package/dist/references.d.ts +47 -0
  68. package/dist/references.d.ts.map +1 -0
  69. package/dist/references.js +241 -0
  70. package/dist/references.js.map +1 -0
  71. package/dist/script-modules.d.ts +60 -0
  72. package/dist/script-modules.d.ts.map +1 -0
  73. package/dist/script-modules.js +382 -0
  74. package/dist/script-modules.js.map +1 -0
  75. package/dist/server-script-rules.d.ts +94 -1
  76. package/dist/server-script-rules.d.ts.map +1 -1
  77. package/dist/server-script-rules.js +2572 -230
  78. package/dist/server-script-rules.js.map +1 -1
  79. package/dist/server-script-templates.d.ts +250 -0
  80. package/dist/server-script-templates.d.ts.map +1 -0
  81. package/dist/server-script-templates.js +1685 -0
  82. package/dist/server-script-templates.js.map +1 -0
  83. package/dist/server.d.ts +191 -3
  84. package/dist/server.d.ts.map +1 -1
  85. package/dist/server.js +822 -50
  86. package/dist/server.js.map +1 -1
  87. package/dist/start.d.ts +10 -1
  88. package/dist/start.d.ts.map +1 -1
  89. package/dist/start.js +14 -2
  90. package/dist/start.js.map +1 -1
  91. package/dist/string-typed-flow.d.ts +26 -0
  92. package/dist/string-typed-flow.d.ts.map +1 -0
  93. package/dist/string-typed-flow.js +496 -0
  94. package/dist/string-typed-flow.js.map +1 -0
  95. package/dist/typescript-blocks.d.ts +205 -0
  96. package/dist/typescript-blocks.d.ts.map +1 -0
  97. package/dist/typescript-blocks.js +464 -0
  98. package/dist/typescript-blocks.js.map +1 -0
  99. package/dist/typescript-editor-mode.d.ts +28 -0
  100. package/dist/typescript-editor-mode.d.ts.map +1 -0
  101. package/dist/typescript-editor-mode.js +161 -0
  102. package/dist/typescript-editor-mode.js.map +1 -0
  103. package/dist/typescript-engine.d.ts +115 -0
  104. package/dist/typescript-engine.d.ts.map +1 -0
  105. package/dist/typescript-engine.js +286 -0
  106. package/dist/typescript-engine.js.map +1 -0
  107. package/dist/typescript-features.d.ts +136 -0
  108. package/dist/typescript-features.d.ts.map +1 -0
  109. package/dist/typescript-features.js +374 -0
  110. package/dist/typescript-features.js.map +1 -0
  111. package/dist/typescript-loader.d.ts +55 -0
  112. package/dist/typescript-loader.d.ts.map +1 -0
  113. package/dist/typescript-loader.js +202 -0
  114. package/dist/typescript-loader.js.map +1 -0
  115. package/dist/typescript-lsp.d.ts +8 -0
  116. package/dist/typescript-lsp.d.ts.map +1 -0
  117. package/dist/typescript-lsp.js +115 -0
  118. package/dist/typescript-lsp.js.map +1 -0
  119. package/dist/typescript-service.d.ts +350 -0
  120. package/dist/typescript-service.d.ts.map +1 -0
  121. package/dist/typescript-service.js +1465 -0
  122. package/dist/typescript-service.js.map +1 -0
  123. package/dist/typescript-worker.d.ts +11 -0
  124. package/dist/typescript-worker.d.ts.map +1 -0
  125. package/dist/typescript-worker.js +107 -0
  126. package/dist/typescript-worker.js.map +1 -0
  127. package/package.json +34 -12
package/dist/analyzer.js CHANGED
@@ -4,13 +4,19 @@ import { pathToFileURL } from "node:url";
4
4
  import { DiagnosticSeverity, CompletionItemKind, MarkupKind, CodeActionKind, } from "vscode-languageserver";
5
5
  import { isInsideComponentRoots, normalizeComponentName, htmlSuppliesComponentProp, } from "./project.js";
6
6
  import { findCompatibilityMatches } from "./rules.js";
7
+ import { cssBraceImbalanceMessage, findCssBraceImbalance, } from "./css-brace-balance.js";
8
+ import { collectCssClasses, collectPreservedTargets, findPreservedCssTargets, findPreservedJsTargets, } from "./preserved-targets.js";
7
9
  import { analyzeApiRouteSource } from "./api-rules.js";
8
10
  import { findComponentStructureProblems, isKnownBascikAttribute, isKnownBuildValue, unknownBascikAttributeMessage, unknownDirectiveValueMessage, } from "./directive-rules.js";
9
11
  import { findModuleSpecifiers } from "./module-specifiers.js";
10
- import { analyzeServerScriptSource } from "./server-script-rules.js";
12
+ import { analyzeServerScriptSource, } from "./server-script-rules.js";
13
+ import { HAND_WRITTEN_ESCAPER_RULE } from "./hand-written-escaper.js";
14
+ import { normalizeModulePath, scriptModulesOf, } from "./script-modules.js";
15
+ import { parseImportSpecifier } from "./server-script-templates.js";
11
16
  import { analyzeComponentSource, } from "./component-metadata.js";
12
17
  import { parseIgnoreDirectives, isDiagnosticIgnored, } from "./ignore-comments.js";
13
18
  import { loadExtensionConfig } from "./config.js";
19
+ import { countInstancesOnPages, findNameGroups, sharedNameGroupMessage, } from "./name-groups.js";
14
20
  export const BUILT_IN_HTML_ELEMENTS = new Set([
15
21
  "a",
16
22
  "abbr",
@@ -143,12 +149,12 @@ export const SCRIPT_DIRECTIVES = [
143
149
  {
144
150
  name: "data-bascik-server",
145
151
  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.",
152
+ 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
153
  },
148
154
  {
149
155
  name: "data-bascik-stream",
150
156
  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.",
157
+ 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
158
  },
153
159
  ];
154
160
  export const SCRIPT_BLOCK_RE = /(<script(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/script(?:[\t\n\f\r /][^>]*)?>/gi;
@@ -158,24 +164,45 @@ export function maskHtmlRawTextContents(html) {
158
164
  export function escapeRegExp(value) {
159
165
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
160
166
  }
167
+ /** Lookahead for the end of a tag name, as in the compiler: HTML whitespace, `/` or `>`. */
168
+ const TAG_NAME_END = "(?=[\\t\\n\\f\\r />])";
161
169
  export function findMatchingClose(html, tagName, contentStart) {
162
170
  const tn = tagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
163
- const openRe = new RegExp(`<${tn}[\\s>]`, "gi");
164
- const closeRe = new RegExp(`<\\/${tn}>`, "gi");
171
+ // Tag names end at HTML whitespace, `/` or `>`, and an end tag may carry whitespace or junk before
172
+ // its `>`, the shapes the compiler accepts (component-tags.ts, component-slots.ts).
173
+ // The end tag runs to the first `>` after its name, so it is found as the name, then indexOf(">"): a
174
+ // regex `[^>]*>` rescanned the rest of the document from each `</name` with no `>` (quadratic).
175
+ const openRe = new RegExp(`<${tn}${TAG_NAME_END}`, "gi");
176
+ const closeNameRe = new RegExp(`<\\/${tn}${TAG_NAME_END}`, "gi");
177
+ const closeFrom = (from) => {
178
+ closeNameRe.lastIndex = from;
179
+ const name = closeNameRe.exec(html);
180
+ if (!name)
181
+ return null;
182
+ // No `>` after this end tag means none after any later one either.
183
+ const gt = html.indexOf(">", name.index + name[0].length);
184
+ return gt === -1 ? null : { index: name.index, end: gt + 1 };
185
+ };
186
+ // The next open and end tag at or after `pos`, kept while `pos` has not passed them, so nested or
187
+ // self-closing tags do not search again for the same end tag each time.
188
+ let openMatch;
189
+ let closeMatch;
165
190
  let depth = 1;
166
191
  let pos = contentStart;
167
192
  while (pos < html.length) {
168
- openRe.lastIndex = pos;
169
- closeRe.lastIndex = pos;
170
- const openMatch = openRe.exec(html);
171
- const closeMatch = closeRe.exec(html);
193
+ if (closeMatch === undefined || (closeMatch && closeMatch.index < pos))
194
+ closeMatch = closeFrom(pos);
172
195
  if (!closeMatch)
173
196
  return -1;
197
+ if (openMatch === undefined || (openMatch && openMatch.index < pos)) {
198
+ openRe.lastIndex = pos;
199
+ openMatch = openRe.exec(html);
200
+ }
174
201
  if (!openMatch || closeMatch.index < openMatch.index) {
175
202
  depth--;
176
203
  if (depth === 0)
177
204
  return closeMatch.index;
178
- pos = closeMatch.index + closeMatch[0].length;
205
+ pos = closeMatch.end;
179
206
  }
180
207
  else {
181
208
  let inDoubleQuote = false;
@@ -224,7 +251,7 @@ const isTagNameChar = (code) => isTagNameStart(code) ||
224
251
  * so its result depends only on where the scan stands; `tagEndFrom` remembers
225
252
  * it per position and no position is scanned twice.
226
253
  */
227
- function* scanTags(source) {
254
+ function* scanTags(source, from = 0) {
228
255
  const length = source.length;
229
256
  // 0 = not scanned yet, -1 = no closing `>`, otherwise the index after `>`.
230
257
  const tagEndFrom = new Int32Array(length + 1);
@@ -258,7 +285,7 @@ function* scanTags(source) {
258
285
  tagEndFrom[index] = end;
259
286
  return end;
260
287
  };
261
- let cursor = 0;
288
+ let cursor = from;
262
289
  while (cursor < length) {
263
290
  const open = source.indexOf("<", cursor);
264
291
  if (open < 0)
@@ -281,33 +308,77 @@ function* scanTags(source) {
281
308
  name: source.slice(nameStart, nameEnd),
282
309
  closing,
283
310
  text: source.slice(open, end),
311
+ start: open,
312
+ end,
284
313
  };
285
314
  cursor = end;
286
315
  }
287
316
  }
288
317
  export function findNearestParentComponent(source, componentMap) {
289
- const stack = [];
290
- for (const tag of scanTags(source)) {
318
+ return findNearestParentComponents(source, [source.length], componentMap)[0];
319
+ }
320
+ /**
321
+ * For each offset (ascending), the component that `findNearestParentComponent(source.slice(0, offset))`
322
+ * finds, from one scan of `source`. Rescanning the prefix for every offset was quadratic in the number of
323
+ * offsets (one per `data-bascik-slot` tag).
324
+ *
325
+ * The open-element stack carries, per entry, the nearest component at or below it, so each answer is
326
+ * read in constant time. A tag that starts before an offset but ends after it is not a tag in that prefix
327
+ * (its `>` is cut off), so for that offset the prefix scan is continued from just after its `<`, exactly
328
+ * as the prefix scan would, on a copy of the stack.
329
+ */
330
+ export function findNearestParentComponents(source, offsets, componentMap) {
331
+ const apply = (stack, nearest, tag) => {
291
332
  const name = tag.name.toLowerCase();
292
333
  if (tag.closing) {
293
334
  const matchingIndex = stack.lastIndexOf(name);
294
- if (matchingIndex >= 0)
295
- stack.splice(matchingIndex);
335
+ if (matchingIndex >= 0) {
336
+ stack.length = matchingIndex;
337
+ nearest.length = matchingIndex;
338
+ }
296
339
  }
297
340
  else if (!/\/\s*>$/.test(tag.text)) {
298
341
  stack.push(name);
342
+ nearest.push(componentMap.has(name) ? name : nearest.at(-1));
343
+ }
344
+ };
345
+ const stack = [];
346
+ const nearest = [];
347
+ const tags = scanTags(source);
348
+ let pending = tags.next();
349
+ const results = [];
350
+ for (const offset of offsets) {
351
+ while (!pending.done && pending.value.end <= offset) {
352
+ apply(stack, nearest, pending.value);
353
+ pending = tags.next();
354
+ }
355
+ if (!pending.done && pending.value.start < offset) {
356
+ // The offset sits inside what the full scan reads as one tag (an unclosed quote can make it long),
357
+ // so the tags before it are read from the source cut at the offset. Each such offset rescans from
358
+ // that tag's start: quadratic only when many slot tags hide inside one long run-on tag, which
359
+ // markup does not do, so the cost is accepted rather than memoized.
360
+ const prefixStack = stack.slice();
361
+ const prefixNearest = nearest.slice();
362
+ for (const tag of scanTags(source.slice(0, offset), pending.value.start + 1))
363
+ apply(prefixStack, prefixNearest, tag);
364
+ results.push(prefixNearest.at(-1));
365
+ }
366
+ else {
367
+ results.push(nearest.at(-1));
299
368
  }
300
369
  }
301
- return stack.reverse().find((name) => componentMap.has(name));
370
+ return results;
302
371
  }
303
372
  export function parseScriptOpenTagAttributes(openTag) {
304
373
  const attrs = new Map();
305
374
  const insideTag = openTag.replace(/^<script\b/i, "").replace(/>$/, "");
306
- const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
375
+ // An unquoted value runs to whitespace (quotes, `=` and backticks
376
+ // included), and the first occurrence of a name wins, as in the tokenizer.
377
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
307
378
  let match;
308
379
  while ((match = attrRe.exec(insideTag)) !== null) {
309
380
  const name = match[1]?.toLowerCase();
310
- if (!name)
381
+ if (!name || attrs.has(name))
311
382
  continue;
312
383
  const value = match[2] ?? match[3] ?? match[4];
313
384
  attrs.set(name, value === undefined ? true : value);
@@ -319,11 +390,14 @@ export function parseScriptOpenTagAttributes(openTag) {
319
390
  * maps to `""`, as the DOM reports it. The first occurrence of a name wins, as
320
391
  * in the HTML tokenizer, and text inside a quoted value is never read as an
321
392
  * attribute. An unquoted value keeps its slashes; a trailing `/>` ends it.
393
+ *
394
+ * @internal Exported for the attribute tokenizer agreement test
395
+ * (skills-tests/tests/attribute-tokenizer-agreement.test.ts).
322
396
  */
323
- function readOpenTagAttributes(openTag) {
397
+ export function readOpenTagAttributes(openTag) {
324
398
  const attrs = new Map();
325
399
  const insideTag = openTag.replace(/^<[^\s/>]+/, "").replace(/\/?>$/, "");
326
- const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
400
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
327
401
  let match;
328
402
  while ((match = attrRe.exec(insideTag)) !== null) {
329
403
  const name = match[1].toLowerCase();
@@ -353,12 +427,22 @@ export function leadingSlashSpecifierMessage(specifier) {
353
427
  `Use '@/${rest}' to resolve against scripts.importRoot, ` +
354
428
  `or './${rest}' to resolve relative to this file.`);
355
429
  }
430
+ /**
431
+ * The script directives that run in Node and resolve `./`, `../` and `@/` specifiers against the
432
+ * file and `scripts.importRoot`. Leading-slash diagnostics and Go to Definition share this list.
433
+ */
434
+ const MODULE_RESOLVING_DIRECTIVES = [
435
+ "data-bascik-build",
436
+ "data-bascik-build-once",
437
+ "data-bascik-server",
438
+ "data-bascik-routes",
439
+ "data-bascik-stream",
440
+ ];
441
+ function hasModuleResolvingDirective(attrs) {
442
+ return MODULE_RESOLVING_DIRECTIVES.some((name) => attrs.has(name));
443
+ }
356
444
  export function collectLeadingSlashDiagnostics(document, openTag, scriptBody, blockStart, attrs) {
357
- if (!attrs.has("data-bascik-build") &&
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")) {
445
+ if (!hasModuleResolvingDirective(attrs)) {
362
446
  return [];
363
447
  }
364
448
  const out = [];
@@ -439,7 +523,72 @@ export function completionReplacementRange(document, position) {
439
523
  end: position,
440
524
  };
441
525
  }
442
- export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = []) {
526
+ /**
527
+ * The `component-name-underscore` message for a component file, or null. The
528
+ * tag is the lowercased file name up to its first dot, as the build derives it
529
+ * (`deriveComponentName` in @bascik/bascik), so `site-nav.my_v2.html` defines
530
+ * `<site-nav>` and gets no warning. An `#id` rule compiles to the class
531
+ * `b_id_<component>_<id>`, so `<a_b>` with `#c` and `<a>` with `#b_c` spell
532
+ * one class, which the build rejects; the example uses the file's own name.
533
+ */
534
+ /**
535
+ * A hyphenated name to suggest for a component file without one: camelCase and underscores split into
536
+ * words (`MyCard.html` -> `my-card`), a single word gets an `app-` prefix (`card.html` -> `app-card`).
537
+ */
538
+ export const suggestHyphenatedName = (fileName) => {
539
+ const base = fileName.split(".")[0];
540
+ const words = base
541
+ .split(/_+|(?<=[a-z0-9])(?=[A-Z])/)
542
+ .filter(Boolean)
543
+ .map((w) => w.toLowerCase());
544
+ return words.length > 1 ? words.join("-") : `app-${words[0] ?? base}`;
545
+ };
546
+ export const componentNameUnderscoreMessage = (fileName) => {
547
+ const tag = fileName.split(".")[0].toLowerCase();
548
+ const at = tag.indexOf("_");
549
+ if (at === -1)
550
+ return null;
551
+ const head = tag.slice(0, at);
552
+ const rest = tag.slice(at + 1);
553
+ // The example needs a real pair: a component name and an id that starts
554
+ // with a letter, as an #id selector the build converts does.
555
+ return underscoreMessage(tag, head && /^[a-z]/.test(rest) ? { head, rest } : null);
556
+ };
557
+ const underscoreMessage = (tag, split) => {
558
+ const example = split
559
+ ? `: #btn in <${tag}> and #${split.rest}_btn in <${split.head}> both compile to the class b_id_${tag}_btn, which stops the build`
560
+ : "";
561
+ 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, "-")}").`;
562
+ };
563
+ /**
564
+ * createDiagnostics, or one analysis-failed warning when it throws, so one
565
+ * file cannot stop `bascik --check` or end the language server. The
566
+ * template scanners keep their nesting on an explicit stack, so deep
567
+ * nesting does not throw; this is the net for whatever else does.
568
+ */
569
+ export function createDiagnosticsSafely(...args) {
570
+ try {
571
+ return createDiagnostics(...args);
572
+ }
573
+ catch (error) {
574
+ const reason = error instanceof Error ? error.message : String(error);
575
+ return [
576
+ {
577
+ range: {
578
+ start: { line: 0, character: 0 },
579
+ end: { line: 0, character: 0 },
580
+ },
581
+ 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.`,
582
+ severity: DiagnosticSeverity.Warning,
583
+ source: "bascik",
584
+ code: "analysis-failed",
585
+ },
586
+ ];
587
+ }
588
+ }
589
+ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = [],
590
+ /** The files that run in Node (see script-modules.ts); found from the snapshot when left out. */
591
+ scriptModules) {
443
592
  const { languageId } = document;
444
593
  if (languageId !== "css" &&
445
594
  languageId !== "javascript" &&
@@ -453,6 +602,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
453
602
  }
454
603
  const text = document.getText();
455
604
  const diagnostics = [];
605
+ const earlyExtConfig = snapshot
606
+ ? loadExtensionConfig(snapshot.projectRoot)
607
+ : {};
456
608
  const isComponentDocument = snapshot !== undefined &&
457
609
  isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots);
458
610
  // The API folder is `directory.api`, so it is read from the project when there is one. Without a project
@@ -485,10 +637,18 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
485
637
  severity = DiagnosticSeverity.Information;
486
638
  }
487
639
  diagnostics.push({
488
- range: {
489
- start: { line: 0, character: 0 },
490
- end: { line: 0, character: Math.min(text.length, 10) },
491
- },
640
+ range: diag.range
641
+ ? {
642
+ start: {
643
+ line: diag.range.startLine,
644
+ character: diag.range.startChar,
645
+ },
646
+ end: { line: diag.range.endLine, character: diag.range.endChar },
647
+ }
648
+ : {
649
+ start: { line: 0, character: 0 },
650
+ end: { line: 0, character: Math.min(text.length, 10) },
651
+ },
492
652
  message: diag.message,
493
653
  severity,
494
654
  source: "bascik",
@@ -496,11 +656,80 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
496
656
  });
497
657
  }
498
658
  }
499
- if (languageId === "html" && fsPath.startsWith("/")) {
500
- if (snapshot &&
501
- isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots)) {
659
+ /** Located diagnostics for a script body at `bodyStart`, with the data its quick fixes need. */
660
+ const pushScriptDiagnostics = (found, bodyStart, bodyLength) => {
661
+ const bodyEnd = bodyStart + bodyLength;
662
+ for (const sd of found) {
663
+ let severity = DiagnosticSeverity.Error;
664
+ if (sd.severity === "warning")
665
+ severity = DiagnosticSeverity.Warning;
666
+ else if (sd.severity === "info")
667
+ severity = DiagnosticSeverity.Information;
668
+ let data;
669
+ if (sd.template)
670
+ data = {
671
+ templateStart: bodyStart + sd.template.start,
672
+ fixable: sd.template.fixable,
673
+ bodyStart,
674
+ bodyEnd,
675
+ };
676
+ else if (sd.code === HAND_WRITTEN_ESCAPER_RULE)
677
+ data = {
678
+ bodyStart,
679
+ bodyEnd,
680
+ ...(sd.escaper
681
+ ? {
682
+ delegate: {
683
+ ...sd.escaper,
684
+ start: bodyStart + sd.escaper.start,
685
+ end: bodyStart + sd.escaper.end,
686
+ },
687
+ }
688
+ : {}),
689
+ };
690
+ diagnostics.push({
691
+ range: {
692
+ start: document.positionAt(bodyStart + sd.start),
693
+ end: document.positionAt(bodyStart + sd.end),
694
+ },
695
+ message: sd.message,
696
+ severity,
697
+ source: "bascik",
698
+ code: sd.code,
699
+ ...(data ? { data } : {}),
700
+ });
701
+ }
702
+ };
703
+ // A .ts or .js file that runs in Node (a directive script's src= file, a
704
+ // module a script imports, an API route) gets the markup and escaper rules
705
+ // that inline directive scripts get. See script-modules.ts.
706
+ const isScriptLanguage = languageId === "typescript" || languageId === "javascript";
707
+ const modules = isScriptLanguage && snapshot !== undefined
708
+ ? (scriptModules ?? scriptModulesOf(snapshot, openDocumentTexts))
709
+ : undefined;
710
+ const modulePath = normalizeModulePath(fsPath);
711
+ const isScriptModuleDocument = isScriptLanguage &&
712
+ (isApiRouteDocument || modules?.has(modulePath) === true);
713
+ // API routes, and what server scripts, stream scripts and API routes
714
+ // import, run per request: every sink rule applies.
715
+ const isRequestTimeModule = isApiRouteDocument || modules?.requestTime.has(modulePath) === true;
716
+ // A module browser code imports too is also scoped for the browser.
717
+ const isBrowserModule = modules?.browser.has(modulePath) === true;
718
+ if (isScriptModuleDocument &&
719
+ earlyExtConfig.diagnostics?.serverScriptRules !== false)
720
+ pushScriptDiagnostics(analyzeServerScriptSource(text, {
721
+ hasSrcAttribute: false,
722
+ directive: "module",
723
+ requestTime: isRequestTimeModule,
724
+ escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
725
+ }), 0, text.length);
726
+ // isComponentDocument needs the file inside a resolved (absolute) component root, so an unsaved
727
+ // buffer never matches; no POSIX-only `startsWith("/")` gate, which skipped every Windows path.
728
+ if (languageId === "html") {
729
+ if (isComponentDocument) {
502
730
  const fileName = path.basename(normalizedDocumentPath);
503
731
  const nameWithoutExt = fileName.replace(/\.html$/i, "").toLowerCase();
732
+ const suggestedName = suggestHyphenatedName(fileName);
504
733
  if (!nameWithoutExt.includes("-") &&
505
734
  !BUILT_IN_HTML_ELEMENTS.has(nameWithoutExt)) {
506
735
  diagnostics.push({
@@ -509,7 +738,20 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
509
738
  end: { line: 0, character: Math.min(text.length, 10) },
510
739
  },
511
740
  code: "component-name-not-hyphenated",
512
- message: `Component "${nameWithoutExt}" is not hyphenated. Under WHATWG HTML §4.13, custom elements should include a hyphen (e.g. "my-${nameWithoutExt}") to avoid collisions with future HTML standards.`,
741
+ message: `Component "${nameWithoutExt}" is not hyphenated. Under WHATWG HTML §4.13, custom elements should include a hyphen (e.g. "${suggestedName}") to avoid collisions with future HTML standards.`,
742
+ severity: DiagnosticSeverity.Warning,
743
+ source: "bascik",
744
+ });
745
+ }
746
+ const underscore = componentNameUnderscoreMessage(fileName);
747
+ if (underscore) {
748
+ diagnostics.push({
749
+ range: {
750
+ start: { line: 0, character: 0 },
751
+ end: { line: 0, character: Math.min(text.length, 10) },
752
+ },
753
+ code: "component-name-underscore",
754
+ message: underscore,
513
755
  severity: DiagnosticSeverity.Warning,
514
756
  source: "bascik",
515
757
  });
@@ -537,6 +779,59 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
537
779
  });
538
780
  }
539
781
  };
782
+ // Component CSS is joined into one page stylesheet, where an unbalanced brace nests or drops other
783
+ // components' rules; the build stops on it (pkg components.ts), so this is an error at the same line.
784
+ const addBraceBalanceDiagnostic = (sourceText, offset) => {
785
+ if (!appliesScopingRules)
786
+ return;
787
+ const imbalance = findCssBraceImbalance(sourceText);
788
+ if (!imbalance)
789
+ return;
790
+ diagnostics.push({
791
+ range: {
792
+ start: document.positionAt(offset + imbalance.offset),
793
+ end: document.positionAt(offset + imbalance.offset + 1),
794
+ },
795
+ message: cssBraceImbalanceMessage(imbalance),
796
+ severity: DiagnosticSeverity.Error,
797
+ source: "bascik",
798
+ code: "css-unbalanced-braces",
799
+ });
800
+ };
801
+ // A component's <style> bodies and browser <script> bodies, with their offsets, for the preserved-target
802
+ // rule, which needs every block before it can tell what the stylesheet scopes.
803
+ const componentStyleBodies = [];
804
+ const componentClientScripts = [];
805
+ const pushPreservedTargetDiagnostics = (matches, code, offset) => {
806
+ for (const m of matches) {
807
+ diagnostics.push({
808
+ range: {
809
+ start: document.positionAt(offset + m.index),
810
+ end: document.positionAt(offset + m.index + m.length),
811
+ },
812
+ message: `${m.message} ${m.suggestion}`,
813
+ severity: DiagnosticSeverity.Warning,
814
+ source: "bascik",
815
+ code,
816
+ });
817
+ }
818
+ };
819
+ /** The current text of another file: an open editor buffer's, else the project's copy, else the file on disk. */
820
+ const readCurrentText = (filePath) => {
821
+ const normalized = path.resolve(filePath);
822
+ const open = openDocumentTexts.find(({ fsPath: openPath }) => path.resolve(openPath) === normalized);
823
+ if (open)
824
+ return open.text;
825
+ const known = snapshot?.componentSourceByFile?.get(filePath);
826
+ if (known !== undefined)
827
+ return known;
828
+ try {
829
+ return fs.readFileSync(filePath, "utf8");
830
+ }
831
+ catch {
832
+ return undefined;
833
+ }
834
+ };
540
835
  const isJavaScriptScriptTag = (openTag) => {
541
836
  const attrs = parseScriptOpenTagAttributes(openTag);
542
837
  const typeValue = attrs.get("type");
@@ -547,7 +842,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
547
842
  normalized === "text/javascript" ||
548
843
  normalized === "application/javascript" ||
549
844
  normalized === "text/ecmascript" ||
550
- normalized === "application/ecmascript");
845
+ normalized === "application/ecmascript" ||
846
+ // Bascik transpiles inline TypeScript and scopes it like JavaScript (components.ts isJs).
847
+ normalized === "text/typescript");
551
848
  };
552
849
  const scriptBlockRe = new RegExp(SCRIPT_BLOCK_RE.source, SCRIPT_BLOCK_RE.flags);
553
850
  const styleBlockRe = /(<style(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/style(?:[\t\n\f\r /][^>]*)?>/gi;
@@ -639,9 +936,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
639
936
  });
640
937
  }
641
938
  }
939
+ // Field names are renamed only when the project opts in to name scoping; by default they ship as written,
940
+ // so a form that posts elsewhere needs nothing.
642
941
  const formOpenTagRegex = /<form\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
643
942
  let formMatch;
644
943
  while (isComponentDocument &&
944
+ snapshot?.scopesName === true &&
645
945
  (formMatch = formOpenTagRegex.exec(text)) !== null) {
646
946
  const formAttributes = readOpenTagAttributes(formMatch[0]);
647
947
  const action = formAttributes.get("action");
@@ -668,6 +968,27 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
668
968
  source: "bascik",
669
969
  });
670
970
  }
971
+ if (snapshot && isComponentDocument && !snapshot.scopesName) {
972
+ const groups = findNameGroups(text);
973
+ const componentName = normalizeComponentName(fsPath);
974
+ const instances = groups.length > 0
975
+ ? countInstancesOnPages(componentName, snapshot, openDocumentTexts)
976
+ : undefined;
977
+ if (instances && instances.count > 1) {
978
+ for (const group of groups) {
979
+ diagnostics.push({
980
+ range: {
981
+ start: document.positionAt(group.attributeStart),
982
+ end: document.positionAt(group.attributeEnd),
983
+ },
984
+ code: "shared-name-group",
985
+ message: sharedNameGroupMessage(group, componentName, instances, snapshot.projectRoot),
986
+ severity: DiagnosticSeverity.Warning,
987
+ source: "bascik",
988
+ });
989
+ }
990
+ }
991
+ }
671
992
  if (snapshot && isComponentDocument) {
672
993
  const componentName = normalizeComponentName(fsPath);
673
994
  const directiveRegex = /data-bascik-attr-([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([\w-]+)"|'([\w-]+)'|([\w-]+))/gi;
@@ -676,7 +997,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
676
997
  const targetName = directiveMatch[1];
677
998
  const propName = directiveMatch[2] ?? directiveMatch[3] ?? directiveMatch[4];
678
999
  const suppliedInOpen = openDocumentTexts.some(({ text }) => htmlSuppliesComponentProp(text, componentName, propName));
679
- const suppliedInDisk = Array.from(snapshot.htmlUsageByFile.values()).some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
1000
+ // Pages and HTML under src, plus every component file: a component root outside src (shared
1001
+ // components in a monorepo) is not in htmlUsageByFile, as Find All References also allows for.
1002
+ const suppliedInDisk = [
1003
+ ...snapshot.htmlUsageByFile.values(),
1004
+ ...(snapshot.componentSourceByFile?.values() ?? []),
1005
+ ].some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
680
1006
  if (suppliedInOpen || suppliedInDisk)
681
1007
  continue;
682
1008
  const start = document.positionAt(directiveMatch.index);
@@ -787,33 +1113,24 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
787
1113
  ? "build"
788
1114
  : "routes";
789
1115
  const hasSrcAttribute = /\ssrc\s*=/i.test(openTag);
790
- const serverDiags = analyzeServerScriptSource(scriptBody, {
791
- hasSrcAttribute,
792
- directive,
793
- });
794
- for (const sd of serverDiags) {
795
- const start = document.positionAt(scriptBodyOffset + sd.start);
796
- const end = document.positionAt(scriptBodyOffset + sd.end);
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,
1116
+ const serverDiags = earlyExtConfig.diagnostics?.serverScriptRules === false
1117
+ ? []
1118
+ : analyzeServerScriptSource(scriptBody, {
1119
+ hasSrcAttribute,
1120
+ directive,
1121
+ escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
1122
+ lineOffset: document.positionAt(scriptBodyOffset).line,
810
1123
  });
811
- }
1124
+ pushScriptDiagnostics(serverDiags, scriptBodyOffset, scriptBody.length);
812
1125
  }
813
1126
  diagnostics.push(...collectLeadingSlashDiagnostics(document, openTag, scriptBody, scriptMatch.index ?? 0, attrs));
814
1127
  // A directive script runs in Node, at build time or per request, and never in the browser Bascik scopes.
815
1128
  if (isJavaScriptScriptTag(openTag) && !hasServerDirective) {
816
1129
  addCompatibilityDiagnostics(scriptBody, "js", scriptBodyOffset);
1130
+ componentClientScripts.push({
1131
+ body: scriptBody,
1132
+ offset: scriptBodyOffset,
1133
+ });
817
1134
  }
818
1135
  }
819
1136
  let styleMatch;
@@ -911,6 +1228,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
911
1228
  // 2. Diagnose data-bascik-slot outside of components, on the component itself, or targeting undeclared slots
912
1229
  const slotTagRe = /<([A-Za-z][\w-]*)(?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?\/?>/gi;
913
1230
  let slotMatch;
1231
+ const slotTags = [];
914
1232
  while ((slotMatch = slotTagRe.exec(maskedText)) !== null) {
915
1233
  const openTag = slotMatch[0];
916
1234
  const matchStart = slotMatch.index;
@@ -931,11 +1249,15 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
931
1249
  break;
932
1250
  }
933
1251
  }
934
- if (!slotAttr)
935
- continue;
936
- const tagOffset = slotMatch.index;
1252
+ if (slotAttr)
1253
+ slotTags.push({ matchStart, baseOffset, slotAttr });
1254
+ }
1255
+ // One scan finds every slot tag's parent; a prefix rescan per tag was quadratic.
1256
+ const slotParents = findNearestParentComponents(maskedText, slotTags.map(({ matchStart }) => matchStart), componentMap);
1257
+ for (const [slotIndex, slotTag] of slotTags.entries()) {
1258
+ const { matchStart, baseOffset, slotAttr } = slotTag;
937
1259
  const slotName = slotAttr.value;
938
- const parentName = findNearestParentComponent(maskedText.slice(0, tagOffset), componentMap);
1260
+ const parentName = slotParents[slotIndex];
939
1261
  const isInsideComponentDefinition = isComponentDocument;
940
1262
  if (!parentName && !isInsideComponentDefinition) {
941
1263
  const start = document.positionAt(matchStart + baseOffset + slotAttr.index);
@@ -969,7 +1291,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
969
1291
  if (componentNames.length > 0) {
970
1292
  componentNames.sort((a, b) => b.length - a.length);
971
1293
  const escapedNames = componentNames.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
972
- const componentTagRe = new RegExp(`<(${escapedNames.join("|")})\\b`, "gi");
1294
+ const componentTagRe = new RegExp(`<(${escapedNames.join("|")})${TAG_NAME_END}`, "gi");
973
1295
  let compMatch;
974
1296
  while ((compMatch = componentTagRe.exec(maskedText)) !== null) {
975
1297
  const tagStartIndex = compMatch.index;
@@ -1014,7 +1336,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1014
1336
  }
1015
1337
  if (compMeta.props.length > 0) {
1016
1338
  const insideOpenTag = openTagText
1017
- .replace(new RegExp(`^<${escapeRegExp(tagName)}\\b`, "i"), "")
1339
+ .replace(new RegExp(`^<${escapeRegExp(tagName)}${TAG_NAME_END}`, "i"), "")
1018
1340
  .replace(/\/?>$/, "");
1019
1341
  const baseAttrOffset = openTagText.indexOf(insideOpenTag);
1020
1342
  const bareAttrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?/gi;
@@ -1027,7 +1349,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1027
1349
  const declaredProp = compMeta.props.find((p) => p.name.toLowerCase() === lowerAttr);
1028
1350
  if (!declaredProp)
1029
1351
  continue;
1030
- const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}\\b`, "i").test(openTagText);
1352
+ const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}(?![\\w-])`, "i").test(openTagText);
1031
1353
  if (alreadySupplied)
1032
1354
  continue;
1033
1355
  const attrOffset = tagStartIndex + baseAttrOffset + bareMatch.index;
@@ -1096,16 +1418,46 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1096
1418
  });
1097
1419
  }
1098
1420
  addCompatibilityDiagnostics(styleBody, "css", styleBodyOffset);
1421
+ addBraceBalanceDiagnostic(styleBody, styleBodyOffset);
1422
+ componentStyleBodies.push({ body: styleBody, offset: styleBodyOffset });
1423
+ }
1424
+ // A rule or class query aimed only at preserved elements never applies: they keep their literal class
1425
+ // and id while Bascik renames the selector (the build's css-preserved-target and js-preserved-target).
1426
+ // Only a known component: a page, or a file outside any project, is never scoped, so `code {}` there works.
1427
+ if (isComponentDocument) {
1428
+ const targets = collectPreservedTargets(text, snapshot?.preserve ?? ["code"]);
1429
+ const companionCss = readCurrentText(fsPath.replace(/\.html$/i, ".css"));
1430
+ const cssClasses = collectCssClasses(companionCss ?? "");
1431
+ for (const { body } of componentStyleBodies) {
1432
+ for (const className of collectCssClasses(body)) {
1433
+ cssClasses.add(className);
1434
+ }
1435
+ }
1436
+ for (const { body, offset } of componentStyleBodies) {
1437
+ pushPreservedTargetDiagnostics(findPreservedCssTargets(body, targets), "css-preserved-target", offset);
1438
+ }
1439
+ for (const { body, offset } of componentClientScripts) {
1440
+ pushPreservedTargetDiagnostics(findPreservedJsTargets(body, targets, cssClasses), "js-preserved-target", offset);
1441
+ }
1099
1442
  }
1100
1443
  }
1101
1444
  else if (languageId === "css") {
1102
1445
  addCompatibilityDiagnostics(text, "css", 0);
1446
+ addBraceBalanceDiagnostic(text, 0);
1447
+ // A companion stylesheet's preserved targets come from its component's markup.
1448
+ const componentHtml = isComponentDocument
1449
+ ? readCurrentText(fsPath.replace(/\.css$/i, ".html"))
1450
+ : undefined;
1451
+ if (componentHtml !== undefined) {
1452
+ pushPreservedTargetDiagnostics(findPreservedCssTargets(text, collectPreservedTargets(componentHtml, snapshot?.preserve ?? ["code"])), "css-preserved-target", 0);
1453
+ }
1103
1454
  }
1104
- else {
1455
+ else if (!isScriptModuleDocument || isBrowserModule) {
1456
+ // A module that only runs in Node is never scoped for the browser.
1105
1457
  addCompatibilityDiagnostics(text, "js", 0);
1106
1458
  }
1107
1459
  const ignoreRanges = parseIgnoreDirectives(text, languageId);
1108
- const extConfig = snapshot ? loadExtensionConfig(snapshot.projectRoot) : {};
1460
+ const extConfig = earlyExtConfig;
1109
1461
  const disabledRules = new Set(extConfig.diagnostics?.disabledRules?.map((r) => r.toLowerCase()) ?? []);
1110
1462
  if (extConfig.diagnostics?.enabled === false) {
1111
1463
  return [];
@@ -1124,7 +1476,19 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1124
1476
  extConfig.diagnostics?.unclosedComponents === false) {
1125
1477
  return false;
1126
1478
  }
1127
- return !isDiagnosticIgnored(line, code, ignoreRanges);
1479
+ if (isDiagnosticIgnored(line, code, ignoreRanges))
1480
+ return false;
1481
+ // A hole on a later line of a multi-line template: an ignore comment
1482
+ // above the template's first line covers it too.
1483
+ const templateStart = diag.data
1484
+ ?.templateStart;
1485
+ if (typeof templateStart === "number") {
1486
+ const templateLine = document.positionAt(templateStart).line;
1487
+ if (templateLine !== line &&
1488
+ isDiagnosticIgnored(templateLine, code, ignoreRanges))
1489
+ return false;
1490
+ }
1491
+ return true;
1128
1492
  });
1129
1493
  }
1130
1494
  export function createCompletions(document, position, snapshot) {
@@ -1249,7 +1613,7 @@ export function createCompletions(document, position, snapshot) {
1249
1613
  {
1250
1614
  label: "bascik-stream",
1251
1615
  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.",
1616
+ documentation: "Executes in Node.js per request on production and dev servers. Streams chunked HTML responses to the client as data becomes available.",
1253
1617
  insertText: `<script data-bascik-stream>\n export default async function (request, context, { signal }) {\n return \`$0\`;\n }\n</script>`,
1254
1618
  },
1255
1619
  ];
@@ -1380,10 +1744,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1380
1744
  if (offset < blockStart || offset > blockEnd)
1381
1745
  continue;
1382
1746
  const attrs = parseScriptOpenTagAttributes(openTag);
1383
- if (!attrs.has("data-bascik-build") &&
1384
- !attrs.has("data-bascik-build-once") &&
1385
- !attrs.has("data-bascik-server") &&
1386
- !attrs.has("data-bascik-routes")) {
1747
+ if (!hasModuleResolvingDirective(attrs)) {
1387
1748
  return undefined;
1388
1749
  }
1389
1750
  const baseDir = path.dirname(fsPath);
@@ -1408,7 +1769,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1408
1769
  start: document.positionAt(valueStart),
1409
1770
  end: document.positionAt(valueEnd),
1410
1771
  },
1411
- targetUri: `file://${resolved}`,
1772
+ targetUri: pathToFileURL(resolved).toString(),
1412
1773
  targetRange: {
1413
1774
  start: { line: 0, character: 0 },
1414
1775
  end: { line: 0, character: 0 },
@@ -1433,7 +1794,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1433
1794
  start: document.positionAt(openTagEnd + start),
1434
1795
  end: document.positionAt(openTagEnd + end),
1435
1796
  },
1436
- targetUri: `file://${resolved}`,
1797
+ targetUri: pathToFileURL(resolved).toString(),
1437
1798
  targetRange: {
1438
1799
  start: { line: 0, character: 0 },
1439
1800
  end: { line: 0, character: 0 },
@@ -1469,7 +1830,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1469
1830
  start: { line: position.line, character: start },
1470
1831
  end: { line: position.line, character: end },
1471
1832
  },
1472
- targetUri: `file://${componentPath}`,
1833
+ targetUri: pathToFileURL(componentPath).toString(),
1473
1834
  targetRange: {
1474
1835
  start: { line: 0, character: 0 },
1475
1836
  end: { line: 0, character: 0 },
@@ -1527,6 +1888,269 @@ export function buildAutoFixEdit(document, diag) {
1527
1888
  }
1528
1889
  return undefined;
1529
1890
  }
1891
+ const sameEdits = (action, wrap) => JSON.stringify(Object.values(action.edit?.changes ?? {})[0]) ===
1892
+ JSON.stringify(wrap.edits);
1893
+ /**
1894
+ * `body` with string contents, comments and template-literal text replaced
1895
+ * by spaces (offsets kept), and the code inside template holes kept.
1896
+ */
1897
+ function codeOnly(body) {
1898
+ const out = body.split("");
1899
+ const blank = (from, to) => {
1900
+ for (let k = from; k < to && k < out.length; k++)
1901
+ if (out[k] !== "\n")
1902
+ out[k] = " ";
1903
+ };
1904
+ // A stack of open template literals; each entry is the brace depth of
1905
+ // the hole code that the template sits in.
1906
+ const holes = [];
1907
+ let depth = 0;
1908
+ let i = 0;
1909
+ const template = (from) => {
1910
+ // Scan template text from `from` (just past ` or }) to the end or `${`.
1911
+ let k = from;
1912
+ while (k < body.length) {
1913
+ if (body[k] === "\\")
1914
+ k += 2;
1915
+ else if (body[k] === "`") {
1916
+ blank(from, k);
1917
+ i = k + 1;
1918
+ return;
1919
+ }
1920
+ else if (body[k] === "$" && body[k + 1] === "{") {
1921
+ blank(from, k);
1922
+ holes.push(depth);
1923
+ depth = 0;
1924
+ i = k + 2;
1925
+ return;
1926
+ }
1927
+ else
1928
+ k++;
1929
+ }
1930
+ blank(from, body.length);
1931
+ i = body.length;
1932
+ };
1933
+ while (i < body.length) {
1934
+ const c = body[i];
1935
+ if (c === "/" && body[i + 1] === "/") {
1936
+ const nl = body.indexOf("\n", i);
1937
+ const end = nl === -1 ? body.length : nl;
1938
+ blank(i, end);
1939
+ i = end;
1940
+ }
1941
+ else if (c === "/" && body[i + 1] === "*") {
1942
+ const close = body.indexOf("*/", i + 2);
1943
+ const end = close === -1 ? body.length : close + 2;
1944
+ blank(i, end);
1945
+ i = end;
1946
+ }
1947
+ else if (c === "'" || c === '"') {
1948
+ let k = i + 1;
1949
+ while (k < body.length && body[k] !== c && body[k] !== "\n")
1950
+ k += body[k] === "\\" ? 2 : 1;
1951
+ blank(i + 1, k);
1952
+ i = k + 1;
1953
+ }
1954
+ else if (c === "`")
1955
+ template(i + 1);
1956
+ else if (c === "{") {
1957
+ depth++;
1958
+ i++;
1959
+ }
1960
+ else if (c === "}") {
1961
+ if (depth === 0 && holes.length > 0) {
1962
+ depth = holes.pop();
1963
+ template(i + 1);
1964
+ }
1965
+ else {
1966
+ if (depth > 0)
1967
+ depth--;
1968
+ i++;
1969
+ }
1970
+ }
1971
+ else
1972
+ i++;
1973
+ }
1974
+ return out.join("");
1975
+ }
1976
+ /**
1977
+ * The quick fix for server-script-unescaped-markup: put `html` before the
1978
+ * template's backtick and import it from @bascik/bascik/html (after the
1979
+ * script's last import, or merged into an existing import from the module).
1980
+ * When the name html is already used in the script's code (a variable, a
1981
+ * parameter, another import), it imports `html as safeHtml` instead, so the
1982
+ * fix never tags with a binding that means something else; when safeHtml is
1983
+ * taken too, or a hole sits where html would throw, it is not offered.
1984
+ */
1985
+ export function buildWrapHtmlEdits(document, diag) {
1986
+ if (diag.code !== "server-script-unescaped-markup")
1987
+ return undefined;
1988
+ const data = diag.data;
1989
+ if (!data || !data.fixable)
1990
+ return undefined;
1991
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
1992
+ if (!plan)
1993
+ return undefined;
1994
+ const backtick = document.positionAt(data.templateStart);
1995
+ return {
1996
+ title: "Wrap template in html`...`",
1997
+ edits: [
1998
+ ...plan.edits,
1999
+ { range: { start: backtick, end: backtick }, newText: plan.local },
2000
+ ],
2001
+ };
2002
+ }
2003
+ /**
2004
+ * The local name to use for `exportName` from @bascik/bascik/html in the
2005
+ * script between `bodyStart` and `bodyEnd`, and the edits that import it:
2006
+ * after the script's last import, or merged into an existing import from
2007
+ * the module. When the name is already used in the script's code (a
2008
+ * variable, a parameter, another import), it imports `exportName as alias`
2009
+ * instead, so the edit never uses a binding that means something else;
2010
+ * when the alias is taken too, there is no plan. With `onlyAsTagOrCall`, an
2011
+ * existing import of the name counts only when the name is never shadowed.
2012
+ */
2013
+ function planHtmlImport(document, bodyStart, bodyEnd, exportName, alias, onlyAsTagOrCall) {
2014
+ const text = document.getText();
2015
+ const body = text.slice(bodyStart, bodyEnd);
2016
+ const at = (offset) => document.positionAt(bodyStart + offset);
2017
+ const edits = [];
2018
+ const existing = /\bimport\s*\{([^}]*)\}\s*from\s*["']@bascik\/bascik\/html["']/.exec(body);
2019
+ // Identifiers in code only: strings, comments and template text blanked,
2020
+ // and the import from the module left out, so `<html>` or "html" is no
2021
+ // clash but a parameter, a variable or another import named html is.
2022
+ const code = codeOnly(existing
2023
+ ? body.slice(0, existing.index) +
2024
+ " ".repeat(existing[0].length) +
2025
+ body.slice((existing.index ?? 0) + existing[0].length)
2026
+ : body);
2027
+ const word = (name) => `(?<![\\w$.])${escapeRegExp(name)}(?![\\w$])`;
2028
+ const uses = (name) => new RegExp(word(name)).test(code);
2029
+ // An imported name is safe to tag with when it is only ever a tag or a
2030
+ // callee: anywhere else (a parameter, a variable, a function declaration)
2031
+ // it may be shadowed.
2032
+ const onlyTagOrCall = (name) => !new RegExp(`(?<!\\bfunction\\s*)${word(name)}(?!\\s*[\`(])`).test(code) &&
2033
+ !new RegExp(`\\bfunction\\s*${word(name)}`).test(code);
2034
+ let local;
2035
+ let specifier;
2036
+ const entries = existing
2037
+ ? existing[1]
2038
+ .split(",")
2039
+ .map((e) => e.trim())
2040
+ .filter(Boolean)
2041
+ : [];
2042
+ // Names that are not identifiers (a half-typed `html as h(`) bind nothing.
2043
+ const bound = entries
2044
+ .map(parseImportSpecifier)
2045
+ .filter((parts) => parts?.[0] === exportName)
2046
+ .map((parts) => parts[1]);
2047
+ local = bound.find((name) => !onlyAsTagOrCall || onlyTagOrCall(name));
2048
+ if (local === undefined) {
2049
+ if (!bound.includes(exportName) && !uses(exportName)) {
2050
+ local = exportName;
2051
+ specifier = exportName;
2052
+ }
2053
+ else if (!bound.includes(alias) && !uses(alias)) {
2054
+ local = alias;
2055
+ specifier = `${exportName} as ${alias}`;
2056
+ }
2057
+ else
2058
+ return undefined;
2059
+ }
2060
+ if (specifier !== undefined && existing) {
2061
+ const open = (existing.index ?? 0) + existing[0].indexOf("{") + 1;
2062
+ const close = open + existing[1].length;
2063
+ edits.push({
2064
+ range: { start: at(open), end: at(close) },
2065
+ newText: ` ${[...entries, specifier].join(", ")} `,
2066
+ });
2067
+ }
2068
+ else if (specifier !== undefined) {
2069
+ const statement = `import { ${specifier} } from "@bascik/bascik/html";`;
2070
+ const imports = [
2071
+ ...body.matchAll(/^([ \t]*)import\b[^;]*?from\s*["'][^"']+["'][ \t]*;?[ \t]*$/gm),
2072
+ ];
2073
+ const last = imports[imports.length - 1];
2074
+ if (last) {
2075
+ const end = (last.index ?? 0) + last[0].length;
2076
+ edits.push({
2077
+ range: { start: at(end), end: at(end) },
2078
+ newText: `\n${last[1]}${statement}`,
2079
+ });
2080
+ }
2081
+ else {
2082
+ const first = /^([ \t]*)\S/m.exec(body);
2083
+ const lineStart = first?.index ?? 0;
2084
+ edits.push({
2085
+ range: { start: at(lineStart), end: at(lineStart) },
2086
+ newText: `${first?.[1] ?? ""}${statement}\n`,
2087
+ });
2088
+ }
2089
+ }
2090
+ return { local, edits };
2091
+ }
2092
+ /**
2093
+ * The code actions for hand-written-html-escaper. A one-return escaper with
2094
+ * one plain parameter gets "Make NAME() call esc()": its body becomes a call
2095
+ * to esc() from @bascik/bascik/html (imported, aliased when the name esc is
2096
+ * taken, as it is when the escaper itself is called esc). The callers keep
2097
+ * working: esc() escapes the same characters and quotes as well. Rewriting
2098
+ * the callers to html`...` is not automatic, since a template's value then
2099
+ * changes from a string to an html value. Every other escaper (a lookup
2100
+ * object, a longer body) gets "Import html from @bascik/bascik/html" when
2101
+ * the script does not import it yet, as a start on rewriting by hand.
2102
+ */
2103
+ export function buildEscaperActions(document, diag) {
2104
+ if (diag.code !== HAND_WRITTEN_ESCAPER_RULE)
2105
+ return [];
2106
+ const data = diag.data;
2107
+ if (!data)
2108
+ return [];
2109
+ const name = document.getText(diag.range);
2110
+ if (data.delegate) {
2111
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "esc", "escapeValue", true);
2112
+ if (plan) {
2113
+ const { start, end, param, block } = data.delegate;
2114
+ const startPos = document.positionAt(start);
2115
+ const lineStart = document.offsetAt({
2116
+ line: startPos.line,
2117
+ character: 0,
2118
+ });
2119
+ const indent = /^[ \t]*/.exec(document.getText().slice(lineStart, start))?.[0] ?? "";
2120
+ const call = `${plan.local}(${param})`;
2121
+ return [
2122
+ {
2123
+ title: name === "default"
2124
+ ? "Make the default export call esc() from @bascik/bascik/html"
2125
+ : `Make ${name}() call esc() from @bascik/bascik/html`,
2126
+ preferred: true,
2127
+ edits: [
2128
+ ...plan.edits,
2129
+ {
2130
+ range: { start: startPos, end: document.positionAt(end) },
2131
+ newText: block
2132
+ ? `{\n${indent} return ${call};\n${indent}}`
2133
+ : call,
2134
+ },
2135
+ ],
2136
+ },
2137
+ ];
2138
+ }
2139
+ }
2140
+ const body = document.getText().slice(data.bodyStart, data.bodyEnd);
2141
+ if (/\bimport\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s*["']@bascik\/bascik\/html["']/.test(body))
2142
+ return [];
2143
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
2144
+ if (!plan || plan.edits.length === 0)
2145
+ return [];
2146
+ return [
2147
+ {
2148
+ title: "Import html from @bascik/bascik/html to build markup safely",
2149
+ preferred: false,
2150
+ edits: plan.edits,
2151
+ },
2152
+ ];
2153
+ }
1530
2154
  export function createCodeActions(document, range, diagnostics, snapshot, fsPath) {
1531
2155
  const activeDiagnostics = diagnostics.length > 0
1532
2156
  ? diagnostics
@@ -1537,6 +2161,33 @@ export function createCodeActions(document, range, diagnostics, snapshot, fsPath
1537
2161
  for (const diag of activeDiagnostics) {
1538
2162
  if (!rangesOverlap(diag.range, range))
1539
2163
  continue;
2164
+ // Editor only: wrapping changes the value from a string to SafeHtml, so
2165
+ // `bascik --check --fix` (applyAutoFixes) never applies it.
2166
+ const escaperActions = buildEscaperActions(document, diag);
2167
+ if (escaperActions.length > 0) {
2168
+ for (const action of escaperActions)
2169
+ actions.push({
2170
+ title: action.title,
2171
+ kind: CodeActionKind.QuickFix,
2172
+ diagnostics: [diag],
2173
+ isPreferred: action.preferred,
2174
+ edit: { changes: { [document.uri]: action.edits } },
2175
+ });
2176
+ continue;
2177
+ }
2178
+ const wrap = buildWrapHtmlEdits(document, diag);
2179
+ if (wrap) {
2180
+ if (actions.some((a) => a.title === wrap.title && sameEdits(a, wrap)))
2181
+ continue;
2182
+ actions.push({
2183
+ title: wrap.title,
2184
+ kind: CodeActionKind.QuickFix,
2185
+ diagnostics: [diag],
2186
+ isPreferred: true,
2187
+ edit: { changes: { [document.uri]: wrap.edits } },
2188
+ });
2189
+ continue;
2190
+ }
1540
2191
  const fix = buildAutoFixEdit(document, diag);
1541
2192
  if (!fix)
1542
2193
  continue;