@astrojs/language-server 0.9.2 → 0.12.0

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 (97) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bin/browserServer.js +3 -0
  3. package/bin/nodeServer.js +3 -0
  4. package/dist/browser.d.ts +1 -0
  5. package/dist/browser.js +8 -0
  6. package/dist/check.js +2 -5
  7. package/dist/core/DiagnosticsManager.d.ts +3 -3
  8. package/dist/core/DiagnosticsManager.js +2 -2
  9. package/dist/core/config/ConfigManager.d.ts +19 -164
  10. package/dist/core/config/ConfigManager.js +62 -101
  11. package/dist/core/config/index.d.ts +1 -0
  12. package/dist/core/config/index.js +6 -1
  13. package/dist/core/config/interfaces.d.ts +123 -0
  14. package/dist/core/config/interfaces.js +2 -0
  15. package/dist/core/documents/AstroDocument.d.ts +18 -0
  16. package/dist/core/documents/AstroDocument.js +37 -0
  17. package/dist/core/documents/DocumentBase.d.ts +10 -2
  18. package/dist/core/documents/DocumentBase.js +15 -50
  19. package/dist/core/documents/DocumentManager.d.ts +12 -16
  20. package/dist/core/documents/DocumentManager.js +32 -26
  21. package/dist/core/documents/DocumentMapper.js +3 -1
  22. package/dist/core/documents/index.d.ts +1 -1
  23. package/dist/core/documents/index.js +6 -2
  24. package/dist/core/documents/parseAstro.d.ts +2 -2
  25. package/dist/core/documents/parseHtml.d.ts +2 -2
  26. package/dist/core/documents/parseHtml.js +4 -1
  27. package/dist/core/documents/utils.d.ts +22 -26
  28. package/dist/core/documents/utils.js +96 -134
  29. package/dist/index.d.ts +0 -1
  30. package/dist/index.js +1 -3
  31. package/dist/node.d.ts +1 -0
  32. package/dist/node.js +29 -0
  33. package/dist/plugins/PluginHost.d.ts +8 -9
  34. package/dist/plugins/PluginHost.js +22 -36
  35. package/dist/plugins/astro/AstroPlugin.d.ts +11 -12
  36. package/dist/plugins/astro/AstroPlugin.js +17 -38
  37. package/dist/plugins/astro/features/{CompletionProvider.d.ts → CompletionsProvider.d.ts} +5 -5
  38. package/dist/plugins/astro/features/{CompletionProvider.js → CompletionsProvider.js} +33 -54
  39. package/dist/plugins/css/CSSDocument.d.ts +3 -3
  40. package/dist/plugins/css/CSSDocument.js +7 -16
  41. package/dist/plugins/css/CSSPlugin.d.ts +19 -11
  42. package/dist/plugins/css/CSSPlugin.js +63 -41
  43. package/dist/plugins/css/StyleAttributeDocument.d.ts +2 -2
  44. package/dist/plugins/css/StyleAttributeDocument.js +2 -2
  45. package/dist/plugins/css/features/astro-selectors.d.ts +2 -0
  46. package/dist/plugins/css/features/astro-selectors.js +16 -0
  47. package/dist/plugins/css/features/{getIdClassCompletion.d.ts → getIdClassCompletions.d.ts} +3 -3
  48. package/dist/plugins/css/features/{getIdClassCompletion.js → getIdClassCompletions.js} +10 -9
  49. package/dist/plugins/css/{service.d.ts → language-service.d.ts} +0 -0
  50. package/dist/plugins/css/{service.js → language-service.js} +2 -1
  51. package/dist/plugins/html/HTMLPlugin.d.ts +15 -17
  52. package/dist/plugins/html/HTMLPlugin.js +33 -41
  53. package/dist/plugins/index.d.ts +2 -2
  54. package/dist/plugins/index.js +7 -3
  55. package/dist/plugins/interfaces.d.ts +35 -48
  56. package/dist/plugins/typescript/LanguageServiceManager.d.ts +33 -14
  57. package/dist/plugins/typescript/LanguageServiceManager.js +57 -32
  58. package/dist/plugins/typescript/TypeScriptPlugin.d.ts +16 -23
  59. package/dist/plugins/typescript/TypeScriptPlugin.js +48 -56
  60. package/dist/plugins/typescript/astro-sys.d.ts +5 -3
  61. package/dist/plugins/typescript/astro-sys.js +24 -41
  62. package/dist/plugins/typescript/features/CompletionsProvider.d.ts +6 -6
  63. package/dist/plugins/typescript/features/CompletionsProvider.js +17 -33
  64. package/dist/plugins/typescript/features/DiagnosticsProvider.d.ts +4 -4
  65. package/dist/plugins/typescript/features/DiagnosticsProvider.js +22 -61
  66. package/dist/plugins/typescript/features/HoverProvider.d.ts +4 -5
  67. package/dist/plugins/typescript/features/HoverProvider.js +9 -10
  68. package/dist/plugins/typescript/features/SignatureHelpProvider.d.ts +4 -5
  69. package/dist/plugins/typescript/features/SignatureHelpProvider.js +15 -11
  70. package/dist/plugins/typescript/features/utils.d.ts +1 -12
  71. package/dist/plugins/typescript/features/utils.js +2 -22
  72. package/dist/plugins/typescript/language-service.d.ts +38 -0
  73. package/dist/plugins/typescript/language-service.js +227 -0
  74. package/dist/plugins/typescript/module-loader.d.ts +5 -8
  75. package/dist/plugins/typescript/module-loader.js +43 -23
  76. package/dist/plugins/typescript/{DocumentSnapshot.d.ts → snapshots/DocumentSnapshot.d.ts} +45 -42
  77. package/dist/plugins/typescript/snapshots/DocumentSnapshot.js +135 -0
  78. package/dist/plugins/typescript/snapshots/SnapshotManager.d.ts +42 -0
  79. package/dist/plugins/typescript/snapshots/SnapshotManager.js +197 -0
  80. package/dist/plugins/typescript/snapshots/utils.d.ts +28 -0
  81. package/dist/plugins/typescript/snapshots/utils.js +84 -0
  82. package/dist/plugins/typescript/utils.d.ts +10 -11
  83. package/dist/plugins/typescript/utils.js +122 -151
  84. package/dist/server.d.ts +2 -4
  85. package/dist/server.js +88 -54
  86. package/dist/utils.d.ts +16 -8
  87. package/dist/utils.js +29 -14
  88. package/package.json +19 -13
  89. package/bin/server.js +0 -7
  90. package/dist/core/documents/Document.d.ts +0 -51
  91. package/dist/core/documents/Document.js +0 -135
  92. package/dist/plugins/typescript/DocumentSnapshot.js +0 -202
  93. package/dist/plugins/typescript/SnapshotManager.d.ts +0 -24
  94. package/dist/plugins/typescript/SnapshotManager.js +0 -97
  95. package/dist/plugins/typescript/languageService.d.ts +0 -17
  96. package/dist/plugins/typescript/languageService.js +0 -169
  97. package/types/index.d.ts +0 -4
@@ -10,12 +10,12 @@ const previewer_1 = require("../previewer");
10
10
  const utils_1 = require("../utils");
11
11
  const partsMap = new Map([['JSX attribute', 'HTML attribute']]);
12
12
  class HoverProviderImpl {
13
- constructor(lang) {
14
- this.lang = lang;
13
+ constructor(languageServiceManager) {
14
+ this.languageServiceManager = languageServiceManager;
15
15
  }
16
16
  async doHover(document, position) {
17
- const { lang, tsDoc } = await this.getLSAndTSDoc(document);
18
- const fragment = await tsDoc.getFragment();
17
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
18
+ const fragment = await tsDoc.createFragment();
19
19
  const offset = fragment.offsetAt(fragment.getGeneratedPosition(position));
20
20
  const filePath = (0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath);
21
21
  let info = lang.getQuickInfoAtPosition(filePath, offset);
@@ -23,21 +23,20 @@ class HoverProviderImpl {
23
23
  return null;
24
24
  }
25
25
  const textSpan = info.textSpan;
26
- const displayParts = (info.displayParts || []).map(value => ({
26
+ const displayParts = (info.displayParts || []).map((value) => ({
27
27
  text: partsMap.has(value.text) ? partsMap.get(value.text) : value.text,
28
- kind: value.kind
28
+ kind: value.kind,
29
29
  }));
30
30
  const declaration = typescript_1.default.displayPartsToString(displayParts);
31
31
  const documentation = (0, previewer_1.getMarkdownDocumentation)(info.documentation, info.tags);
32
32
  // https://microsoft.github.io/language-server-protocol/specification#textDocument_hover
33
- const contents = ['```typescript', declaration, '```'].concat(documentation ? ['---', documentation] : []).join('\n');
33
+ const contents = ['```typescript', declaration, '```']
34
+ .concat(documentation ? ['---', documentation] : [])
35
+ .join('\n');
34
36
  return (0, documents_1.mapObjWithRangeToOriginal)(fragment, {
35
37
  range: (0, utils_1.convertRange)(fragment, textSpan),
36
38
  contents,
37
39
  });
38
40
  }
39
- async getLSAndTSDoc(document) {
40
- return this.lang.getTypeScriptDoc(document);
41
- }
42
41
  }
43
42
  exports.HoverProviderImpl = HoverProviderImpl;
@@ -1,13 +1,13 @@
1
1
  import type { LanguageServiceManager } from '../LanguageServiceManager';
2
2
  import type { SignatureHelpProvider } from '../../interfaces';
3
3
  import { Position, SignatureHelpContext, SignatureHelp, CancellationToken } from 'vscode-languageserver';
4
- import { Document } from '../../../core/documents';
4
+ import { AstroDocument } from '../../../core/documents';
5
5
  export declare class SignatureHelpProviderImpl implements SignatureHelpProvider {
6
- private readonly lang;
7
- constructor(lang: LanguageServiceManager);
6
+ private readonly languageServiceManager;
7
+ constructor(languageServiceManager: LanguageServiceManager);
8
8
  private static readonly triggerCharacters;
9
9
  private static readonly retriggerCharacters;
10
- getSignatureHelp(document: Document, position: Position, context: SignatureHelpContext | undefined, cancellationToken?: CancellationToken): Promise<SignatureHelp | null>;
10
+ getSignatureHelp(document: AstroDocument, position: Position, context: SignatureHelpContext | undefined, cancellationToken?: CancellationToken): Promise<SignatureHelp | null>;
11
11
  private isReTrigger;
12
12
  private isTriggerCharacter;
13
13
  /**
@@ -18,5 +18,4 @@ export declare class SignatureHelpProviderImpl implements SignatureHelpProvider
18
18
  * adopted from https://github.com/microsoft/vscode/blob/265a2f6424dfbd3a9788652c7d376a7991d049a3/extensions/typescript-language-features/src/languageFeatures/signatureHelp.ts#L73
19
19
  */
20
20
  private toSignatureHelpInformation;
21
- private isInSvelte2tsxGeneratedFunction;
22
21
  }
@@ -9,19 +9,20 @@ const vscode_languageserver_1 = require("vscode-languageserver");
9
9
  const previewer_1 = require("../previewer");
10
10
  const utils_1 = require("../utils");
11
11
  class SignatureHelpProviderImpl {
12
- constructor(lang) {
13
- this.lang = lang;
12
+ constructor(languageServiceManager) {
13
+ this.languageServiceManager = languageServiceManager;
14
14
  }
15
15
  async getSignatureHelp(document, position, context, cancellationToken) {
16
- const { lang, tsDoc } = await this.lang.getTypeScriptDoc(document);
17
- const fragment = await tsDoc.getFragment();
16
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
17
+ const fragment = await tsDoc.createFragment();
18
18
  if (cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.isCancellationRequested) {
19
19
  return null;
20
20
  }
21
+ const filePath = (0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath);
21
22
  const offset = fragment.offsetAt(fragment.getGeneratedPosition(position));
22
23
  const triggerReason = this.toTsTriggerReason(context);
23
- const info = lang.getSignatureHelpItems((0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath), offset, triggerReason ? { triggerReason } : undefined);
24
- if (!info || info.items.some((signature) => this.isInSvelte2tsxGeneratedFunction(signature))) {
24
+ const info = lang.getSignatureHelpItems(filePath, offset, triggerReason ? { triggerReason } : undefined);
25
+ if (!info) {
25
26
  return null;
26
27
  }
27
28
  const signatures = info.items.map(this.toSignatureHelpInformation);
@@ -32,7 +33,9 @@ class SignatureHelpProviderImpl {
32
33
  };
33
34
  }
34
35
  isReTrigger(isRetrigger, triggerCharacter) {
35
- return isRetrigger && (this.isTriggerCharacter(triggerCharacter) || SignatureHelpProviderImpl.retriggerCharacters.includes(triggerCharacter));
36
+ return (isRetrigger &&
37
+ (this.isTriggerCharacter(triggerCharacter) ||
38
+ SignatureHelpProviderImpl.retriggerCharacters.includes(triggerCharacter)));
36
39
  }
37
40
  isTriggerCharacter(triggerCharacter) {
38
41
  return SignatureHelpProviderImpl.triggerCharacters.includes(triggerCharacter);
@@ -66,7 +69,11 @@ class SignatureHelpProviderImpl {
66
69
  * adopted from https://github.com/microsoft/vscode/blob/265a2f6424dfbd3a9788652c7d376a7991d049a3/extensions/typescript-language-features/src/languageFeatures/signatureHelp.ts#L73
67
70
  */
68
71
  toSignatureHelpInformation(item) {
69
- const [prefixLabel, separatorLabel, suffixLabel] = [item.prefixDisplayParts, item.separatorDisplayParts, item.suffixDisplayParts].map(typescript_1.default.displayPartsToString);
72
+ const [prefixLabel, separatorLabel, suffixLabel] = [
73
+ item.prefixDisplayParts,
74
+ item.separatorDisplayParts,
75
+ item.suffixDisplayParts,
76
+ ].map(typescript_1.default.displayPartsToString);
70
77
  let textIndex = prefixLabel.length;
71
78
  let signatureLabel = '';
72
79
  const parameters = [];
@@ -95,9 +102,6 @@ class SignatureHelpProviderImpl {
95
102
  parameters,
96
103
  };
97
104
  }
98
- isInSvelte2tsxGeneratedFunction(signatureHelpItem) {
99
- return signatureHelpItem.prefixDisplayParts.some((part) => part.text.includes('__sveltets'));
100
- }
101
105
  }
102
106
  exports.SignatureHelpProviderImpl = SignatureHelpProviderImpl;
103
107
  SignatureHelpProviderImpl.triggerCharacters = ['(', ',', '<'];
@@ -1,16 +1,5 @@
1
- import type { SnapshotFragment, DocumentSnapshot } from '../DocumentSnapshot';
1
+ import type { SnapshotFragment, DocumentSnapshot } from '../snapshots/DocumentSnapshot';
2
2
  import type { LanguageServiceManager } from '../LanguageServiceManager';
3
- import type { TextSpan } from 'typescript';
4
- /**
5
- * Checks if this a section that should be completely ignored
6
- * because it's purely generated.
7
- */
8
- export declare function isInGeneratedCode(text: string, start: number, end: number): boolean;
9
- /**
10
- * Checks that this isn't a text span that should be completely ignored
11
- * because it's purely generated.
12
- */
13
- export declare function isNoTextSpanInGeneratedCode(text: string, span: TextSpan): boolean;
14
3
  export declare class SnapshotFragmentMap {
15
4
  private languageServiceManager;
16
5
  private map;
@@ -1,26 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SnapshotFragmentMap = exports.isNoTextSpanInGeneratedCode = exports.isInGeneratedCode = void 0;
4
- /**
5
- * Checks if this a section that should be completely ignored
6
- * because it's purely generated.
7
- */
8
- function isInGeneratedCode(text, start, end) {
9
- const lineStart = text.lastIndexOf('\n', start);
10
- const lineEnd = text.indexOf('\n', end);
11
- const lastStart = text.substring(lineStart, start).lastIndexOf('/*Ωignore_startΩ*/');
12
- const lastEnd = text.substring(lineStart, start).lastIndexOf('/*Ωignore_endΩ*/');
13
- return lastStart > lastEnd && text.substring(end, lineEnd).includes('/*Ωignore_endΩ*/');
14
- }
15
- exports.isInGeneratedCode = isInGeneratedCode;
16
- /**
17
- * Checks that this isn't a text span that should be completely ignored
18
- * because it's purely generated.
19
- */
20
- function isNoTextSpanInGeneratedCode(text, span) {
21
- return !isInGeneratedCode(text, span.start, span.start + span.length);
22
- }
23
- exports.isNoTextSpanInGeneratedCode = isNoTextSpanInGeneratedCode;
3
+ exports.SnapshotFragmentMap = void 0;
24
4
  class SnapshotFragmentMap {
25
5
  constructor(languageServiceManager) {
26
6
  this.languageServiceManager = languageServiceManager;
@@ -40,7 +20,7 @@ class SnapshotFragmentMap {
40
20
  let snapshotFragment = this.get(fileName);
41
21
  if (!snapshotFragment) {
42
22
  const snapshot = await this.languageServiceManager.getSnapshot(fileName);
43
- const fragment = await snapshot.getFragment();
23
+ const fragment = await snapshot.createFragment();
44
24
  snapshotFragment = { fragment, snapshot };
45
25
  this.set(fileName, snapshotFragment);
46
26
  }
@@ -0,0 +1,38 @@
1
+ import { AstroDocument } from '../../core/documents';
2
+ import ts from 'typescript';
3
+ import { TextDocumentContentChangeEvent } from 'vscode-languageserver';
4
+ import { GlobalSnapshotManager, SnapshotManager } from './snapshots/SnapshotManager';
5
+ import { DocumentSnapshot } from './snapshots/DocumentSnapshot';
6
+ export interface LanguageServiceContainer {
7
+ readonly tsconfigPath: string;
8
+ readonly compilerOptions: ts.CompilerOptions;
9
+ /**
10
+ * @internal Public for tests only
11
+ */
12
+ readonly snapshotManager: SnapshotManager;
13
+ getService(): ts.LanguageService;
14
+ updateSnapshot(documentOrFilePath: AstroDocument | string): DocumentSnapshot;
15
+ deleteSnapshot(filePath: string): void;
16
+ updateProjectFiles(): void;
17
+ updateNonAstroFile(fileName: string, changes?: TextDocumentContentChangeEvent[]): void;
18
+ /**
19
+ * Checks if a file is present in the project.
20
+ * Unlike `fileBelongsToProject`, this doesn't run a file search on disk.
21
+ */
22
+ hasFile(filePath: string): boolean;
23
+ /**
24
+ * Careful, don't call often, or it will hurt performance.
25
+ */
26
+ fileBelongsToProject(filePath: string): boolean;
27
+ }
28
+ export interface LanguageServiceDocumentContext {
29
+ createDocument: (fileName: string, content: string) => AstroDocument;
30
+ globalSnapshotManager: GlobalSnapshotManager;
31
+ }
32
+ export declare function getLanguageService(path: string, workspaceUris: string[], docContext: LanguageServiceDocumentContext): Promise<LanguageServiceContainer>;
33
+ export declare function forAllLanguageServices(cb: (service: LanguageServiceContainer) => any): Promise<void>;
34
+ /**
35
+ * @param tsconfigPath has to be absolute
36
+ * @param docContext
37
+ */
38
+ export declare function getLanguageServiceForTsconfig(tsconfigPath: string, docContext: LanguageServiceDocumentContext): Promise<LanguageServiceContainer>;
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.getLanguageServiceForTsconfig = exports.forAllLanguageServices = exports.getLanguageService = void 0;
30
+ const path_1 = require("path");
31
+ const typescript_1 = __importDefault(require("typescript"));
32
+ const utils_1 = require("../../utils");
33
+ const module_loader_1 = require("./module-loader");
34
+ const SnapshotManager_1 = require("./snapshots/SnapshotManager");
35
+ const utils_2 = require("./utils");
36
+ const DocumentSnapshotUtils = __importStar(require("./snapshots/utils"));
37
+ const services = new Map();
38
+ async function getLanguageService(path, workspaceUris, docContext) {
39
+ const tsconfigPath = (0, utils_2.findTsConfigPath)(path, workspaceUris);
40
+ return getLanguageServiceForTsconfig(tsconfigPath, docContext);
41
+ }
42
+ exports.getLanguageService = getLanguageService;
43
+ async function forAllLanguageServices(cb) {
44
+ for (const service of services.values()) {
45
+ cb(await service);
46
+ }
47
+ }
48
+ exports.forAllLanguageServices = forAllLanguageServices;
49
+ /**
50
+ * @param tsconfigPath has to be absolute
51
+ * @param docContext
52
+ */
53
+ async function getLanguageServiceForTsconfig(tsconfigPath, docContext) {
54
+ let service;
55
+ if (services.has(tsconfigPath)) {
56
+ service = await services.get(tsconfigPath);
57
+ }
58
+ else {
59
+ const newService = createLanguageService(tsconfigPath, docContext);
60
+ services.set(tsconfigPath, newService);
61
+ service = await newService;
62
+ }
63
+ return service;
64
+ }
65
+ exports.getLanguageServiceForTsconfig = getLanguageServiceForTsconfig;
66
+ async function createLanguageService(tsconfigPath, docContext) {
67
+ const workspaceRoot = tsconfigPath ? (0, path_1.dirname)(tsconfigPath) : process.cwd();
68
+ // `raw` here represent the tsconfig merged with any extended config
69
+ const { compilerOptions, fileNames: files, raw: fullConfig } = getParsedTSConfig();
70
+ let projectVersion = 0;
71
+ const snapshotManager = new SnapshotManager_1.SnapshotManager(docContext.globalSnapshotManager, files, fullConfig, workspaceRoot || process.cwd());
72
+ const astroModuleLoader = (0, module_loader_1.createAstroModuleLoader)(getScriptSnapshot, compilerOptions);
73
+ const host = {
74
+ getNewLine: () => typescript_1.default.sys.newLine,
75
+ useCaseSensitiveFileNames: () => typescript_1.default.sys.useCaseSensitiveFileNames,
76
+ getDirectories: typescript_1.default.sys.getDirectories,
77
+ resolveModuleNames: astroModuleLoader.resolveModuleNames,
78
+ readFile: astroModuleLoader.readFile,
79
+ fileExists: astroModuleLoader.fileExists,
80
+ readDirectory: astroModuleLoader.readDirectory,
81
+ getCompilationSettings: () => compilerOptions,
82
+ getCurrentDirectory: () => workspaceRoot,
83
+ getDefaultLibFileName: typescript_1.default.getDefaultLibFilePath,
84
+ getProjectVersion: () => projectVersion.toString(),
85
+ getScriptFileNames: () => Array.from(new Set([...snapshotManager.getProjectFileNames(), ...snapshotManager.getFileNames()])),
86
+ getScriptSnapshot,
87
+ getScriptVersion: (fileName) => getScriptSnapshot(fileName).version.toString(),
88
+ };
89
+ let languageService = typescript_1.default.createLanguageService(host);
90
+ docContext.globalSnapshotManager.onChange(() => {
91
+ projectVersion++;
92
+ });
93
+ return {
94
+ tsconfigPath,
95
+ compilerOptions,
96
+ getService: () => languageService,
97
+ updateSnapshot,
98
+ deleteSnapshot,
99
+ updateProjectFiles,
100
+ updateNonAstroFile,
101
+ hasFile,
102
+ fileBelongsToProject,
103
+ snapshotManager,
104
+ };
105
+ function deleteSnapshot(filePath) {
106
+ astroModuleLoader.deleteFromModuleCache(filePath);
107
+ snapshotManager.delete(filePath);
108
+ }
109
+ function updateSnapshot(documentOrFilePath) {
110
+ return typeof documentOrFilePath === 'string'
111
+ ? updateSnapshotFromFilePath(documentOrFilePath)
112
+ : updateSnapshotFromDocument(documentOrFilePath);
113
+ }
114
+ function updateSnapshotFromDocument(document) {
115
+ const filePath = document.getFilePath() || '';
116
+ const prevSnapshot = snapshotManager.get(filePath);
117
+ if ((prevSnapshot === null || prevSnapshot === void 0 ? void 0 : prevSnapshot.version) === document.version) {
118
+ return prevSnapshot;
119
+ }
120
+ if (!prevSnapshot) {
121
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(filePath);
122
+ }
123
+ const newSnapshot = DocumentSnapshotUtils.createFromDocument(document);
124
+ snapshotManager.set(filePath, newSnapshot);
125
+ if (prevSnapshot && prevSnapshot.scriptKind !== newSnapshot.scriptKind) {
126
+ // Restart language service as it doesn't handle script kind changes.
127
+ languageService.dispose();
128
+ languageService = typescript_1.default.createLanguageService(host);
129
+ }
130
+ return newSnapshot;
131
+ }
132
+ function updateSnapshotFromFilePath(filePath) {
133
+ const prevSnapshot = snapshotManager.get(filePath);
134
+ if (prevSnapshot) {
135
+ return prevSnapshot;
136
+ }
137
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(filePath);
138
+ const newSnapshot = DocumentSnapshotUtils.createFromFilePath(filePath, docContext.createDocument);
139
+ snapshotManager.set(filePath, newSnapshot);
140
+ return newSnapshot;
141
+ }
142
+ function getScriptSnapshot(fileName) {
143
+ fileName = (0, utils_2.ensureRealFilePath)(fileName);
144
+ let doc = snapshotManager.get(fileName);
145
+ if (doc) {
146
+ return doc;
147
+ }
148
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(fileName);
149
+ doc = DocumentSnapshotUtils.createFromFilePath(fileName, docContext.createDocument);
150
+ snapshotManager.set(fileName, doc);
151
+ return doc;
152
+ }
153
+ function updateProjectFiles() {
154
+ projectVersion++;
155
+ snapshotManager.updateProjectFiles();
156
+ }
157
+ function hasFile(filePath) {
158
+ return snapshotManager.has(filePath);
159
+ }
160
+ function fileBelongsToProject(filePath) {
161
+ filePath = (0, utils_1.normalizePath)(filePath);
162
+ return hasFile(filePath) || getParsedTSConfig().fileNames.includes(filePath);
163
+ }
164
+ function updateNonAstroFile(fileName, changes) {
165
+ if (!snapshotManager.has(fileName)) {
166
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(fileName);
167
+ }
168
+ snapshotManager.updateNonAstroFile(fileName, changes);
169
+ }
170
+ function getParsedTSConfig() {
171
+ var _a, _b, _c, _d;
172
+ let configJson = (tsconfigPath && typescript_1.default.readConfigFile(tsconfigPath, typescript_1.default.sys.readFile).config) || {};
173
+ // If our user has types in their config but it doesn't include the types needed for Astro, add them to the config
174
+ if (((_a = configJson.compilerOptions) === null || _a === void 0 ? void 0 : _a.types) && !((_b = configJson.compilerOptions) === null || _b === void 0 ? void 0 : _b.types.includes('astro/env'))) {
175
+ configJson.compilerOptions.types.push('astro/env');
176
+ }
177
+ configJson.compilerOptions = Object.assign(getDefaultCompilerOptions(), configJson.compilerOptions);
178
+ // If the user supplied exclude, let's use theirs
179
+ (_c = configJson.exclude) !== null && _c !== void 0 ? _c : (configJson.exclude = getDefaultExclude());
180
+ // Delete include so that .astro files don't get mistakenly excluded by the user
181
+ delete configJson.include;
182
+ // If the user supplied exclude, let's use theirs otherwise, use ours
183
+ (_d = configJson.exclude) !== null && _d !== void 0 ? _d : (configJson.exclude = getDefaultExclude());
184
+ // Everything here will always, unconditionally, be in the resulting config
185
+ const forcedCompilerOptions = {
186
+ // Our TSX is currently not typed, which unfortunately means that we can't support `noImplicitAny`
187
+ noImplicitAny: false,
188
+ // Most of the code people write in an .astro file is in the frontmatter which is executed server side
189
+ // Thus, we don't want the DOM lib. We'll need to overwrite this for script tags however
190
+ lib: ['ESNext'],
191
+ noEmit: true,
192
+ declaration: false,
193
+ allowNonTsExtensions: true,
194
+ allowJs: true,
195
+ jsx: typescript_1.default.JsxEmit.Preserve,
196
+ module: typescript_1.default.ModuleKind.ESNext,
197
+ target: typescript_1.default.ScriptTarget.ESNext,
198
+ moduleResolution: typescript_1.default.ModuleResolutionKind.NodeJs,
199
+ };
200
+ const project = typescript_1.default.parseJsonConfigFileContent(configJson, typescript_1.default.sys, workspaceRoot, forcedCompilerOptions, tsconfigPath, undefined, [
201
+ { extension: '.vue', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
202
+ { extension: '.svelte', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
203
+ { extension: '.astro', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
204
+ ]);
205
+ return {
206
+ ...project,
207
+ fileNames: project.fileNames.map(utils_1.normalizePath),
208
+ compilerOptions: {
209
+ ...project.options,
210
+ ...forcedCompilerOptions,
211
+ },
212
+ };
213
+ }
214
+ }
215
+ /**
216
+ * Default configuration used as a base and when the user doesn't have any
217
+ */
218
+ function getDefaultCompilerOptions() {
219
+ return {
220
+ maxNodeModuleJsDepth: 2,
221
+ allowSyntheticDefaultImports: true,
222
+ types: ['astro/env'],
223
+ };
224
+ }
225
+ function getDefaultExclude() {
226
+ return ['dist', 'node_modules'];
227
+ }
@@ -1,11 +1,11 @@
1
1
  import ts from 'typescript';
2
- import type { DocumentSnapshot } from './DocumentSnapshot';
2
+ import type { DocumentSnapshot } from './snapshots/DocumentSnapshot';
3
3
  /**
4
- * Creates a module loader specifically for `.astro` files.
4
+ * Creates a module loader specifically for `.astro` and other frameworks files.
5
5
  *
6
6
  * The typescript language service tries to look up other files that are referenced in the currently open astro file.
7
- * For `.ts`/`.js` files this works, for `.astro` files it does not by default.
8
- * Reason: The typescript language service does not know about the `.astro` file ending,
7
+ * For `.ts`/`.js` files this works, for `.astro` and frameworks files it does not by default.
8
+ * Reason: The typescript language service does not know about those file endings,
9
9
  * so it assumes it's a normal typescript file and searches for files like `../Component.astro.ts`, which is wrong.
10
10
  * In order to fix this, we need to wrap typescript's module resolution and reroute all `.astro.ts` file lookups to .astro.
11
11
  *
@@ -15,11 +15,8 @@ import type { DocumentSnapshot } from './DocumentSnapshot';
15
15
  export declare function createAstroModuleLoader(getSnapshot: (fileName: string) => DocumentSnapshot, compilerOptions: ts.CompilerOptions): {
16
16
  fileExists: (path: string) => boolean;
17
17
  readFile: (path: string, encoding?: string | undefined) => string | undefined;
18
- writeFile: (path: string, data: string, writeByteOrderMark?: boolean | undefined) => void;
19
18
  readDirectory: (path: string, extensions?: readonly string[] | undefined, exclude?: readonly string[] | undefined, include?: readonly string[] | undefined, depth?: number | undefined) => string[];
20
- directoryExists: (path: string) => boolean;
21
- getDirectories: (path: string) => string[];
22
- realpath: ((path: string) => string) | undefined;
23
19
  deleteFromModuleCache: (path: string) => void;
20
+ deleteUnresolvedResolutionsFromCache: (path: string) => void;
24
21
  resolveModuleNames: (moduleNames: string[], containingFile: string) => Array<ts.ResolvedModule | undefined>;
25
22
  };
@@ -7,6 +7,7 @@ exports.createAstroModuleLoader = void 0;
7
7
  const typescript_1 = __importDefault(require("typescript"));
8
8
  const utils_1 = require("./utils");
9
9
  const astro_sys_1 = require("./astro-sys");
10
+ const utils_2 = require("../../utils");
10
11
  /**
11
12
  * Caches resolved modules.
12
13
  */
@@ -21,12 +22,15 @@ class ModuleResolutionCache {
21
22
  return this.cache.get(this.getKey(moduleName, containingFile));
22
23
  }
23
24
  /**
24
- * Caches resolved module, if it is not undefined.
25
+ * Checks if has cached module.
26
+ */
27
+ has(moduleName, containingFile) {
28
+ return this.cache.has(this.getKey(moduleName, containingFile));
29
+ }
30
+ /**
31
+ * Caches resolved module (or undefined).
25
32
  */
26
33
  set(moduleName, containingFile, resolvedModule) {
27
- if (!resolvedModule) {
28
- return;
29
- }
30
34
  this.cache.set(this.getKey(moduleName, containingFile), resolvedModule);
31
35
  }
32
36
  /**
@@ -35,21 +39,34 @@ class ModuleResolutionCache {
35
39
  */
36
40
  delete(resolvedModuleName) {
37
41
  this.cache.forEach((val, key) => {
38
- if (val.resolvedFileName === resolvedModuleName) {
42
+ if ((val === null || val === void 0 ? void 0 : val.resolvedFileName) === resolvedModuleName) {
43
+ this.cache.delete(key);
44
+ }
45
+ });
46
+ }
47
+ /**
48
+ * Deletes everything from cache that resolved to `undefined`
49
+ * and which might match the path.
50
+ */
51
+ deleteUnresolvedResolutionsFromCache(path) {
52
+ const fileNameWithoutEnding = (0, utils_2.getLastPartOfPath)(path).split('.').shift() || '';
53
+ this.cache.forEach((val, key) => {
54
+ const moduleName = key.split(':::').pop() || '';
55
+ if (!val && moduleName.includes(fileNameWithoutEnding)) {
39
56
  this.cache.delete(key);
40
57
  }
41
58
  });
42
59
  }
43
60
  getKey(moduleName, containingFile) {
44
- return containingFile + ':::' + (0, utils_1.ensureRealAstroFilePath)(moduleName);
61
+ return containingFile + ':::' + (0, utils_1.ensureRealFilePath)(moduleName);
45
62
  }
46
63
  }
47
64
  /**
48
- * Creates a module loader specifically for `.astro` files.
65
+ * Creates a module loader specifically for `.astro` and other frameworks files.
49
66
  *
50
67
  * The typescript language service tries to look up other files that are referenced in the currently open astro file.
51
- * For `.ts`/`.js` files this works, for `.astro` files it does not by default.
52
- * Reason: The typescript language service does not know about the `.astro` file ending,
68
+ * For `.ts`/`.js` files this works, for `.astro` and frameworks files it does not by default.
69
+ * Reason: The typescript language service does not know about those file endings,
53
70
  * so it assumes it's a normal typescript file and searches for files like `../Component.astro.ts`, which is wrong.
54
71
  * In order to fix this, we need to wrap typescript's module resolution and reroute all `.astro.ts` file lookups to .astro.
55
72
  *
@@ -62,19 +79,21 @@ function createAstroModuleLoader(getSnapshot, compilerOptions) {
62
79
  return {
63
80
  fileExists: astroSys.fileExists,
64
81
  readFile: astroSys.readFile,
65
- writeFile: astroSys.writeFile,
66
82
  readDirectory: astroSys.readDirectory,
67
- directoryExists: astroSys.directoryExists,
68
- getDirectories: astroSys.getDirectories,
69
- realpath: astroSys.realpath,
70
- deleteFromModuleCache: (path) => moduleCache.delete(path),
83
+ deleteFromModuleCache: (path) => {
84
+ astroSys.deleteFromCache(path);
85
+ moduleCache.delete(path);
86
+ },
87
+ deleteUnresolvedResolutionsFromCache: (path) => {
88
+ astroSys.deleteFromCache(path);
89
+ moduleCache.deleteUnresolvedResolutionsFromCache(path);
90
+ },
71
91
  resolveModuleNames,
72
92
  };
73
93
  function resolveModuleNames(moduleNames, containingFile) {
74
94
  return moduleNames.map((moduleName) => {
75
- const cachedModule = moduleCache.get(moduleName, containingFile);
76
- if (cachedModule) {
77
- return cachedModule;
95
+ if (moduleCache.has(moduleName, containingFile)) {
96
+ return moduleCache.get(moduleName, containingFile);
78
97
  }
79
98
  const resolvedModule = resolveModuleName(moduleName, containingFile);
80
99
  moduleCache.set(moduleName, containingFile, resolvedModule);
@@ -84,22 +103,23 @@ function createAstroModuleLoader(getSnapshot, compilerOptions) {
84
103
  function resolveModuleName(name, containingFile) {
85
104
  // Delegate to the TS resolver first.
86
105
  // If that does not bring up anything, try the Astro Module loader
87
- // which is able to deal with .astro files.
106
+ // which is able to deal with .astro and other frameworks files.
88
107
  const tsResolvedModule = typescript_1.default.resolveModuleName(name, containingFile, compilerOptions, typescript_1.default.sys).resolvedModule;
89
- if (tsResolvedModule && !(0, utils_1.isVirtualAstroFilePath)(tsResolvedModule.resolvedFileName)) {
108
+ if (tsResolvedModule && !(0, utils_1.isVirtualFilePath)(tsResolvedModule.resolvedFileName)) {
90
109
  return tsResolvedModule;
91
110
  }
92
111
  const astroResolvedModule = typescript_1.default.resolveModuleName(name, containingFile, compilerOptions, astroSys).resolvedModule;
93
- if (!astroResolvedModule || !(0, utils_1.isVirtualAstroFilePath)(astroResolvedModule.resolvedFileName)) {
112
+ if (!astroResolvedModule || !(0, utils_1.isVirtualFilePath)(astroResolvedModule.resolvedFileName)) {
94
113
  return astroResolvedModule;
95
114
  }
96
- const resolvedFileName = (0, utils_1.ensureRealAstroFilePath)(astroResolvedModule.resolvedFileName);
115
+ const resolvedFileName = (0, utils_1.ensureRealFilePath)(astroResolvedModule.resolvedFileName);
97
116
  const snapshot = getSnapshot(resolvedFileName);
98
- const resolvedastroModule = {
117
+ const resolvedAstroModule = {
99
118
  extension: (0, utils_1.getExtensionFromScriptKind)(snapshot && snapshot.scriptKind),
100
119
  resolvedFileName,
120
+ isExternalLibraryImport: astroResolvedModule.isExternalLibraryImport,
101
121
  };
102
- return resolvedastroModule;
122
+ return resolvedAstroModule;
103
123
  }
104
124
  }
105
125
  exports.createAstroModuleLoader = createAstroModuleLoader;