@astrojs/language-server 0.9.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +10 -9
  34. package/dist/plugins/PluginHost.js +30 -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 +22 -12
  42. package/dist/plugins/css/CSSPlugin.js +112 -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 +222 -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 +91 -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
@@ -5,66 +5,43 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DiagnosticsProviderImpl = void 0;
7
7
  const typescript_1 = __importDefault(require("typescript"));
8
- const vscode_languageserver_1 = require("vscode-languageserver");
8
+ const vscode_languageserver_types_1 = require("vscode-languageserver-types");
9
9
  const documents_1 = require("../../../core/documents");
10
10
  const utils_1 = require("../utils");
11
- const utils_2 = require("./utils");
12
11
  class DiagnosticsProviderImpl {
13
12
  constructor(languageServiceManager) {
14
13
  this.languageServiceManager = languageServiceManager;
15
14
  }
16
15
  async getDiagnostics(document, _cancellationToken) {
17
- var _a, _b, _c, _d, _e;
18
- if ((((_a = document.getFilePath()) === null || _a === void 0 ? void 0 : _a.includes('/node_modules/')) ||
19
- ((_b = document.getFilePath()) === null || _b === void 0 ? void 0 : _b.includes('\\node_modules\\'))) &&
20
- // Sapper convention: Put stuff inside node_modules below src
21
- !(((_c = document.getFilePath()) === null || _c === void 0 ? void 0 : _c.includes('/src/node_modules/')) ||
22
- ((_d = document.getFilePath()) === null || _d === void 0 ? void 0 : _d.includes('\\src\\node_modules\\')))) {
23
- // Don't return diagnostics for files inside node_modules. These are considered read-only (cannot be changed)
24
- // and in case of svelte-check they would pollute/skew the output
16
+ var _a, _b, _c;
17
+ // Don't return diagnostics for files inside node_modules. These are considered read-only
18
+ // and they would pollute the output for astro check
19
+ if (((_a = document.getFilePath()) === null || _a === void 0 ? void 0 : _a.includes('/node_modules/')) || ((_b = document.getFilePath()) === null || _b === void 0 ? void 0 : _b.includes('\\node_modules\\'))) {
25
20
  return [];
26
21
  }
27
- const { lang, tsDoc } = await this.getLSAndTSDoc(document);
28
- const isTypescript = tsDoc.scriptKind === typescript_1.default.ScriptKind.TSX;
29
- // Document preprocessing failed, show parser error instead
30
- if (tsDoc.parserError) {
31
- return [
32
- {
33
- range: tsDoc.parserError.range,
34
- severity: vscode_languageserver_1.DiagnosticSeverity.Error,
35
- source: isTypescript ? 'ts' : 'js',
36
- message: tsDoc.parserError.message,
37
- code: tsDoc.parserError.code
38
- }
39
- ];
40
- }
22
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
41
23
  const filePath = (0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath);
42
24
  const { script: scriptBoundaries, markdown: markdownBoundaries } = this.getTagBoundaries(lang, filePath);
43
25
  const syntaxDiagnostics = lang.getSyntacticDiagnostics(filePath);
44
26
  const suggestionDiagnostics = lang.getSuggestionDiagnostics(filePath);
45
- const semanticDiagnostics = lang.getSemanticDiagnostics(filePath).filter(d => {
46
- return (isNoWithinScript(scriptBoundaries, d));
27
+ const semanticDiagnostics = lang.getSemanticDiagnostics(filePath).filter((d) => {
28
+ return isNoWithinScript(scriptBoundaries, d);
47
29
  });
48
- const diagnostics = [
49
- ...syntaxDiagnostics,
50
- ...suggestionDiagnostics,
51
- ...semanticDiagnostics
52
- ];
53
- const fragment = await tsDoc.getFragment();
54
- const sourceFile = (_e = lang.getProgram()) === null || _e === void 0 ? void 0 : _e.getSourceFile(filePath);
30
+ const diagnostics = [...syntaxDiagnostics, ...suggestionDiagnostics, ...semanticDiagnostics];
31
+ const fragment = await tsDoc.createFragment();
32
+ const sourceFile = (_c = lang.getProgram()) === null || _c === void 0 ? void 0 : _c.getSourceFile(filePath);
55
33
  const isNoFalsePositiveInst = isNoFalsePositive();
56
34
  return diagnostics
57
- .filter(isNotGenerated(tsDoc.getText(0, tsDoc.getLength())))
58
35
  .map((diagnostic) => ({
59
36
  range: (0, utils_1.convertRange)(tsDoc, diagnostic),
60
37
  severity: (0, utils_1.mapSeverity)(diagnostic.category),
61
- source: isTypescript ? 'ts' : 'js',
38
+ source: 'ts',
62
39
  message: typescript_1.default.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
63
40
  code: diagnostic.code,
64
- tags: getDiagnosticTag(diagnostic)
41
+ tags: getDiagnosticTag(diagnostic),
65
42
  }))
66
43
  .map(mapRange(fragment, document))
67
- .filter(diag => {
44
+ .filter((diag) => {
68
45
  return (hasNoNegativeLines(diag) &&
69
46
  isNoFalsePositiveInst(diag) &&
70
47
  isNoJSXImplicitRuntimeWarning(diag) &&
@@ -77,21 +54,18 @@ class DiagnosticsProviderImpl {
77
54
  })
78
55
  .map(enhanceIfNecessary);
79
56
  }
80
- async getLSAndTSDoc(document) {
81
- return this.languageServiceManager.getTypeScriptDoc(document);
82
- }
83
57
  getTagBoundaries(lang, tsFilePath) {
84
58
  const program = lang.getProgram();
85
59
  const sourceFile = program === null || program === void 0 ? void 0 : program.getSourceFile(tsFilePath);
86
60
  const boundaries = {
87
61
  script: [],
88
- markdown: []
62
+ markdown: [],
89
63
  };
90
64
  if (!sourceFile) {
91
65
  return boundaries;
92
66
  }
93
67
  function findScript(parent) {
94
- typescript_1.default.forEachChild(parent, node => {
68
+ typescript_1.default.forEachChild(parent, (node) => {
95
69
  if (typescript_1.default.isJsxElement(node)) {
96
70
  let tagName = node.openingElement.tagName.getText();
97
71
  switch (tagName) {
@@ -117,10 +91,10 @@ exports.DiagnosticsProviderImpl = DiagnosticsProviderImpl;
117
91
  function getDiagnosticTag(diagnostic) {
118
92
  const tags = [];
119
93
  if (diagnostic.reportsUnnecessary) {
120
- tags.push(vscode_languageserver_1.DiagnosticTag.Unnecessary);
94
+ tags.push(vscode_languageserver_types_1.DiagnosticTag.Unnecessary);
121
95
  }
122
96
  if (diagnostic.reportsDeprecated) {
123
- tags.push(vscode_languageserver_1.DiagnosticTag.Deprecated);
97
+ tags.push(vscode_languageserver_types_1.DiagnosticTag.Deprecated);
124
98
  }
125
99
  return tags;
126
100
  }
@@ -144,7 +118,7 @@ function hasNoNegativeLines(diagnostic) {
144
118
  }
145
119
  function isNoFalsePositive() {
146
120
  return (diagnostic) => {
147
- return (isNoJsxCannotHaveMultipleAttrsError(diagnostic));
121
+ return isNoJsxCannotHaveMultipleAttrsError(diagnostic);
148
122
  };
149
123
  }
150
124
  /**
@@ -226,7 +200,7 @@ function enhanceIfNecessary(diagnostic) {
226
200
  ' import type { SvelteComponentTyped } from "svelte";\n' +
227
201
  ' class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}\n\n' +
228
202
  'Underlying error:\n' +
229
- diagnostic.message
203
+ diagnostic.message,
230
204
  };
231
205
  }
232
206
  if (diagnostic.code === 2607) {
@@ -235,27 +209,14 @@ function enhanceIfNecessary(diagnostic) {
235
209
  message: 'Element does not support attributes because ' +
236
210
  'type definitions are missing for this Svelte Component or element cannot be used as such.\n\n' +
237
211
  'Underlying error:\n' +
238
- diagnostic.message
212
+ diagnostic.message,
239
213
  };
240
214
  }
241
215
  if (diagnostic.code === 1184) {
242
216
  return {
243
217
  ...diagnostic,
244
- message: diagnostic.message +
245
- '\nIf this is a declare statement, move it into <script context="module">..</script>'
218
+ message: diagnostic.message + '\nIf this is a declare statement, move it into <script context="module">..</script>',
246
219
  };
247
220
  }
248
221
  return diagnostic;
249
222
  }
250
- /**
251
- * Checks if diagnostic is not within a section that should be completely ignored
252
- * because it's purely generated.
253
- */
254
- function isNotGenerated(text) {
255
- return (diagnostic) => {
256
- if (diagnostic.start === undefined || diagnostic.length === undefined) {
257
- return true;
258
- }
259
- return !(0, utils_2.isInGeneratedCode)(text, diagnostic.start, diagnostic.start + diagnostic.length);
260
- };
261
- }
@@ -1,10 +1,9 @@
1
1
  import type { LanguageServiceManager } from '../LanguageServiceManager';
2
2
  import { Hover, Position } from 'vscode-languageserver';
3
- import { Document } from '../../../core/documents';
3
+ import { AstroDocument } from '../../../core/documents';
4
4
  import { HoverProvider } from '../../interfaces';
5
5
  export declare class HoverProviderImpl implements HoverProvider {
6
- private readonly lang;
7
- constructor(lang: LanguageServiceManager);
8
- doHover(document: Document, position: Position): Promise<Hover | null>;
9
- private getLSAndTSDoc;
6
+ private readonly languageServiceManager;
7
+ constructor(languageServiceManager: LanguageServiceManager);
8
+ doHover(document: AstroDocument, position: Position): Promise<Hover | null>;
10
9
  }
@@ -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,222 @@
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;
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
+ // Delete include so that .astro files don't get mistakenly excluded by the user
179
+ delete configJson.include;
180
+ // If the user supplied exclude, let's use theirs otherwise, use ours
181
+ (_c = configJson.exclude) !== null && _c !== void 0 ? _c : (configJson.exclude = getDefaultExclude());
182
+ // Everything here will always, unconditionally, be in the resulting config
183
+ const forcedCompilerOptions = {
184
+ // Our TSX is currently not typed, which unfortunately means that we can't support `noImplicitAny`
185
+ noImplicitAny: false,
186
+ noEmit: true,
187
+ declaration: false,
188
+ allowNonTsExtensions: true,
189
+ allowJs: true,
190
+ jsx: typescript_1.default.JsxEmit.Preserve,
191
+ module: typescript_1.default.ModuleKind.ESNext,
192
+ target: typescript_1.default.ScriptTarget.ESNext,
193
+ moduleResolution: typescript_1.default.ModuleResolutionKind.NodeJs,
194
+ };
195
+ const project = typescript_1.default.parseJsonConfigFileContent(configJson, typescript_1.default.sys, workspaceRoot, forcedCompilerOptions, tsconfigPath, undefined, [
196
+ { extension: '.vue', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
197
+ { extension: '.svelte', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
198
+ { extension: '.astro', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
199
+ ]);
200
+ return {
201
+ ...project,
202
+ fileNames: project.fileNames.map(utils_1.normalizePath),
203
+ compilerOptions: {
204
+ ...project.options,
205
+ ...forcedCompilerOptions,
206
+ },
207
+ };
208
+ }
209
+ }
210
+ /**
211
+ * Default configuration used as a base and when the user doesn't have any
212
+ */
213
+ function getDefaultCompilerOptions() {
214
+ return {
215
+ maxNodeModuleJsDepth: 2,
216
+ allowSyntheticDefaultImports: true,
217
+ types: ['astro/env'],
218
+ };
219
+ }
220
+ function getDefaultExclude() {
221
+ return ['dist', 'node_modules'];
222
+ }
@@ -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
  };