@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.
Files changed (115) hide show
  1. package/README.md +72 -30
  2. package/dist/analyzer.d.ts +70 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/analyzer.js +625 -75
  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 +235 -16
  9. package/dist/api-rules.js.map +1 -1
  10. package/dist/bin.js +4 -1
  11. package/dist/bin.js.map +1 -1
  12. package/dist/check.d.ts +14 -1
  13. package/dist/check.d.ts.map +1 -1
  14. package/dist/check.js +116 -10
  15. package/dist/check.js.map +1 -1
  16. package/dist/cli.d.ts.map +1 -1
  17. package/dist/cli.js +27 -8
  18. package/dist/cli.js.map +1 -1
  19. package/dist/compatibility-rules.json +21 -3
  20. package/dist/component-metadata.d.ts.map +1 -1
  21. package/dist/component-metadata.js +3 -1
  22. package/dist/component-metadata.js.map +1 -1
  23. package/dist/component-usages.d.ts +47 -0
  24. package/dist/component-usages.d.ts.map +1 -0
  25. package/dist/component-usages.js +495 -0
  26. package/dist/component-usages.js.map +1 -0
  27. package/dist/config-reader.d.ts +41 -0
  28. package/dist/config-reader.d.ts.map +1 -0
  29. package/dist/config-reader.js +461 -0
  30. package/dist/config-reader.js.map +1 -0
  31. package/dist/config.d.ts +10 -0
  32. package/dist/config.d.ts.map +1 -1
  33. package/dist/config.js +25 -30
  34. package/dist/config.js.map +1 -1
  35. package/dist/hand-written-escaper.d.ts +35 -0
  36. package/dist/hand-written-escaper.d.ts.map +1 -0
  37. package/dist/hand-written-escaper.js +739 -0
  38. package/dist/hand-written-escaper.js.map +1 -0
  39. package/dist/module-specifiers.d.ts +25 -0
  40. package/dist/module-specifiers.d.ts.map +1 -1
  41. package/dist/module-specifiers.js +234 -165
  42. package/dist/module-specifiers.js.map +1 -1
  43. package/dist/name-groups.d.ts +36 -0
  44. package/dist/name-groups.d.ts.map +1 -0
  45. package/dist/name-groups.js +198 -0
  46. package/dist/name-groups.js.map +1 -0
  47. package/dist/plain-holes.d.ts +116 -0
  48. package/dist/plain-holes.d.ts.map +1 -0
  49. package/dist/plain-holes.js +1970 -0
  50. package/dist/plain-holes.js.map +1 -0
  51. package/dist/project.d.ts +58 -1
  52. package/dist/project.d.ts.map +1 -1
  53. package/dist/project.js +146 -8
  54. package/dist/project.js.map +1 -1
  55. package/dist/references.d.ts +47 -0
  56. package/dist/references.d.ts.map +1 -0
  57. package/dist/references.js +241 -0
  58. package/dist/references.js.map +1 -0
  59. package/dist/script-modules.d.ts +60 -0
  60. package/dist/script-modules.d.ts.map +1 -0
  61. package/dist/script-modules.js +382 -0
  62. package/dist/script-modules.js.map +1 -0
  63. package/dist/server-script-rules.d.ts +94 -1
  64. package/dist/server-script-rules.d.ts.map +1 -1
  65. package/dist/server-script-rules.js +2572 -230
  66. package/dist/server-script-rules.js.map +1 -1
  67. package/dist/server-script-templates.d.ts +250 -0
  68. package/dist/server-script-templates.d.ts.map +1 -0
  69. package/dist/server-script-templates.js +1685 -0
  70. package/dist/server-script-templates.js.map +1 -0
  71. package/dist/server.d.ts +191 -3
  72. package/dist/server.d.ts.map +1 -1
  73. package/dist/server.js +822 -50
  74. package/dist/server.js.map +1 -1
  75. package/dist/start.d.ts +10 -1
  76. package/dist/start.d.ts.map +1 -1
  77. package/dist/start.js +14 -2
  78. package/dist/start.js.map +1 -1
  79. package/dist/string-typed-flow.d.ts +26 -0
  80. package/dist/string-typed-flow.d.ts.map +1 -0
  81. package/dist/string-typed-flow.js +496 -0
  82. package/dist/string-typed-flow.js.map +1 -0
  83. package/dist/typescript-blocks.d.ts +205 -0
  84. package/dist/typescript-blocks.d.ts.map +1 -0
  85. package/dist/typescript-blocks.js +464 -0
  86. package/dist/typescript-blocks.js.map +1 -0
  87. package/dist/typescript-editor-mode.d.ts +28 -0
  88. package/dist/typescript-editor-mode.d.ts.map +1 -0
  89. package/dist/typescript-editor-mode.js +161 -0
  90. package/dist/typescript-editor-mode.js.map +1 -0
  91. package/dist/typescript-engine.d.ts +115 -0
  92. package/dist/typescript-engine.d.ts.map +1 -0
  93. package/dist/typescript-engine.js +286 -0
  94. package/dist/typescript-engine.js.map +1 -0
  95. package/dist/typescript-features.d.ts +136 -0
  96. package/dist/typescript-features.d.ts.map +1 -0
  97. package/dist/typescript-features.js +374 -0
  98. package/dist/typescript-features.js.map +1 -0
  99. package/dist/typescript-loader.d.ts +55 -0
  100. package/dist/typescript-loader.d.ts.map +1 -0
  101. package/dist/typescript-loader.js +202 -0
  102. package/dist/typescript-loader.js.map +1 -0
  103. package/dist/typescript-lsp.d.ts +8 -0
  104. package/dist/typescript-lsp.d.ts.map +1 -0
  105. package/dist/typescript-lsp.js +115 -0
  106. package/dist/typescript-lsp.js.map +1 -0
  107. package/dist/typescript-service.d.ts +350 -0
  108. package/dist/typescript-service.d.ts.map +1 -0
  109. package/dist/typescript-service.js +1465 -0
  110. package/dist/typescript-service.js.map +1 -0
  111. package/dist/typescript-worker.d.ts +11 -0
  112. package/dist/typescript-worker.d.ts.map +1 -0
  113. package/dist/typescript-worker.js +107 -0
  114. package/dist/typescript-worker.js.map +1 -0
  115. package/package.json +20 -7
@@ -0,0 +1,1465 @@
1
+ /**
2
+ * TypeScript errors for the `type="text/typescript"` script blocks of Bascik HTML files, from TypeScript's own
3
+ * LanguageService.
4
+ *
5
+ * Each block becomes a virtual `.ts` file next to its HTML file (`page.html.bascik-0.ts`), so a relative import
6
+ * resolves from the page's folder and `@/` resolves against `scripts.importRoot` through `paths`. Client blocks and
7
+ * server-side blocks are checked by two LanguageServices with different libraries: the browser's (DOM, no Node
8
+ * types) and Node's (Node types when `@types/node` is installed, no DOM). A page whose client blocks add to the
9
+ * browser's globals gets a client LanguageService of its own, since no two pages run together (see `serviceKey`).
10
+ * The project's `tsconfig.json`, when it has one, is the base; Bascik's settings go on top.
11
+ *
12
+ * Edits are incremental: an HTML edit replaces only the virtual files of blocks whose text changed, and an edit in
13
+ * an imported file (an unsaved editor buffer, or a change on disk) bumps that file's version.
14
+ *
15
+ * This module is the engine; `typescript-engine.ts` runs it beside the language server, and `check.ts` runs it for
16
+ * `bascik --check`.
17
+ */
18
+ import { createHash } from "node:crypto";
19
+ import * as fs from "node:fs";
20
+ import { builtinModules, createRequire } from "node:module";
21
+ import * as path from "node:path";
22
+ import { extractPageScopeScripts, extractTypeScriptBlocks, GLOBAL_THIS_TYPE, SCRIPT_TYPE_CHECK, sharedScriptText, toGeneratedOffset, toSourceOffset, typeScriptBlockAt, virtualBlockText, withoutGlobalObjectAliases, } from "./typescript-blocks.js";
23
+ import { answerFeature, everyFile, } from "./typescript-features.js";
24
+ import { editorModeMirror } from "./typescript-editor-mode.js";
25
+ import { resolveTypeScript, tsPath, } from "./typescript-loader.js";
26
+ /** The source tag on every published TypeScript diagnostic, so they read apart from Bascik's own. */
27
+ export const TYPESCRIPT_DIAGNOSTIC_SOURCE = "ts (bascik)";
28
+ /** TypeScript's lowest `target` that allows top-level `await`, which Bascik's server-side scripts may use. */
29
+ const MINIMUM_TARGET = 9; // ts.ScriptTarget.ES2022
30
+ /** Library file names a program's `lib` holds for a browser, and the ones that only make sense there. */
31
+ const BROWSER_LIBS = ["lib.dom.d.ts", "lib.dom.iterable.d.ts"];
32
+ const BROWSER_ONLY_LIB = /^lib\.(dom|webworker|scripthost)\b/i;
33
+ /**
34
+ * The web-standard globals a server-side block has without `@types/node`: `Request`, `Response`, `URL`, `fetch`,
35
+ * `Headers`, `AbortSignal`, streams, `crypto` and `import.meta.url`, which Node and workerd both provide. A web
36
+ * worker's library has them and, unlike the browser's, no `document` or `window`.
37
+ */
38
+ export const SERVER_WEB_LIBS = [
39
+ "lib.webworker.d.ts",
40
+ "lib.webworker.iterable.d.ts",
41
+ ];
42
+ /**
43
+ * Node's globals and built-in modules, untyped, for server-side blocks in a project without `@types/node`. Code
44
+ * that runs in Node is never reported for using them; installing `@types/node` gives them their types.
45
+ */
46
+ export function untypedNodeDeclarations() {
47
+ const modules = builtinModules
48
+ .filter((name) => !name.startsWith("_") && !name.startsWith("node:"))
49
+ .map((name) => `declare module ${JSON.stringify(name)};`);
50
+ return [
51
+ "// Node's globals and modules, untyped: the project has no @types/node.",
52
+ "declare var process: any;",
53
+ "declare var Buffer: any;",
54
+ "declare var global: any;",
55
+ "declare var require: any;",
56
+ "declare var module: any;",
57
+ "declare var __dirname: string;",
58
+ "declare var __filename: string;",
59
+ 'declare module "node:*";',
60
+ ...modules,
61
+ "",
62
+ ].join("\n");
63
+ }
64
+ /** Whether `@types/node` can be found from the project, so server-side blocks get Node's globals and modules. */
65
+ export function hasNodeTypes(projectRoot) {
66
+ try {
67
+ createRequire(path.join(projectRoot, "package.json")).resolve("@types/node/package.json");
68
+ return true;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ /**
75
+ * The compiler options for one program: the project's `tsconfig.json` (when it has one), then Bascik's settings,
76
+ * then the libraries and global types that program's scripts run with.
77
+ */
78
+ export function compilerOptionsFor(ts, projectRoot, importRoot, program, nodeTypes = hasNodeTypes(projectRoot)) {
79
+ let base = {};
80
+ projectRoot = tsPath(projectRoot);
81
+ importRoot = tsPath(importRoot);
82
+ // TypeScript asserts the config path it is given is already in its own spelling.
83
+ const configPath = `${projectRoot}/tsconfig.json`;
84
+ if (fs.existsSync(configPath)) {
85
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
86
+ // A tsconfig that does not parse is the editor's to report; the blocks are still checked with the defaults.
87
+ if (read.config !== undefined) {
88
+ base = ts.parseJsonConfigFileContent(read.config, ts.sys, projectRoot, undefined, configPath).options;
89
+ }
90
+ }
91
+ const target = base.target === undefined || base.target < MINIMUM_TARGET
92
+ ? MINIMUM_TARGET
93
+ : base.target;
94
+ // The target's default library, without the browser parts the `.full` variant adds.
95
+ const defaultLib = ts
96
+ .getDefaultLibFileName({ target })
97
+ .replace(/\.full\.d\.ts$/, ".d.ts")
98
+ .replace(/^lib\.d\.ts$/, "lib.es5.d.ts");
99
+ const languageLibs = (base.lib ?? [defaultLib]).filter((lib) => !BROWSER_ONLY_LIB.test(lib));
100
+ const projectTypes = base.types?.filter((name) => name !== "node" && name !== "@types/node");
101
+ const options = {
102
+ strict: true,
103
+ allowJs: true,
104
+ ...base,
105
+ target,
106
+ module: ts.ModuleKind.ESNext,
107
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
108
+ moduleDetection: ts.ModuleDetectionKind.Force,
109
+ allowImportingTsExtensions: true,
110
+ noEmit: true,
111
+ // Only the blocks' own errors are reported, so errors inside declaration files are not worth the time.
112
+ skipLibCheck: true,
113
+ // Emit settings that conflict with noEmit, or make no sense for script blocks.
114
+ composite: false,
115
+ declaration: false,
116
+ declarationMap: false,
117
+ emitDeclarationOnly: false,
118
+ incremental: false,
119
+ sourceMap: false,
120
+ paths: {
121
+ ...base.paths,
122
+ // Bascik resolves `@/` against `scripts.importRoot`; the project's own `@/*` cannot point elsewhere.
123
+ "@/*": [`${importRoot}/*`],
124
+ },
125
+ };
126
+ if (program === "client") {
127
+ options.lib = [...new Set([...languageLibs, ...BROWSER_LIBS])];
128
+ // Explicit, so `@types/node` (picked up automatically otherwise) never gives browser code `process`.
129
+ options.types = projectTypes ?? [];
130
+ }
131
+ else if (nodeTypes) {
132
+ options.lib = languageLibs;
133
+ options.types = [...(projectTypes ?? []), "node"];
134
+ }
135
+ else {
136
+ // Without Node's types, the web globals Node shares with workerd (Node's own are declared untyped).
137
+ options.lib = [...new Set([...languageLibs, ...SERVER_WEB_LIBS])];
138
+ options.types = projectTypes ?? [];
139
+ }
140
+ return options;
141
+ }
142
+ /** Whether `name` appears anywhere in the block outside `declaration` (a call, an `export { }`, an overload). */
143
+ function isNameUsedOutside(ts, source, declaration, name) {
144
+ let found = false;
145
+ const visit = (node) => {
146
+ if (found || node === declaration)
147
+ return;
148
+ if (ts.isIdentifier(node) && node.text === name) {
149
+ found = true;
150
+ return;
151
+ }
152
+ ts.forEachChild(node, visit);
153
+ };
154
+ ts.forEachChild(source, visit);
155
+ return found;
156
+ }
157
+ /**
158
+ * Where Bascik passes a directive script's default export to its typed check function. Passing it as an argument
159
+ * gives an untyped parameter its type from the call. A named function declaration stays a declaration when the
160
+ * block uses its name anywhere else, and the footer checks it by name instead: wrapping would make it an
161
+ * expression, whose name the rest of the module cannot see.
162
+ */
163
+ function defaultExportPlan(ts, content) {
164
+ const source = ts.createSourceFile("block.ts", content, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
165
+ const opening = `${SCRIPT_TYPE_CHECK}(`;
166
+ for (const statement of source.statements) {
167
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
168
+ return {
169
+ insertions: [
170
+ { at: statement.expression.getStart(source), text: opening },
171
+ { at: statement.expression.end, text: ")" },
172
+ ],
173
+ };
174
+ }
175
+ if (ts.isFunctionDeclaration(statement) && statement.body) {
176
+ const modifiers = statement.modifiers ?? [];
177
+ const defaultKeyword = modifiers.find((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
178
+ if (defaultKeyword &&
179
+ modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
180
+ const name = statement.name;
181
+ if (name && isNameUsedOutside(ts, source, statement, name.text)) {
182
+ return {
183
+ insertions: [],
184
+ check: {
185
+ name: name.text,
186
+ start: name.getStart(source),
187
+ end: name.end,
188
+ },
189
+ };
190
+ }
191
+ // `export default async function f() {}` becomes `export default __bascikScript( async function f() {})`.
192
+ return {
193
+ insertions: [
194
+ { at: defaultKeyword.end, text: ` ${opening}` },
195
+ { at: statement.end, text: ")" },
196
+ ],
197
+ };
198
+ }
199
+ }
200
+ }
201
+ return { insertions: [] };
202
+ }
203
+ /** The value names a binding (`a`, `{ a, b: [c] }`) declares. */
204
+ function bindingNames(ts, name, names) {
205
+ if (ts.isIdentifier(name)) {
206
+ names.push(name.text);
207
+ return;
208
+ }
209
+ for (const element of name.elements) {
210
+ if (!ts.isOmittedExpression(element))
211
+ bindingNames(ts, element.name, names);
212
+ }
213
+ }
214
+ /** The text after a script's content when it is parsed alone: a module, as Bascik checks a block. */
215
+ const PARSE_FOOTER = "\nexport {};\n";
216
+ /**
217
+ * Reads a client script on its own: the names it declares at the top level, its interfaces and (for a typed one)
218
+ * its syntax errors. A program of that one file, with no libraries and no imports, finds the syntax errors with
219
+ * TypeScript's public API.
220
+ */
221
+ export function readClassicScript(ts, content, typed) {
222
+ const fileName = typed ? "/__bascik-script.ts" : "/__bascik-script.js";
223
+ const source = ts.createSourceFile(fileName, content + PARSE_FOOTER, ts.ScriptTarget.Latest, true, typed ? ts.ScriptKind.TS : ts.ScriptKind.JS);
224
+ const names = [];
225
+ const windowNames = [];
226
+ const globalAugmentations = [];
227
+ const localNames = [];
228
+ const interfaces = [];
229
+ for (const statement of source.statements) {
230
+ if (statement.pos >= content.length)
231
+ break;
232
+ if ((ts.isFunctionDeclaration(statement) ||
233
+ ts.isClassDeclaration(statement) ||
234
+ ts.isEnumDeclaration(statement)) &&
235
+ statement.name) {
236
+ names.push(statement.name.text);
237
+ if (ts.isFunctionDeclaration(statement))
238
+ windowNames.push(statement.name.text);
239
+ }
240
+ else if (ts.isVariableStatement(statement)) {
241
+ // `let`, `const` and `using` are globals of the page's scope, but not properties of `window`.
242
+ const isVar = (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === 0;
243
+ for (const declaration of statement.declarationList.declarations) {
244
+ bindingNames(ts, declaration.name, names);
245
+ if (isVar)
246
+ bindingNames(ts, declaration.name, windowNames);
247
+ }
248
+ }
249
+ else if (ts.isModuleDeclaration(statement) &&
250
+ (statement.flags & ts.NodeFlags.GlobalAugmentation) !== 0) {
251
+ globalAugmentations.push(statement.getText(source));
252
+ }
253
+ else if ((ts.isTypeAliasDeclaration(statement) ||
254
+ ts.isModuleDeclaration(statement)) &&
255
+ ts.isIdentifier(statement.name)) {
256
+ localNames.push(statement.name.text);
257
+ }
258
+ else if (ts.isImportDeclaration(statement)) {
259
+ const clause = statement.importClause;
260
+ if (clause?.name)
261
+ localNames.push(clause.name.text);
262
+ const bindings = clause?.namedBindings;
263
+ if (bindings && ts.isNamespaceImport(bindings))
264
+ localNames.push(bindings.name.text);
265
+ else if (bindings)
266
+ for (const element of bindings.elements)
267
+ localNames.push(element.name.text);
268
+ }
269
+ else if (ts.isImportEqualsDeclaration(statement)) {
270
+ localNames.push(statement.name.text);
271
+ }
272
+ else if (ts.isInterfaceDeclaration(statement) &&
273
+ (statement.modifiers?.length ?? 0) === 0) {
274
+ interfaces.push({
275
+ name: statement.name.text,
276
+ start: statement.getStart(source),
277
+ end: statement.end,
278
+ text: statement.getText(source),
279
+ });
280
+ }
281
+ }
282
+ let syntaxErrors = [];
283
+ if (typed) {
284
+ const host = {
285
+ getSourceFile: (name) => (name === fileName ? source : undefined),
286
+ getDefaultLibFileName: () => "/lib.d.ts",
287
+ writeFile: () => undefined,
288
+ getCurrentDirectory: () => "/",
289
+ getCanonicalFileName: (name) => name,
290
+ useCaseSensitiveFileNames: () => true,
291
+ getNewLine: () => "\n",
292
+ fileExists: (name) => name === fileName,
293
+ readFile: () => undefined,
294
+ };
295
+ const program = ts.createProgram({
296
+ rootNames: [fileName],
297
+ options: { noLib: true, noResolve: true, types: [] },
298
+ host,
299
+ });
300
+ syntaxErrors = program.getSyntacticDiagnostics(source).map((diagnostic) => {
301
+ // An error past the content (an unclosed brace runs into the footer) is at the end of the script.
302
+ const start = Math.min(diagnostic.start ?? 0, content.length);
303
+ return {
304
+ start,
305
+ end: Math.max(start, Math.min((diagnostic.start ?? 0) + (diagnostic.length ?? 0), content.length)),
306
+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
307
+ code: diagnostic.code,
308
+ };
309
+ });
310
+ }
311
+ return {
312
+ names: [...new Set(names)],
313
+ windowNames: [...new Set(windowNames)],
314
+ globalAugmentations,
315
+ localNames,
316
+ interfaces,
317
+ syntaxErrors,
318
+ };
319
+ }
320
+ /** Global names per library file, read once per process (the files never change while it runs). */
321
+ const libraryGlobals = new Map();
322
+ /**
323
+ * The interfaces and values a library file declares globally, following its `/// <reference lib>` lines. The
324
+ * library files are generated with every global declaration at the start of a line, so a scan of the text finds
325
+ * them without parsing a multi-megabyte file.
326
+ */
327
+ function globalsOf(ts, libDir, libName, into, seen) {
328
+ const file = path.join(libDir, libName);
329
+ if (seen.has(file))
330
+ return;
331
+ seen.add(file);
332
+ let globals = libraryGlobals.get(file);
333
+ const references = [];
334
+ const text = ts.sys.readFile(file) ?? "";
335
+ for (const match of text.matchAll(/^\/\/\/\s*<reference\s+lib=["']([^"']+)["']/gm))
336
+ references.push(`lib.${match[1].toLowerCase()}.d.ts`);
337
+ if (!globals) {
338
+ const names = (re) => new Set([...text.matchAll(re)].map((match) => match[1]));
339
+ globals = {
340
+ interfaces: names(/^(?:declare\s+)?interface\s+([A-Za-z_$][\w$]*)/gm),
341
+ values: names(/^declare\s+(?:var|let|const|function)\s+([A-Za-z_$][\w$]*)/gm),
342
+ };
343
+ libraryGlobals.set(file, globals);
344
+ }
345
+ for (const name of globals.interfaces)
346
+ into.interfaces.add(name);
347
+ for (const name of globals.values)
348
+ into.values.add(name);
349
+ for (const reference of references)
350
+ globalsOf(ts, libDir, reference, into, seen);
351
+ }
352
+ /** The global objects a page's classic globals are properties of. */
353
+ const GLOBAL_OBJECTS = ["window", "self", "globalThis"];
354
+ /** A short, stable name for a service key, for the names of the files a service holds. */
355
+ const shortHash = (text) => createHash("sha1").update(text).digest("hex").slice(0, 12);
356
+ /** Whether a file is part of an installed package (or TypeScript's own libraries), never the project's own. */
357
+ const isPackageFile = (fileName) => /[\\/]node_modules[\\/]/.test(fileName);
358
+ /** "Variable 'x' is used before being assigned." */
359
+ const USED_BEFORE_ASSIGNED = 2454;
360
+ /** Diagnostics TypeScript gives for a name declared and never used (`noUnusedLocals` and the like). */
361
+ const UNUSED_CODES = new Set([6133, 6196, 6198, 6199]);
362
+ /**
363
+ * Where the names a shared classic script declares at its top level start, with the starts of its variable lists
364
+ * and binding patterns: where TypeScript puts its "declared but never used" errors for them. In a classic script
365
+ * these are globals, which markup (`onclick="toggleFrother()"`) and later scripts can use, so those errors are
366
+ * wrong for them.
367
+ */
368
+ function topLevelNameStarts(ts, source, footerStart) {
369
+ const starts = new Set();
370
+ const visitBinding = (name) => {
371
+ starts.add(name.getStart(source));
372
+ if (!ts.isIdentifier(name))
373
+ for (const element of name.elements)
374
+ if (!ts.isOmittedExpression(element))
375
+ visitBinding(element.name);
376
+ };
377
+ const visitStatements = (statements) => {
378
+ for (const statement of statements) {
379
+ if (statement.pos >= footerStart)
380
+ break;
381
+ if (ts.isVariableStatement(statement)) {
382
+ starts.add(statement.getStart(source));
383
+ starts.add(statement.declarationList.getStart(source));
384
+ for (const declaration of statement.declarationList.declarations)
385
+ visitBinding(declaration.name);
386
+ }
387
+ else if ((ts.isFunctionDeclaration(statement) ||
388
+ ts.isClassDeclaration(statement) ||
389
+ ts.isEnumDeclaration(statement) ||
390
+ ts.isInterfaceDeclaration(statement) ||
391
+ ts.isTypeAliasDeclaration(statement)) &&
392
+ statement.name) {
393
+ starts.add(statement.name.getStart(source));
394
+ }
395
+ else if (ts.isModuleDeclaration(statement) &&
396
+ statement.body &&
397
+ ts.isModuleBlock(statement.body)) {
398
+ // `declare global { interface Window {} }`, which Bascik wraps around a global interface.
399
+ visitStatements(statement.body.statements);
400
+ }
401
+ }
402
+ };
403
+ visitStatements(source.statements);
404
+ return starts;
405
+ }
406
+ const CLASSIC_SCRIPT_NOTE = 'A type="text/typescript" block runs in the browser as a classic script, not a module.';
407
+ /** The `await` keywords at the top level of a client block's virtual file, before its footer. */
408
+ function topLevelAwaits(ts, source, footerStart) {
409
+ const found = [];
410
+ const visit = (node) => {
411
+ // Inside a function `await` is the function's business, which TypeScript checks.
412
+ if (ts.isFunctionLike(node) || node.pos >= footerStart)
413
+ return;
414
+ if (ts.isAwaitExpression(node)) {
415
+ const start = node.getStart(source);
416
+ found.push({
417
+ start,
418
+ end: start + "await".length,
419
+ report: {
420
+ // TypeScript's own message and number for `await` outside an async function and a module.
421
+ message: `'await' expressions are only allowed within async functions and at the top levels of modules. ${CLASSIC_SCRIPT_NOTE}`,
422
+ code: 1308,
423
+ category: "error",
424
+ },
425
+ });
426
+ }
427
+ else if (ts.isForOfStatement(node) && node.awaitModifier) {
428
+ found.push({
429
+ start: node.awaitModifier.getStart(source),
430
+ end: node.awaitModifier.end,
431
+ report: {
432
+ message: `'for await' loops are only allowed within async functions and at the top levels of modules. ${CLASSIC_SCRIPT_NOTE}`,
433
+ code: 1103,
434
+ category: "error",
435
+ },
436
+ });
437
+ }
438
+ ts.forEachChild(node, visit);
439
+ };
440
+ ts.forEachChild(source, visit);
441
+ return found;
442
+ }
443
+ /** The offset where each line of `text` starts. */
444
+ function lineStarts(text) {
445
+ const starts = [0];
446
+ for (let index = text.indexOf("\n"); index >= 0; index = text.indexOf("\n", index + 1))
447
+ starts.push(index + 1);
448
+ return starts;
449
+ }
450
+ /** The line and character of an offset, from `lineStarts`. */
451
+ function positionIn(starts, offset) {
452
+ let low = 0;
453
+ let high = starts.length - 1;
454
+ while (low < high) {
455
+ const middle = (low + high + 1) >> 1;
456
+ if (starts[middle] <= offset)
457
+ low = middle;
458
+ else
459
+ high = middle - 1;
460
+ }
461
+ return { line: low, character: offset - starts[low] };
462
+ }
463
+ /**
464
+ * The TypeScript blocks of one project: two LanguageServices (client and server), the virtual files of every
465
+ * HTML file it was given, and the versions that tell TypeScript what changed.
466
+ */
467
+ export class TypeScriptProject {
468
+ projectRoot;
469
+ importRoot;
470
+ ts;
471
+ readOpenFile;
472
+ files = new Map();
473
+ pages = new Map();
474
+ /** Versions of real files reported changed (an editor buffer or a file on disk). */
475
+ fileVersions = new Map();
476
+ /** `client` and `server`, and a page's own client service once it augments the globals (see `serviceKey`). */
477
+ services = new Map();
478
+ registry;
479
+ cancellationToken;
480
+ clientOptions;
481
+ projectVersion = 0;
482
+ nextFileVersion = 1;
483
+ /** How many times a program was brought up to date with a changed project (see `programUpdates`). */
484
+ updates = 0;
485
+ /**
486
+ * Whether directive scripts get their types from `@bascik/bascik`. It turns false the first time the typed
487
+ * footer fails to resolve (no `@bascik/bascik`, or one from before the types), until the project is made again.
488
+ */
489
+ scriptTypes = true;
490
+ /** Node's untyped globals and modules for the server program, when the project has no `@types/node`. */
491
+ nodeDeclarations;
492
+ /** Each program's compiler options, for `missingLibraryFiles`. */
493
+ programOptions = [];
494
+ /** `readClassicScript` results by kind and text: most scripts do not change between edits. */
495
+ scriptInfo = new Map();
496
+ /**
497
+ * Files and folders TypeScript looked for and did not find, while resolving an import. Creating one of them
498
+ * (or a file inside one of the folders) can make a failed import resolve, which TypeScript does not notice on
499
+ * its own: a block whose text did not change keeps its old resolutions.
500
+ */
501
+ missingPaths = new Set();
502
+ /** Files TypeScript read: deleting one can make an import fail. */
503
+ foundFiles = new Set();
504
+ /**
505
+ * Bumped when a file TypeScript looked for appears or disappears. It is part of every project file's version
506
+ * (not a library's or a package's), so TypeScript parses those files again and resolves their imports anew: a
507
+ * file whose version did not change keeps its old resolutions.
508
+ */
509
+ resolutionGeneration = 0;
510
+ /** The globals the client program's libraries declare, such as `Window` and `close`; read on first need. */
511
+ clientGlobals;
512
+ /** The client programs' declaration of `GLOBAL_THIS_TYPE`. */
513
+ clientDeclarations;
514
+ constructor(options) {
515
+ // TypeScript keys files by absolute path with forward slashes; a relative root would make every relative
516
+ // import miss, and a Windows spelling would make TypeScript ask for files the host does not know.
517
+ this.projectRoot = tsPath(options.projectRoot);
518
+ this.importRoot = tsPath(this.projectRoot, options.importRoot);
519
+ this.ts = options.ts;
520
+ this.readOpenFile = options.readOpenFile ?? (() => undefined);
521
+ this.registry =
522
+ options.registry ??
523
+ this.ts.createDocumentRegistry(this.ts.sys.useCaseSensitiveFileNames, this.projectRoot);
524
+ this.cancellationToken = {
525
+ isCancellationRequested: options.isCancellationRequested ?? (() => false),
526
+ throwIfCancellationRequested: () => {
527
+ if (options.isCancellationRequested?.())
528
+ throw new this.ts.OperationCanceledException();
529
+ },
530
+ };
531
+ const nodeTypes = hasNodeTypes(this.projectRoot);
532
+ this.nodeDeclarations = nodeTypes
533
+ ? undefined
534
+ : {
535
+ fileName: `${this.projectRoot}/__bascik-node-globals.d.ts`,
536
+ text: untypedNodeDeclarations(),
537
+ };
538
+ this.clientDeclarations = {
539
+ fileName: `${this.projectRoot}/__bascik-client-globals.d.ts`,
540
+ text: `// The real globalThis, for pages that redeclare it with their classic globals.\ntype ${GLOBAL_THIS_TYPE} = typeof globalThis;\n`,
541
+ };
542
+ this.clientOptions = compilerOptionsFor(this.ts, this.projectRoot, this.importRoot, "client", nodeTypes);
543
+ const serverOptions = compilerOptionsFor(this.ts, this.projectRoot, this.importRoot, "server", nodeTypes);
544
+ this.programOptions.push(this.clientOptions, serverOptions);
545
+ this.services.set("client", this.createService("client", "client"));
546
+ this.services.set("server", this.ts.createLanguageService(this.host("server", "server", serverOptions), this.registry));
547
+ }
548
+ /**
549
+ * The service a virtual file is checked by. A page whose client blocks add to the browser's globals (a
550
+ * `declare global`, or an interface such as `Window` that Bascik wraps in one) is kept out of the shared client
551
+ * service, where its additions would reach every other page although no two pages run together. Pages whose
552
+ * additions are written the same and refer to none of their own names (the same analytics snippet on every page)
553
+ * mean the same thing, and share a service; any other such page gets one of its own. A page that uses components
554
+ * whose blocks add to the globals is kept out too, as their additions hold on it (`componentBlocks`, each
555
+ * `path#index`); pages that use the same ones share a service.
556
+ */
557
+ serviceKey(program, htmlPath, augmentations, componentBlocks = []) {
558
+ if (program === "server")
559
+ return "server";
560
+ const texts = augmentations?.texts ?? [];
561
+ if (texts.length === 0 && componentBlocks.length === 0)
562
+ return "client";
563
+ const refersToPage = texts.some((text) => (text.match(/[A-Za-z_$][\w$]*/g) ?? []).some((word) => augmentations.localNames.has(word)));
564
+ if (refersToPage)
565
+ return `page:${htmlPath}`;
566
+ // Pages that use the same augmenting components share a service, apart from those components' own pages.
567
+ const uses = componentBlocks.length === 0
568
+ ? ""
569
+ : `\nuses:${componentBlocks.join("\n")}`;
570
+ return `globals:${texts.join("\n")}${uses}`;
571
+ }
572
+ createService(program, key) {
573
+ return this.ts.createLanguageService(this.host(program, key, this.clientOptions), this.registry);
574
+ }
575
+ serviceFor(key) {
576
+ let service = this.services.get(key);
577
+ if (!service) {
578
+ service = this.createService("client", key);
579
+ this.services.set(key, service);
580
+ }
581
+ return service;
582
+ }
583
+ /** Drops a client service of pages that augment the globals, once no page uses it. */
584
+ dropService(key) {
585
+ if (key === undefined || key === "client" || key === "server")
586
+ return;
587
+ for (const page of this.pages.values())
588
+ if (page.clientService === key)
589
+ return;
590
+ this.services.get(key)?.dispose();
591
+ this.services.delete(key);
592
+ }
593
+ /**
594
+ * The library files either program loads that the TypeScript copy does not have, such as one the project's
595
+ * `tsconfig.json` adds to `lib`. Checking without them would report every use of their globals.
596
+ */
597
+ missingLibraryFiles() {
598
+ const missing = new Set();
599
+ for (const options of this.programOptions) {
600
+ const libDir = path.dirname(this.ts.getDefaultLibFilePath(options));
601
+ for (const name of options.lib ?? []) {
602
+ if (!this.ts.sys.fileExists(path.join(libDir, name)))
603
+ missing.add(name);
604
+ }
605
+ }
606
+ return [...missing];
607
+ }
608
+ host(program, key, options) {
609
+ const cancellationToken = this.cancellationToken;
610
+ const ts = this.ts;
611
+ // TypeScript's own library files, wherever the copy sits (a client path need not be under node_modules).
612
+ const libDir = tsPath(path.dirname(ts.getDefaultLibFilePath(options))) + "/";
613
+ return {
614
+ getProjectVersion: () => String(this.projectVersion),
615
+ getCompilationSettings: () => options,
616
+ getScriptFileNames: () => {
617
+ // TypeScript asks only when the project version changed, before it builds the program again.
618
+ this.updates++;
619
+ const names = [...this.files.values()]
620
+ .filter((file) => file.service === key)
621
+ .map((file) => file.fileName);
622
+ if (program === "server" && this.nodeDeclarations)
623
+ names.push(this.nodeDeclarations.fileName);
624
+ if (program === "client")
625
+ names.push(this.clientDeclarations.fileName);
626
+ return names;
627
+ },
628
+ getScriptVersion: (fileName) => {
629
+ const version = this.files.get(fileName)?.version ??
630
+ this.fileVersions.get(tsPath(fileName)) ??
631
+ 0;
632
+ return isPackageFile(fileName) || fileName.startsWith(libDir)
633
+ ? String(version)
634
+ : `${version}.${this.resolutionGeneration}`;
635
+ },
636
+ getScriptSnapshot: (fileName) => {
637
+ const text = this.readFile(fileName);
638
+ return text === undefined
639
+ ? undefined
640
+ : ts.ScriptSnapshot.fromString(text);
641
+ },
642
+ getCurrentDirectory: () => this.projectRoot,
643
+ getDefaultLibFileName: (compilerOptions) => ts.getDefaultLibFilePath(compilerOptions),
644
+ fileExists: (fileName) => {
645
+ const exists = this.files.has(fileName) ||
646
+ fileName === this.nodeDeclarations?.fileName ||
647
+ fileName === this.clientDeclarations.fileName ||
648
+ this.readOpenFile(tsPath(fileName)) !== undefined ||
649
+ ts.sys.fileExists(fileName);
650
+ this.recordLookup(fileName, exists);
651
+ return exists;
652
+ },
653
+ readFile: (fileName) => this.readFile(fileName),
654
+ readDirectory: ts.sys.readDirectory,
655
+ directoryExists: (directoryName) => {
656
+ const exists = ts.sys.directoryExists(directoryName);
657
+ this.recordLookup(directoryName, exists);
658
+ return exists;
659
+ },
660
+ getDirectories: ts.sys.getDirectories,
661
+ realpath: ts.sys.realpath,
662
+ useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
663
+ getCancellationToken: () => cancellationToken,
664
+ };
665
+ }
666
+ recordLookup(fsPath, exists) {
667
+ // Package files never appear mid-session in a way that matters here.
668
+ if (isPackageFile(fsPath))
669
+ return;
670
+ if (exists)
671
+ this.foundFiles.add(path.resolve(fsPath));
672
+ else
673
+ this.missingPaths.add(path.resolve(fsPath));
674
+ }
675
+ readFile(fileName) {
676
+ const virtual = this.files.get(fileName);
677
+ if (virtual)
678
+ return virtual.text;
679
+ if (fileName === this.nodeDeclarations?.fileName)
680
+ return this.nodeDeclarations.text;
681
+ if (fileName === this.clientDeclarations.fileName)
682
+ return this.clientDeclarations.text;
683
+ return (this.readOpenFile(tsPath(fileName)) ?? this.ts.sys.readFile(fileName));
684
+ }
685
+ /** What a client script declares and how it parses, cached by its text. */
686
+ classicScript(content, typed) {
687
+ const key = `${typed ? "ts" : "js"}:${content}`;
688
+ let info = this.scriptInfo.get(key);
689
+ if (!info) {
690
+ // Bounded: an edit makes a new entry per keystroke, and old texts are rarely seen again.
691
+ if (this.scriptInfo.size >= 500)
692
+ this.scriptInfo.clear();
693
+ info = readClassicScript(this.ts, content, typed);
694
+ this.scriptInfo.set(key, info);
695
+ }
696
+ return info;
697
+ }
698
+ libraryGlobals() {
699
+ if (!this.clientGlobals) {
700
+ const options = this.clientOptions;
701
+ const libDir = path.dirname(this.ts.getDefaultLibFilePath(options));
702
+ const globals = {
703
+ interfaces: new Set(),
704
+ values: new Set(),
705
+ };
706
+ const seen = new Set();
707
+ for (const lib of options.lib ?? [])
708
+ globalsOf(this.ts, libDir, lib, globals, seen);
709
+ this.clientGlobals = globals;
710
+ }
711
+ return this.clientGlobals;
712
+ }
713
+ /**
714
+ * How a page's shared text declares the names of the page's classic scripts. `typed` are the infos of the typed
715
+ * blocks it joins, `untyped` those of every other classic script in the page's scope (plain scripts, components'
716
+ * scripts, blocks left out for a syntax error).
717
+ */
718
+ pageGlobals(typed, untyped) {
719
+ const declared = new Set(typed.flatMap((info) => info.names));
720
+ const ambient = new Set();
721
+ const assignedElsewhere = new Set();
722
+ for (const info of untyped)
723
+ for (const name of info.names)
724
+ (declared.has(name) ? assignedElsewhere : ambient).add(name);
725
+ const members = new Map();
726
+ for (const [infos, isTyped] of [
727
+ [typed, true],
728
+ [untyped, false],
729
+ ])
730
+ for (const info of infos)
731
+ for (const name of info.windowNames)
732
+ if (!members.has(name))
733
+ members.set(name, isTyped);
734
+ // A name the DOM already declares (`name`, `close`, `length`) keeps the DOM's type on `window`. The library
735
+ // is scanned only for a page that has such names at all.
736
+ if (members.size > 0) {
737
+ const libraryValues = this.libraryGlobals().values;
738
+ for (const name of members.keys())
739
+ if (libraryValues.has(name))
740
+ members.delete(name);
741
+ }
742
+ const objects = GLOBAL_OBJECTS.filter((object) => !declared.has(object) && !ambient.has(object));
743
+ for (const object of GLOBAL_OBJECTS)
744
+ members.delete(object);
745
+ return {
746
+ // A name a block declares itself is the block's: declaring it again would be reported as a redeclaration.
747
+ ambientNames: [...ambient],
748
+ globalObjects: {
749
+ members: [...members].map(([name, isTyped]) => ({
750
+ name,
751
+ typed: isTyped,
752
+ })),
753
+ objects,
754
+ },
755
+ assignedElsewhere: [...assignedElsewhere],
756
+ };
757
+ }
758
+ /** Adds what a client script adds to the browser's globals, and the names it declares, to `into`. */
759
+ collectAugmentations(info, into) {
760
+ const globals = this.libraryGlobals().interfaces;
761
+ for (const declaration of info.interfaces)
762
+ if (globals.has(declaration.name))
763
+ into.texts.push(declaration.text);
764
+ else
765
+ into.localNames.add(declaration.name);
766
+ into.texts.push(...info.globalAugmentations);
767
+ for (const name of [...info.names, ...info.localNames])
768
+ into.localNames.add(name);
769
+ }
770
+ /**
771
+ * In a classic script, a top-level `interface Window { ... }` adds to the global interface; the block is checked
772
+ * as a module, where it would declare a new one. Wrapping it in `declare global { }` keeps the browser's meaning.
773
+ */
774
+ globalInterfaceWraps(info) {
775
+ const insertions = [];
776
+ const globals = info.interfaces.length > 0
777
+ ? this.libraryGlobals().interfaces
778
+ : new Set();
779
+ for (const declaration of info.interfaces) {
780
+ if (!globals.has(declaration.name))
781
+ continue;
782
+ insertions.push({ at: declaration.start, text: "declare global { " }, { at: declaration.end, text: " }" });
783
+ }
784
+ return insertions;
785
+ }
786
+ /**
787
+ * The client blocks of the components a page uses that add to the browser's globals (a `declare global`, or an
788
+ * interface such as `Window` that Bascik wraps in one), each as the virtual text it is checked as on its own.
789
+ * The page's service gets a copy of each, so their additions hold on the page; the rest of a component's code
790
+ * is never reported there. A block mid-edit (a syntax error) adds nothing.
791
+ */
792
+ componentGlobalBlocks(usedComponents) {
793
+ const found = [];
794
+ for (const component of usedComponents) {
795
+ const fsPath = tsPath(this.projectRoot, component.fsPath);
796
+ for (const block of extractTypeScriptBlocks(component.text)) {
797
+ if (block.program !== "client")
798
+ continue;
799
+ const info = this.classicScript(block.content, true);
800
+ if (info.syntaxErrors.length > 0)
801
+ continue;
802
+ const additions = { texts: [], localNames: new Set() };
803
+ this.collectAugmentations(info, additions);
804
+ if (additions.texts.length === 0)
805
+ continue;
806
+ found.push({
807
+ key: `${fsPath}#${block.index}`,
808
+ fsPath,
809
+ block,
810
+ virtual: this.virtualFile(block),
811
+ });
812
+ }
813
+ }
814
+ return found;
815
+ }
816
+ /** Deletes the component files no page lists any more. True when one was deleted. */
817
+ dropComponentFiles(fileNames) {
818
+ if (fileNames.length === 0)
819
+ return false;
820
+ const listed = new Set();
821
+ for (const page of this.pages.values())
822
+ for (const fileName of page.componentFileNames)
823
+ listed.add(fileName);
824
+ let dropped = false;
825
+ for (const fileName of fileNames)
826
+ if (!listed.has(fileName) && this.files.delete(fileName))
827
+ dropped = true;
828
+ return dropped;
829
+ }
830
+ /**
831
+ * Records an HTML file's text. Only virtual files whose text changed get a new version, so TypeScript reuses
832
+ * what it knows about the rest.
833
+ */
834
+ updatePage(htmlPath, text, options = {}) {
835
+ htmlPath = tsPath(this.projectRoot, htmlPath);
836
+ const isolatedClientBlocks = options.isolatedClientBlocks === true;
837
+ const pageScopeHtml = isolatedClientBlocks
838
+ ? []
839
+ : (options.pageScopeHtml ?? []);
840
+ const usedComponents = options.usedComponents ?? [];
841
+ const previous = this.pages.get(htmlPath);
842
+ if (previous?.text === text &&
843
+ previous.isolatedClientBlocks === isolatedClientBlocks &&
844
+ previous.pageScopeHtml.length === pageScopeHtml.length &&
845
+ previous.pageScopeHtml.every((html, index) => html === pageScopeHtml[index]) &&
846
+ previous.usedComponents.length === usedComponents.length &&
847
+ previous.usedComponents.every((component, index) => component.fsPath === usedComponents[index].fsPath &&
848
+ component.text === usedComponents[index].text))
849
+ return;
850
+ const blocks = extractTypeScriptBlocks(text);
851
+ const units = [];
852
+ const blockErrors = [];
853
+ const augmentations = { texts: [], localNames: new Set() };
854
+ if (!isolatedClientBlocks) {
855
+ const shared = this.sharedClientText(text, blocks, pageScopeHtml, augmentations);
856
+ blockErrors.push(...shared.blockErrors);
857
+ if (shared.virtual)
858
+ units.push({
859
+ fileName: `${htmlPath}.bascik-client.ts`,
860
+ program: "client",
861
+ sharedScope: true,
862
+ virtual: shared.virtual,
863
+ });
864
+ }
865
+ for (const block of blocks) {
866
+ if (block.program === "client" && !isolatedClientBlocks)
867
+ continue;
868
+ if (block.program === "client")
869
+ this.collectAugmentations(this.classicScript(block.content, true), augmentations);
870
+ units.push({
871
+ fileName: `${htmlPath}.bascik-${block.index}.ts`,
872
+ program: block.program,
873
+ sharedScope: false,
874
+ virtual: this.virtualFile(block),
875
+ });
876
+ }
877
+ const componentBlocks = units.some((unit) => unit.program === "client")
878
+ ? this.componentGlobalBlocks(usedComponents)
879
+ : [];
880
+ const clientService = this.serviceKey("client", htmlPath, augmentations, componentBlocks.map(({ key }) => key));
881
+ let changed = false;
882
+ for (const { fileName, program, sharedScope, virtual } of units) {
883
+ const existing = this.files.get(fileName);
884
+ const service = program === "client"
885
+ ? clientService
886
+ : this.serviceKey(program, htmlPath, undefined);
887
+ if (existing &&
888
+ existing.text === virtual.text &&
889
+ existing.program === program &&
890
+ existing.service === service) {
891
+ // Same text; only the offsets moved (an edit above the block).
892
+ existing.segments = virtual.segments;
893
+ existing.footerStart = virtual.footerStart;
894
+ existing.footerCheck = virtual.footerCheck;
895
+ existing.assignedElsewhere = virtual.assignedElsewhere;
896
+ continue;
897
+ }
898
+ changed = true;
899
+ this.files.set(fileName, {
900
+ ...virtual,
901
+ fileName,
902
+ htmlPath,
903
+ program,
904
+ service,
905
+ sharedScope,
906
+ version: this.nextFileVersion++,
907
+ });
908
+ }
909
+ const fileNames = units.map((unit) => unit.fileName);
910
+ const kept = new Set(fileNames);
911
+ for (const fileName of previous?.fileNames ?? []) {
912
+ if (kept.has(fileName))
913
+ continue;
914
+ this.files.delete(fileName);
915
+ changed = true;
916
+ }
917
+ if (previous?.editingFileName &&
918
+ this.files.delete(previous.editingFileName))
919
+ changed = true;
920
+ const componentFileNames = [];
921
+ for (const { fsPath, block, virtual } of componentBlocks) {
922
+ const fileName = `${fsPath}.bascik-${block.index}.global-${shortHash(clientService)}.ts`;
923
+ componentFileNames.push(fileName);
924
+ const existing = this.files.get(fileName);
925
+ if (existing?.text === virtual.text)
926
+ continue;
927
+ changed = true;
928
+ this.files.set(fileName, {
929
+ ...virtual,
930
+ fileName,
931
+ htmlPath: fsPath,
932
+ program: "client",
933
+ service: clientService,
934
+ sharedScope: false,
935
+ version: this.nextFileVersion++,
936
+ });
937
+ }
938
+ this.pages.set(htmlPath, {
939
+ text,
940
+ isolatedClientBlocks,
941
+ pageScopeHtml,
942
+ usedComponents,
943
+ fileNames,
944
+ componentFileNames,
945
+ clientService,
946
+ blockErrors,
947
+ });
948
+ if (this.dropComponentFiles(previous?.componentFileNames ?? []))
949
+ changed = true;
950
+ if (previous && previous.clientService !== clientService)
951
+ this.dropService(previous.clientService);
952
+ if (changed)
953
+ this.projectVersion++;
954
+ }
955
+ /**
956
+ * A page's client blocks as the one classic script the browser runs them as. A block with a syntax error does
957
+ * not run at all in a browser, while the others do, so it is left out and reported on its own; its names stay
958
+ * declared (`any`), so the error is not repeated as unknown names in the blocks after it. The page's plain
959
+ * JavaScript scripts and the component scripts that share its scope add their names the same way.
960
+ */
961
+ sharedClientText(text, blocks, pageScopeHtml, augmentations) {
962
+ const blockErrors = [];
963
+ const client = blocks.filter((block) => block.program === "client");
964
+ if (client.length === 0)
965
+ return { blockErrors };
966
+ const valid = [];
967
+ const insertions = new Map();
968
+ const typed = [];
969
+ const untyped = [];
970
+ for (const block of client) {
971
+ const info = this.classicScript(block.content, true);
972
+ if (info.syntaxErrors.length > 0) {
973
+ for (const error of info.syntaxErrors)
974
+ blockErrors.push({
975
+ ...error,
976
+ start: block.contentStart + error.start,
977
+ end: block.contentStart + error.end,
978
+ category: "error",
979
+ });
980
+ untyped.push(info);
981
+ continue;
982
+ }
983
+ valid.push(block);
984
+ typed.push(info);
985
+ const wraps = this.globalInterfaceWraps(info);
986
+ if (wraps.length > 0)
987
+ insertions.set(block.index, wraps);
988
+ this.collectAugmentations(info, augmentations);
989
+ }
990
+ if (valid.length === 0)
991
+ return { blockErrors };
992
+ untyped.push(...this.otherPageScopeScripts(text, pageScopeHtml));
993
+ // An addition that names a plain script's global refers to this page too.
994
+ for (const info of untyped)
995
+ for (const name of info.names)
996
+ augmentations.localNames.add(name);
997
+ return {
998
+ virtual: sharedScriptText(valid, {
999
+ insertions,
1000
+ ...this.pageGlobals(typed, untyped),
1001
+ }),
1002
+ blockErrors,
1003
+ };
1004
+ }
1005
+ /** The page's plain classic scripts, and the scripts of components that run in its scope. */
1006
+ otherPageScopeScripts(text, pageScopeHtml) {
1007
+ return [
1008
+ ...extractPageScopeScripts(text).filter((script) => !script.typed),
1009
+ ...pageScopeHtml.flatMap((html) => extractPageScopeScripts(html)),
1010
+ ].map((script) => this.classicScript(script.content, script.typed));
1011
+ }
1012
+ virtualFile(block) {
1013
+ if (block.directive === undefined)
1014
+ return virtualBlockText(block, this.globalInterfaceWraps(this.classicScript(block.content, true)), this.scriptTypes);
1015
+ const plan = defaultExportPlan(this.ts, block.content);
1016
+ return virtualBlockText(block, plan.insertions, this.scriptTypes, plan.check);
1017
+ }
1018
+ /** Rewrites every directive block with the untyped footer, after the typed one failed to resolve. */
1019
+ dropScriptTypes() {
1020
+ this.scriptTypes = false;
1021
+ const pages = [...this.pages];
1022
+ this.pages.clear();
1023
+ for (const [htmlPath, page] of pages)
1024
+ this.updatePage(htmlPath, page.text, page);
1025
+ }
1026
+ /** Forgets an HTML file, so its blocks are no longer part of either program. */
1027
+ removePage(htmlPath) {
1028
+ htmlPath = tsPath(this.projectRoot, htmlPath);
1029
+ const page = this.pages.get(htmlPath);
1030
+ if (!page)
1031
+ return;
1032
+ for (const fileName of page.fileNames)
1033
+ this.files.delete(fileName);
1034
+ if (page.editingFileName)
1035
+ this.files.delete(page.editingFileName);
1036
+ this.pages.delete(htmlPath);
1037
+ this.dropComponentFiles(page.componentFileNames);
1038
+ this.dropService(page.clientService);
1039
+ this.projectVersion++;
1040
+ }
1041
+ /**
1042
+ * How many times either program was brought up to date with a changed project. Each one makes TypeScript build
1043
+ * a new program and type checker, and work out the libraries' globals again, so pages are given to the project
1044
+ * together (`updatePage` for each, then `diagnostics`) rather than one per check.
1045
+ */
1046
+ get programUpdates() {
1047
+ return this.updates;
1048
+ }
1049
+ /** How many LanguageServices the project holds: client, server, and those of pages that augment the globals. */
1050
+ get serviceCount() {
1051
+ return this.services.size;
1052
+ }
1053
+ /** A file the blocks may import changed, appeared or disappeared, in an editor buffer or on disk. */
1054
+ fileChanged(fsPath) {
1055
+ fsPath = path.resolve(fsPath);
1056
+ this.fileVersions.set(tsPath(fsPath), this.nextFileVersion++);
1057
+ this.projectVersion++;
1058
+ let appeared = false;
1059
+ for (let current = fsPath; !appeared; current = path.dirname(current)) {
1060
+ appeared = this.missingPaths.has(current);
1061
+ if (path.dirname(current) === current)
1062
+ break;
1063
+ }
1064
+ const disappeared = this.foundFiles.has(fsPath) &&
1065
+ this.readOpenFile(tsPath(fsPath)) === undefined &&
1066
+ !this.ts.sys.fileExists(fsPath);
1067
+ if (appeared || disappeared) {
1068
+ this.resolutionGeneration++;
1069
+ // Recorded again as the programs resolve their imports anew.
1070
+ this.missingPaths.clear();
1071
+ this.foundFiles.clear();
1072
+ }
1073
+ }
1074
+ /** The TypeScript errors and warnings of an HTML file's blocks, located in its text. */
1075
+ diagnostics(htmlPath, text, options = {}) {
1076
+ htmlPath = tsPath(this.projectRoot, htmlPath);
1077
+ this.updatePage(htmlPath, text, options);
1078
+ const page = this.pages.get(htmlPath);
1079
+ const result = [...(page?.blockErrors ?? [])];
1080
+ for (const fileName of page?.fileNames ?? []) {
1081
+ const file = this.files.get(fileName);
1082
+ const service = this.serviceFor(file.service);
1083
+ const syntactic = service.getSyntacticDiagnostics(fileName);
1084
+ let semantic = service.getSemanticDiagnostics(fileName);
1085
+ // A var another classic script declares may have been assigned there, before this block runs.
1086
+ const assignedElsewhere = new Set(file.assignedElsewhere);
1087
+ if (assignedElsewhere.size > 0)
1088
+ semantic = semantic.filter((diagnostic) => diagnostic.code !== USED_BEFORE_ASSIGNED ||
1089
+ diagnostic.start === undefined ||
1090
+ !assignedElsewhere.has(file.text.slice(diagnostic.start, diagnostic.start + (diagnostic.length ?? 0))));
1091
+ if (file.sharedScope && semantic.some((d) => UNUSED_CODES.has(d.code))) {
1092
+ const source = service.getProgram()?.getSourceFile(fileName);
1093
+ if (source) {
1094
+ const globals = topLevelNameStarts(this.ts, source, file.footerStart);
1095
+ semantic = semantic.filter((diagnostic) => !UNUSED_CODES.has(diagnostic.code) ||
1096
+ diagnostic.start === undefined ||
1097
+ !globals.has(diagnostic.start));
1098
+ }
1099
+ }
1100
+ // A type error in Bascik's footer means @bascik/bascik's script types are not there: check without them.
1101
+ // Not while the block has a syntax error, which can swallow the footer (an unclosed brace or comment).
1102
+ const inFooterCheck = (diagnostic) => file.footerCheck !== undefined &&
1103
+ diagnostic.start !== undefined &&
1104
+ diagnostic.start >= file.footerCheck.generatedStart &&
1105
+ diagnostic.start < file.footerCheck.generatedEnd;
1106
+ if (this.scriptTypes &&
1107
+ file.program === "server" &&
1108
+ syntactic.length === 0 &&
1109
+ semantic.some((diagnostic) => (diagnostic.start ?? 0) >= file.footerStart &&
1110
+ !inFooterCheck(diagnostic))) {
1111
+ this.dropScriptTypes();
1112
+ return this.diagnostics(htmlPath, text, options);
1113
+ }
1114
+ const syntacticSet = new Set(syntactic);
1115
+ for (const diagnostic of [...syntactic, ...semantic]) {
1116
+ if (diagnostic.start === undefined)
1117
+ continue;
1118
+ if (diagnostic.category !== this.ts.DiagnosticCategory.Error &&
1119
+ diagnostic.category !== this.ts.DiagnosticCategory.Warning)
1120
+ continue;
1121
+ const message = withoutGlobalObjectAliases(this.ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
1122
+ const category = diagnostic.category === this.ts.DiagnosticCategory.Error
1123
+ ? "error"
1124
+ : "warning";
1125
+ // The footer's check of a named default export: the function does not fit the script's type. It is the
1126
+ // author's error, located on the function's name.
1127
+ if (file.footerCheck && inFooterCheck(diagnostic)) {
1128
+ result.push({
1129
+ start: file.footerCheck.sourceStart,
1130
+ end: file.footerCheck.sourceEnd,
1131
+ message,
1132
+ code: diagnostic.code,
1133
+ category,
1134
+ });
1135
+ continue;
1136
+ }
1137
+ // A syntax error found in the footer is the author's (an unclosed brace runs past the block's end): it is
1138
+ // reported at the end of the block. A type error there is Bascik's, not theirs to fix.
1139
+ const inFooter = diagnostic.start >= file.footerStart;
1140
+ if (inFooter && !syntacticSet.has(diagnostic))
1141
+ continue;
1142
+ const start = Math.min(diagnostic.start, file.footerStart);
1143
+ const end = Math.min(diagnostic.start + (diagnostic.length ?? 0), file.footerStart);
1144
+ result.push({
1145
+ start: toSourceOffset(file, start),
1146
+ end: toSourceOffset(file, Math.max(start, end)),
1147
+ message,
1148
+ code: diagnostic.code,
1149
+ category,
1150
+ });
1151
+ }
1152
+ // A client block runs as a classic script (wrapped in a function in a component), never as a module, so
1153
+ // top-level `await` fails in the browser although TypeScript accepts it in the module the block is checked as.
1154
+ if (file.program === "client" && syntactic.length === 0) {
1155
+ const source = service.getProgram()?.getSourceFile(fileName);
1156
+ if (source) {
1157
+ for (const found of topLevelAwaits(this.ts, source, file.footerStart))
1158
+ result.push({
1159
+ start: toSourceOffset(file, found.start),
1160
+ end: toSourceOffset(file, found.end),
1161
+ ...found.report,
1162
+ });
1163
+ }
1164
+ }
1165
+ }
1166
+ return result.sort((a, b) => a.start - b.start || a.end - b.end);
1167
+ }
1168
+ /**
1169
+ * Answers a language feature at an offset of an HTML file, inside one of its TypeScript blocks; `undefined`
1170
+ * outside them or with nothing to say. See `typescript-features.ts`.
1171
+ */
1172
+ feature(htmlPath, text, options, query) {
1173
+ htmlPath = tsPath(this.projectRoot, htmlPath);
1174
+ this.updatePage(htmlPath, text, options);
1175
+ const at = this.virtualOffset(htmlPath, text, query.offset);
1176
+ if (!at)
1177
+ return undefined;
1178
+ const { file, generated } = at;
1179
+ const service = this.serviceFor(file.service);
1180
+ const libDir = tsPath(path.dirname(this.ts.getDefaultLibFilePath(this.clientOptions)));
1181
+ const isVirtual = (fileName) => this.files.has(fileName) ||
1182
+ fileName === this.nodeDeclarations?.fileName ||
1183
+ fileName === this.clientDeclarations.fileName;
1184
+ // A block VS Code's HTML support does not embed gets nothing from its modes: every answer is Bascik's. One it
1185
+ // embeds as JavaScript (an uppercase `TYPE`) gets the page-local answers from its JavaScript mode.
1186
+ const editorLanguage = query.crossFileOnly === true
1187
+ ? typeScriptBlockAt(text, query.offset)?.editorLanguage
1188
+ : undefined;
1189
+ const crossFileOnly = editorLanguage !== undefined;
1190
+ const isForeign = crossFileOnly
1191
+ ? (fileName) => !isVirtual(fileName) && tsPath(path.dirname(fileName)) !== libDir
1192
+ : everyFile;
1193
+ const lines = lineStarts(text);
1194
+ return answerFeature({
1195
+ ts: this.ts,
1196
+ service,
1197
+ fileName: file.fileName,
1198
+ generated,
1199
+ file,
1200
+ isForeign,
1201
+ editor: editorLanguage === undefined
1202
+ ? undefined
1203
+ : editorModeMirror(this.ts, editorLanguage).at(text, query.offset),
1204
+ toSource: (offset) => offset > file.footerStart ? undefined : toSourceOffset(file, offset),
1205
+ locate: (fileName, start, end) => {
1206
+ const virtual = this.files.get(fileName);
1207
+ if (virtual) {
1208
+ if (virtual.htmlPath !== htmlPath || start >= virtual.footerStart)
1209
+ return undefined;
1210
+ return {
1211
+ // The page's own path, in the platform's spelling like every other location.
1212
+ fsPath: path.resolve(htmlPath),
1213
+ start: positionIn(lines, toSourceOffset(virtual, start)),
1214
+ end: positionIn(lines, toSourceOffset(virtual, Math.min(end, virtual.footerStart))),
1215
+ };
1216
+ }
1217
+ if (isVirtual(fileName))
1218
+ return undefined;
1219
+ return this.locateInFile(service, fileName, start, end);
1220
+ },
1221
+ }, query);
1222
+ }
1223
+ /** Where an HTML offset is in the page's virtual files, or `undefined` outside its blocks. */
1224
+ virtualOffset(htmlPath, text, offset) {
1225
+ const page = this.pages.get(htmlPath);
1226
+ if (!page)
1227
+ return undefined;
1228
+ for (const fileName of page.fileNames) {
1229
+ const file = this.files.get(fileName);
1230
+ const generated = toGeneratedOffset(file, offset);
1231
+ if (generated !== undefined)
1232
+ return { file, generated };
1233
+ }
1234
+ // A client block left out of the shared scope for a syntax error, as a block mid-edit often is.
1235
+ const broken = page.blockErrors.length > 0 && !page.isolatedClientBlocks;
1236
+ if (!broken)
1237
+ return undefined;
1238
+ const file = this.editingFile(htmlPath, text, page);
1239
+ const generated = file && toGeneratedOffset(file, offset);
1240
+ return file && generated !== undefined ? { file, generated } : undefined;
1241
+ }
1242
+ /** The page's client blocks, broken ones included, in one virtual file for language features (see `Page`). */
1243
+ editingFile(htmlPath, text, page) {
1244
+ if (page.editingFileName)
1245
+ return this.files.get(page.editingFileName);
1246
+ const blocks = extractTypeScriptBlocks(text).filter((block) => block.program === "client");
1247
+ if (blocks.length === 0)
1248
+ return undefined;
1249
+ const globals = this.pageGlobals(blocks.map((block) => this.classicScript(block.content, true)), this.otherPageScopeScripts(text, page.pageScopeHtml));
1250
+ const fileName = `${htmlPath}.bascik-client-editing.ts`;
1251
+ const file = {
1252
+ ...sharedScriptText(blocks, globals),
1253
+ fileName,
1254
+ htmlPath,
1255
+ program: "client",
1256
+ service: page.clientService,
1257
+ sharedScope: true,
1258
+ version: this.nextFileVersion++,
1259
+ };
1260
+ this.files.set(fileName, file);
1261
+ page.editingFileName = fileName;
1262
+ this.projectVersion++;
1263
+ return file;
1264
+ }
1265
+ /** A span of a real file by line and character, read from the program (or the file, if it holds none). */
1266
+ locateInFile(service, fileName, start, end) {
1267
+ const source = service.getProgram()?.getSourceFile(fileName);
1268
+ const text = source?.text ?? this.readFile(fileName);
1269
+ if (text === undefined)
1270
+ return undefined;
1271
+ const lines = lineStarts(text);
1272
+ return {
1273
+ fsPath: path.resolve(fileName),
1274
+ start: positionIn(lines, start),
1275
+ end: positionIn(lines, end),
1276
+ };
1277
+ }
1278
+ dispose() {
1279
+ for (const service of this.services.values())
1280
+ service.dispose();
1281
+ this.services.clear();
1282
+ }
1283
+ }
1284
+ /**
1285
+ * Every project's TypeScript blocks, keyed by project root: the synchronous engine behind the language server's
1286
+ * worker and `bascik --check`. TypeScript is looked up once per project, on the first request.
1287
+ */
1288
+ export class TypeScriptProjects {
1289
+ options;
1290
+ projects = new Map();
1291
+ resolutions = new Map();
1292
+ /** Unsaved editor buffers of files the blocks may import. */
1293
+ openFiles = new Map();
1294
+ /** One per TypeScript copy, shared by its projects. */
1295
+ registries = new Map();
1296
+ constructor(options = {}) {
1297
+ this.options = options;
1298
+ }
1299
+ resolution(projectRoot) {
1300
+ let resolution = this.resolutions.get(projectRoot);
1301
+ if (!resolution) {
1302
+ resolution =
1303
+ this.options.resolve?.(projectRoot) ??
1304
+ resolveTypeScript({
1305
+ clientPath: this.options.clientPath,
1306
+ editorPath: this.options.editorPath,
1307
+ projectRoot,
1308
+ fallbackFrom: this.options.fallbackFrom,
1309
+ });
1310
+ this.resolutions.set(projectRoot, resolution);
1311
+ }
1312
+ return resolution;
1313
+ }
1314
+ /** The project for a root and import root, made again when the import root changed. */
1315
+ project(projectRoot, importRoot) {
1316
+ const resolution = this.resolution(projectRoot);
1317
+ if (!resolution.ok)
1318
+ return resolution.message;
1319
+ let project = this.projects.get(projectRoot);
1320
+ if (project && project.importRoot !== tsPath(projectRoot, importRoot)) {
1321
+ project.dispose();
1322
+ project = undefined;
1323
+ }
1324
+ if (!project) {
1325
+ project = new TypeScriptProject({
1326
+ ts: resolution.ts,
1327
+ projectRoot,
1328
+ importRoot,
1329
+ readOpenFile: (fsPath) => this.openFiles.get(fsPath),
1330
+ isCancellationRequested: this.options.isCancellationRequested,
1331
+ registry: this.registryFor(resolution.ts),
1332
+ });
1333
+ this.projects.set(projectRoot, project);
1334
+ }
1335
+ const missing = project.missingLibraryFiles();
1336
+ if (missing.length > 0)
1337
+ return `TypeScript checks of type="text/typescript" scripts are off: TypeScript ${resolution.version} in ${resolution.packageDir} is missing library files the project's settings need: ${missing.join(", ")}. Reinstall it, or point the editor at a complete copy.`;
1338
+ return project;
1339
+ }
1340
+ registryFor(ts) {
1341
+ let registry = this.registries.get(ts);
1342
+ if (!registry) {
1343
+ registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames);
1344
+ this.registries.set(ts, registry);
1345
+ }
1346
+ return registry;
1347
+ }
1348
+ /** The TypeScript the project uses, or why it has none. */
1349
+ describe(projectRoot) {
1350
+ return this.resolution(path.resolve(projectRoot));
1351
+ }
1352
+ diagnostics(request) {
1353
+ const projectRoot = path.resolve(request.projectRoot);
1354
+ const { clientPathProblem } = this.resolution(projectRoot);
1355
+ const problem = clientPathProblem === undefined ? {} : { clientPathProblem };
1356
+ const project = this.project(projectRoot, request.importRoot);
1357
+ if (typeof project === "string")
1358
+ return { status: "unavailable", message: project, ...problem };
1359
+ try {
1360
+ return {
1361
+ status: "ok",
1362
+ ...problem,
1363
+ diagnostics: project.diagnostics(path.resolve(projectRoot, request.htmlPath), request.text, {
1364
+ isolatedClientBlocks: request.isolatedClientBlocks,
1365
+ pageScopeHtml: request.pageScopeHtml,
1366
+ usedComponents: request.usedComponents,
1367
+ }),
1368
+ };
1369
+ }
1370
+ catch (error) {
1371
+ const { ts } = this.resolution(projectRoot);
1372
+ if (error instanceof ts.OperationCanceledException)
1373
+ return { status: "cancelled" };
1374
+ throw error;
1375
+ }
1376
+ }
1377
+ /** Answers a language feature inside a page's TypeScript blocks (see `TypeScriptProject.feature`). */
1378
+ feature(request, query) {
1379
+ const projectRoot = path.resolve(request.projectRoot);
1380
+ const project = this.project(projectRoot, request.importRoot);
1381
+ if (typeof project === "string")
1382
+ return { status: "unavailable", message: project };
1383
+ try {
1384
+ return {
1385
+ status: "ok",
1386
+ answer: project.feature(path.resolve(projectRoot, request.htmlPath), request.text, {
1387
+ isolatedClientBlocks: request.isolatedClientBlocks,
1388
+ pageScopeHtml: request.pageScopeHtml,
1389
+ usedComponents: request.usedComponents,
1390
+ }, query),
1391
+ };
1392
+ }
1393
+ catch (error) {
1394
+ const { ts } = this.resolution(projectRoot);
1395
+ if (error instanceof ts.OperationCanceledException)
1396
+ return { status: "cancelled" };
1397
+ throw error;
1398
+ }
1399
+ }
1400
+ /**
1401
+ * Records the current text of several pages before any of them is checked, so the programs are brought up to
1402
+ * date once for all of them instead of once per page. Without a usable TypeScript it does nothing.
1403
+ */
1404
+ preparePages(request) {
1405
+ const projectRoot = path.resolve(request.projectRoot);
1406
+ const project = this.project(projectRoot, request.importRoot);
1407
+ if (typeof project === "string")
1408
+ return;
1409
+ for (const page of request.pages)
1410
+ project.updatePage(path.resolve(projectRoot, page.htmlPath), page.text, {
1411
+ isolatedClientBlocks: page.isolatedClientBlocks,
1412
+ pageScopeHtml: page.pageScopeHtml,
1413
+ usedComponents: page.usedComponents,
1414
+ });
1415
+ }
1416
+ /** How many times the project's programs were brought up to date (see `TypeScriptProject.programUpdates`). */
1417
+ programUpdates(projectRoot) {
1418
+ return this.projects.get(path.resolve(projectRoot))?.programUpdates ?? 0;
1419
+ }
1420
+ /** Records (or, with `undefined`, drops) the unsaved text of an editor buffer. */
1421
+ setOpenFile(fsPath, text) {
1422
+ fsPath = path.resolve(fsPath);
1423
+ // Keyed the way TypeScript asks for files, so a buffer is found on Windows too.
1424
+ if (text === undefined)
1425
+ this.openFiles.delete(tsPath(fsPath));
1426
+ else
1427
+ this.openFiles.set(tsPath(fsPath), text);
1428
+ this.fileChanged(fsPath);
1429
+ }
1430
+ /**
1431
+ * A file changed. A `tsconfig.json` remakes its project (with the new options); anything else gets a new
1432
+ * version in every project, which is cheap: TypeScript re-reads it only where a program holds it.
1433
+ */
1434
+ fileChanged(fsPath) {
1435
+ fsPath = path.resolve(fsPath);
1436
+ if (path.basename(fsPath) === "tsconfig.json") {
1437
+ this.forgetProject(path.dirname(fsPath));
1438
+ return;
1439
+ }
1440
+ if (path.basename(fsPath) === "package.json") {
1441
+ // A newly installed (or removed) typescript or @types/node.
1442
+ this.forgetProject(path.dirname(fsPath));
1443
+ this.resolutions.delete(path.dirname(fsPath));
1444
+ return;
1445
+ }
1446
+ for (const project of this.projects.values())
1447
+ project.fileChanged(fsPath);
1448
+ }
1449
+ closePage(projectRoot, htmlPath) {
1450
+ this.projects.get(path.resolve(projectRoot))?.removePage(htmlPath);
1451
+ }
1452
+ forgetProject(projectRoot) {
1453
+ projectRoot = path.resolve(projectRoot);
1454
+ this.projects.get(projectRoot)?.dispose();
1455
+ this.projects.delete(projectRoot);
1456
+ }
1457
+ /** Drops every project and the parsed files they share, which frees TypeScript's memory until the next check. */
1458
+ dispose() {
1459
+ for (const project of this.projects.values())
1460
+ project.dispose();
1461
+ this.projects.clear();
1462
+ this.registries.clear();
1463
+ }
1464
+ }
1465
+ //# sourceMappingURL=typescript-service.js.map