Clean up dependencies
All checks were successful
Build and Push / build (push) Successful in 18s

This commit is contained in:
2026-02-16 15:12:59 -05:00
parent d181f77fb2
commit 2f15523a55
14941 changed files with 0 additions and 2078483 deletions

View File

@@ -1,2 +0,0 @@
import type { LanguageServicePlugin } from '@volar/language-server';
export declare const create: (ts: typeof import("typescript")) => LanguageServicePlugin;

View File

@@ -1,155 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const node_path_1 = require("node:path");
const language_server_1 = require("@volar/language-server");
const fast_glob_1 = __importDefault(require("fast-glob"));
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../core/index.js");
const utils_js_1 = require("./utils.js");
const create = (ts) => {
return {
capabilities: {
completionProvider: {
triggerCharacters: ['-'],
},
diagnosticProvider: {
interFileDependencies: false,
workspaceDiagnostics: false,
},
codeLensProvider: {},
},
create(context) {
return {
provideCompletionItems(document, position, completionContext, token) {
if (token.isCancellationRequested)
return null;
let items = [];
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const virtualCode = decoded && sourceScript?.generated?.embeddedCodes.get(decoded[1]);
if (!(virtualCode instanceof index_js_1.AstroVirtualCode))
return;
if (completionContext.triggerCharacter === '-') {
const frontmatterCompletion = getFrontmatterCompletion(virtualCode, document, position);
if (frontmatterCompletion)
items.push(frontmatterCompletion);
}
return {
isIncomplete: false,
items: items,
};
},
provideDiagnostics(document, token) {
if (token.isCancellationRequested)
return [];
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const virtualCode = decoded && sourceScript?.generated?.embeddedCodes.get(decoded[1]);
if (!(virtualCode instanceof index_js_1.AstroVirtualCode))
return;
return virtualCode.compilerDiagnostics.map(compilerMessageToDiagnostic);
function compilerMessageToDiagnostic(message) {
const start = language_server_1.Position.create(message.location.line - 1, message.location.column - 1);
const end = document.positionAt(document.offsetAt(start) + message.location.length);
return {
message: message.text + (message.hint ? '\n\n' + message.hint : ''),
range: language_server_1.Range.create(start, end),
code: message.code,
severity: message.severity,
source: 'astro',
};
}
},
provideCodeLenses(document, token) {
if (token.isCancellationRequested)
return;
if (!(0, utils_js_1.isJSDocument)(document.languageId))
return;
if (!context.project.typescript)
return;
const { uriConverter } = context.project.typescript;
const languageService = context.inject('typescript/languageService');
if (!languageService)
return;
const tsProgram = languageService.getProgram();
if (!tsProgram)
return;
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
if (!decoded)
return;
const globcodeLens = [];
const sourceFile = tsProgram.getSourceFile(decoded[0].fsPath);
function walk() {
return ts.forEachChild(sourceFile, function cb(node) {
if (ts.isCallExpression(node) && node.expression.getText() === 'Astro.glob') {
const globArgument = node.arguments.at(0);
if (globArgument && decoded) {
globcodeLens.push(getGlobResultAsCodeLens(globArgument.getText().slice(1, -1), (0, node_path_1.dirname)(uriConverter.asFileName(decoded[0])), document.positionAt(node.arguments.pos)));
}
}
return ts.forEachChild(node, cb);
});
}
walk();
return globcodeLens;
},
};
},
};
};
exports.create = create;
function getGlobResultAsCodeLens(globText, dir, position) {
const globResult = fast_glob_1.default.sync(globText, {
cwd: dir,
onlyFiles: true,
});
return {
range: language_server_1.Range.create(position, position),
command: { title: `Matches ${globResult.length} files`, command: '' },
};
}
function getFrontmatterCompletion(file, document, position) {
const base = {
kind: language_server_1.CompletionItemKind.Snippet,
label: '---',
sortText: '\0',
preselect: true,
detail: 'Create component script block',
insertTextFormat: language_server_1.InsertTextFormat.Snippet,
commitCharacters: [],
};
const documentLines = document.getText().split(/\r?\n/);
const { line, character } = document.positionAt(document.offsetAt(position));
const prefix = documentLines[line].slice(0, character);
if (file.astroMeta.frontmatter.status === 'doesnt-exist') {
return {
...base,
insertText: '---\n$0\n---',
textEdit: /^\s*-+/.test(prefix)
? language_server_1.TextEdit.replace({ start: { ...position, character: 0 }, end: position }, '---\n$0\n---')
: undefined,
};
}
if (file.astroMeta.frontmatter.status === 'open') {
let insertText = '---';
// If the current line is a full component script starter/ender, the user expects a full frontmatter
// completion and not just a completion for "---" on the same line (which result in, well, nothing)
if (prefix === '---') {
insertText = '---\n$0\n---';
}
return {
...base,
insertText,
detail: insertText === '---' ? 'Close component script block' : 'Create component script block',
textEdit: /^\s*-+/.test(prefix)
? language_server_1.TextEdit.replace({ start: { ...position, character: 0 }, end: position }, insertText)
: undefined,
};
}
return null;
}
//# sourceMappingURL=astro.js.map

View File

@@ -1,4 +0,0 @@
export declare const classListAttribute: import("vscode-html-languageservice").IHTMLDataProvider;
export declare const astroElements: import("vscode-html-languageservice").IHTMLDataProvider;
export declare const astroAttributes: import("vscode-html-languageservice").IHTMLDataProvider;
export declare const astroDirectives: import("vscode-html-languageservice").IHTMLDataProvider;

View File

@@ -1,277 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.astroDirectives = exports.astroAttributes = exports.astroElements = exports.classListAttribute = void 0;
const vscode_html_languageservice_1 = require("vscode-html-languageservice");
const defaultProvider = (0, vscode_html_languageservice_1.getDefaultHTMLDataProvider)();
const slotAttr = defaultProvider.provideAttributes('div').find((attr) => attr.name === 'slot');
exports.classListAttribute = (0, vscode_html_languageservice_1.newHTMLDataProvider)('class-list', {
version: 1,
globalAttributes: [
{
name: 'class:list',
description: 'Utility to provide a list of classes of the element. Takes an array of class values and converts them into a class string.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#classlist',
},
],
},
],
});
exports.astroElements = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-elements', {
version: 1,
tags: [
{
name: 'slot',
description: 'The slot element is a placeholder for external HTML content, allowing you to inject (or “slot”) child elements from other files into your component template.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#slots',
},
],
attributes: [
{
name: 'name',
description: 'The name attribute allows you to pass only HTML elements with the corresponding slot name into a slots location.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#named-slots',
},
],
},
],
},
{
name: 'script',
attributes: [
{
// The VS Code tag definitions does not provide a description for the deprecated `charset` attribute on script tags
// Which mean that since we get no hover info for this, we instead get JSX hover info. So we'll just specify a description ourselves for this specific case
name: 'charset',
description: "**Deprecated**\n\nIt's unnecessary to specify the charset attribute, because documents must use UTF-8, and the script element inherits its character encoding from the document.",
},
{
name: 'define:vars',
description: 'Passes serializable server-side variables into a client-side script element.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#definevars',
},
],
},
{
name: 'hoist',
description: '**Deprecated in Astro >= 0.26.0**\n\nBuilds, optimizes, and bundles your script with the other JavaScript on the page.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#using-hoisted-scripts',
},
],
},
{
name: 'is:inline',
description: 'Leave a script tag inline in the page template. No processing will be done on its content.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isinline',
},
],
},
{
name: 'data-astro-rerun',
description: 'Force a script to be reexecuted when using <ViewTransitions/>. This will make your script is:inline as well.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#script-behavior',
},
],
},
],
},
{
name: 'style',
attributes: [
{
name: 'define:vars',
description: 'Passes serializable server-side variables into a client-side style element.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#definevars',
},
],
},
{
name: 'global',
description: '**Deprecated in favor of `is:global` in >= Astro 0.26.0**\n\nOpts-out of automatic CSS scoping, all contents will be available globally.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isglobal',
},
],
},
{
name: 'is:global',
description: 'Opts-out of automatic CSS scoping, all contents will be available globally.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isglobal',
},
],
},
{
name: 'is:inline',
description: 'Leave a style tag inline in the page template. No processing will be done on its content.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isinline',
},
],
},
],
},
],
});
exports.astroAttributes = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-attributes', {
version: 1,
globalAttributes: [
{
name: 'set:html',
description: 'Inject unescaped HTML into this tag.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#sethtml',
},
],
},
{
name: 'set:text',
description: 'Inject escaped text into this tag.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#settext',
},
],
},
{
name: 'is:raw',
description: 'Instructs the Astro compiler to treat any children of this element as text.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#israw',
},
],
},
{
name: 'transition:animate',
description: 'Specifies an animation to use with this element on page transition.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
{
name: 'transition:name',
description: 'Specifies a `view-transition-name` for this element. The name must be unique on the page.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
{
name: 'transition:persist',
description: 'Marks this element to be moved to the next page during view transitions.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
slotAttr,
],
});
exports.astroDirectives = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-directives', {
version: 1,
globalAttributes: [
{
name: 'client:load',
description: 'Start importing the component JS at page load. Hydrate the component when import completes.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientload',
},
],
},
{
name: 'client:idle',
description: 'Start importing the component JS as soon as main thread is free (uses requestIdleCallback()). Hydrate the component when import completes.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientidle',
},
],
},
{
name: 'client:visible',
description: 'Start importing the component JS as soon as the element enters the viewport (uses IntersectionObserver). Hydrate the component when import completes. Useful for content lower down on the page.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientvisible',
},
],
},
{
name: 'client:media',
description: 'Start importing the component JS as soon as the browser matches the given media query (uses matchMedia). Hydrate the component when import completes. Useful for sidebar toggles, or other elements that should only display on mobile or desktop devices.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientmedia',
},
],
},
{
name: 'client:only',
description: 'Start importing the component JS at page load and hydrate when the import completes, similar to client:load. The component will be skipped at build time, useful for components that are entirely dependent on client-side APIs. This is best avoided unless absolutely needed, in most cases it is best to render placeholder content on the server and delay any browser API calls until the component hydrates in the browser.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientonly',
},
],
},
],
});
//# sourceMappingURL=html-data.js.map

View File

@@ -1,2 +0,0 @@
import type { LanguageServicePlugin } from '@volar/language-server';
export declare const create: () => LanguageServicePlugin;

View File

@@ -1,93 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const language_server_1 = require("@volar/language-server");
const volar_service_html_1 = require("volar-service-html");
const html = __importStar(require("vscode-html-languageservice"));
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../core/index.js");
const html_data_js_1 = require("./html-data.js");
const utils_js_1 = require("./utils.js");
const create = () => {
const htmlPlugin = (0, volar_service_html_1.create)({
getCustomData: async (context) => {
const customData = (await context.env.getConfiguration?.('html.customData')) ?? [];
const newData = [];
for (const customDataPath of customData) {
for (const workspaceFolder of context.env.workspaceFolders) {
const uri = vscode_uri_1.Utils.resolvePath(workspaceFolder, customDataPath);
const json = await context.env.fs?.readFile?.(uri);
if (json) {
try {
const data = JSON.parse(json);
newData.push(html.newHTMLDataProvider(customDataPath, data));
}
catch (error) {
console.error(error);
}
break;
}
}
}
return [...newData, html_data_js_1.astroAttributes, html_data_js_1.astroElements, html_data_js_1.classListAttribute];
},
});
return {
...htmlPlugin,
create(context) {
const htmlPluginInstance = htmlPlugin.create(context);
return {
...htmlPluginInstance,
async provideCompletionItems(document, position, completionContext, token) {
if (document.languageId !== 'html')
return;
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const root = sourceScript?.generated?.root;
if (!(root instanceof index_js_1.AstroVirtualCode))
return;
// Don't return completions if the current node is a component
if ((0, utils_js_1.isInComponentStartTag)(root.htmlDocument, document.offsetAt(position))) {
return null;
}
const completions = await htmlPluginInstance.provideCompletionItems(document, position, completionContext, token);
if (!completions) {
return null;
}
// We don't want completions for file references, as they're mostly invalid for Astro
completions.items = completions.items.filter((completion) => completion.kind !== language_server_1.CompletionItemKind.File);
return completions;
},
// Document links provided by `vscode-html-languageservice` are invalid for Astro
provideDocumentLinks() {
return [];
},
};
},
};
};
exports.create = create;
//# sourceMappingURL=html.js.map

View File

@@ -1,2 +0,0 @@
import type { LanguageServicePlugin } from '@volar/language-server';
export declare const create: () => LanguageServicePlugin;

View File

@@ -1,52 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../../core/index.js");
const utils_js_1 = require("../utils.js");
const snippets_js_1 = require("./snippets.js");
const create = () => {
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
},
create(context) {
return {
isAdditionalCompletion: true,
// Q: Why the empty transform and resolve functions?
// A: Volar will skip mapping the completion items if those functions are defined, as such we can return the snippets
// completions as-is, this is notably useful for snippets that insert to the frontmatter, since we don't need to map anything.
transformCompletionItem(item) {
return item;
},
provideCompletionItems(document, position, completionContext, token) {
if (!context ||
!utils_js_1.isJSDocument ||
token.isCancellationRequested ||
completionContext.triggerKind === 2)
return null;
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const root = sourceScript?.generated?.root;
if (!(root instanceof index_js_1.AstroVirtualCode))
return undefined;
if (!(0, utils_js_1.isInsideFrontmatter)(document.offsetAt(position), root.astroMeta.frontmatter))
return null;
const completionList = {
items: [],
isIncomplete: false,
};
completionList.items.push(...(0, snippets_js_1.getSnippetCompletions)(root.astroMeta.frontmatter));
return completionList;
},
resolveCompletionItem(item) {
return item;
},
};
},
};
};
exports.create = create;
//# sourceMappingURL=index.js.map

View File

@@ -1,3 +0,0 @@
import { type CompletionItem } from '@volar/language-server';
import type { FrontmatterStatus } from '../../core/parseAstro.js';
export declare function getSnippetCompletions(frontmatter: FrontmatterStatus): CompletionItem[];

View File

@@ -1,65 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSnippetCompletions = getSnippetCompletions;
const language_server_1 = require("@volar/language-server");
function getSnippetCompletions(frontmatter) {
if (frontmatter.status === 'doesnt-exist')
return [];
const frontmatterStartPosition = {
line: frontmatter.position.start.line,
character: frontmatter.position.start.column - 1,
};
return [
{
label: 'interface Props',
kind: language_server_1.CompletionItemKind.Snippet,
labelDetails: { description: 'Create a new interface to type your props' },
documentation: {
kind: 'markdown',
value: [
'Create a new interface to type your props.',
'\n',
'[Astro reference](https://docs.astro.build/en/guides/typescript/#component-props)',
].join('\n'),
},
insertTextFormat: 2,
filterText: 'interface props',
insertText: 'interface Props {\n\t$1\n}',
},
{
label: 'getStaticPaths',
kind: language_server_1.CompletionItemKind.Snippet,
labelDetails: { description: 'Create a new getStaticPaths function' },
documentation: {
kind: 'markdown',
value: [
'Create a new getStaticPaths function.',
'\n',
'[Astro reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)',
].join('\n'),
},
insertText: 'export const getStaticPaths = (() => {\n\t$1\n\treturn [];\n}) satisfies GetStaticPaths;',
additionalTextEdits: [
language_server_1.TextEdit.insert(frontmatterStartPosition, 'import type { GetStaticPaths } from "astro";\n'),
],
filterText: 'getstaticpaths',
insertTextFormat: 2,
},
{
label: 'prerender',
kind: language_server_1.CompletionItemKind.Snippet,
labelDetails: { description: 'Add prerender export' },
documentation: {
kind: 'markdown',
value: [
'Add prerender export. When [using server-side rendering](https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project), this value will be used to determine whether to prerender the page or not.',
'\n',
'[Astro reference](https://docs.astro.build/en/guides/server-side-rendering/#configuring-individual-routes)',
].join('\n'),
},
insertText: 'export const prerender = ${1|true,false,import.meta.env.|}',
insertTextFormat: 2,
},
];
}
//# sourceMappingURL=snippets.js.map

View File

@@ -1,3 +0,0 @@
import type { CodeAction, LanguageServiceContext } from '@volar/language-service';
export declare function enhancedProvideCodeActions(codeActions: CodeAction[], context: LanguageServiceContext): CodeAction[];
export declare function enhancedResolveCodeAction(codeAction: CodeAction, context: LanguageServiceContext): CodeAction;

View File

@@ -1,37 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enhancedProvideCodeActions = enhancedProvideCodeActions;
exports.enhancedResolveCodeAction = enhancedResolveCodeAction;
const language_server_1 = require("@volar/language-server");
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../../core/index.js");
const utils_js_1 = require("./utils.js");
function enhancedProvideCodeActions(codeActions, context) {
return codeActions.map((codeAction) => mapCodeAction(codeAction, context));
}
function enhancedResolveCodeAction(codeAction, context) {
/**
* TypeScript code actions don't come through here, as they're considered to be already fully resolved
* A lot of the code actions we'll encounter here are more tricky ones, such as fixAll or refactor
* For now, it seems like we don't need to do anything special here, but we'll keep this function around
*/
return mapCodeAction(codeAction, context);
}
function mapCodeAction(codeAction, context) {
if (!codeAction.edit || !codeAction.edit.documentChanges)
return codeAction;
codeAction.edit.documentChanges = codeAction.edit.documentChanges.map((change) => {
if (language_server_1.TextDocumentEdit.is(change)) {
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(change.textDocument.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const virtualCode = decoded && sourceScript?.generated?.embeddedCodes.get(decoded[1]);
const root = sourceScript?.generated?.root;
if (!virtualCode || !(root instanceof index_js_1.AstroVirtualCode))
return change;
change.edits = change.edits.map((edit) => (0, utils_js_1.mapEdit)(edit, root, virtualCode.languageId));
}
return change;
});
return codeAction;
}
//# sourceMappingURL=codeActions.js.map

View File

@@ -1,3 +0,0 @@
import type { CompletionItem, CompletionList, LanguageServiceContext } from '@volar/language-server';
export declare function enhancedProvideCompletionItems(completions: CompletionList): CompletionList;
export declare function enhancedResolveCompletionItem(resolvedCompletion: CompletionItem, context: LanguageServiceContext): CompletionItem;

View File

@@ -1,76 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enhancedProvideCompletionItems = enhancedProvideCompletionItems;
exports.enhancedResolveCompletionItem = enhancedResolveCompletionItem;
const language_server_1 = require("@volar/language-server");
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../../core/index.js");
const utils_js_1 = require("./utils.js");
function enhancedProvideCompletionItems(completions) {
completions.items = completions.items.filter(isValidCompletion).map((completion) => {
const source = completion?.data?.originalItem?.source;
if (source) {
// Sort completions starting with `astro:` higher than other imports
if (source.startsWith('astro:')) {
completion.sortText = '\u0000' + (completion.sortText ?? completion.label);
}
// For components import, use the file kind and sort them first, as they're often what the user want over something else
if (['.astro', '.svelte', '.vue'].some((ext) => source.endsWith(ext))) {
completion.kind = language_server_1.CompletionItemKind.File;
completion.detail = completion.detail + '\n\n' + source;
completion.sortText = '\u0001' + (completion.sortText ?? completion.label);
completion.data.isComponent = true;
}
}
return completion;
});
return completions;
}
function enhancedResolveCompletionItem(resolvedCompletion, context) {
// Make sure we keep our icons even when the completion is resolved
if (resolvedCompletion.data.isComponent) {
resolvedCompletion.detail = getDetailForFileCompletion(resolvedCompletion.detail ?? '', resolvedCompletion.data.originalItem.source);
}
if (resolvedCompletion.additionalTextEdits) {
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(resolvedCompletion.data.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const virtualCode = decoded && sourceScript?.generated?.embeddedCodes.get(decoded[1]);
const root = sourceScript?.generated?.root;
if (!virtualCode || !(root instanceof index_js_1.AstroVirtualCode))
return resolvedCompletion;
resolvedCompletion.additionalTextEdits = resolvedCompletion.additionalTextEdits.map((edit) => (0, utils_js_1.mapEdit)(edit, root, virtualCode.languageId));
}
return resolvedCompletion;
}
function getDetailForFileCompletion(detail, source) {
return `${detail}\n\n${source}`;
}
// When Svelte components are imported, we have to reference the svelte2tsx's types to properly type the component
// An unfortunate downside of this is that it pollutes completions, so let's filter those internal types manually
const svelte2tsxTypes = new Set([
'Svelte2TsxComponent',
'Svelte2TsxComponentConstructorParameters',
'SvelteComponentConstructor',
'SvelteActionReturnType',
'SvelteTransitionConfig',
'SvelteTransitionReturnType',
'SvelteAnimationReturnType',
'SvelteWithOptionalProps',
'SvelteAllProps',
'SveltePropsAnyFallback',
'SvelteSlotsAnyFallback',
'SvelteRestProps',
'SvelteSlots',
'SvelteStore',
]);
function isValidCompletion(completion) {
const isSvelte2tsxCompletion = completion.label.startsWith('__sveltets_') || svelte2tsxTypes.has(completion.label);
// Filter out completions for the children prop, as it doesn't work in Astro
const isChildrenCompletion = completion.label === 'children?' &&
completion.kind === language_server_1.CompletionItemKind.Field &&
completion.filterText === 'children={$1}';
if (isSvelte2tsxCompletion || isChildrenCompletion)
return false;
return true;
}
//# sourceMappingURL=completions.js.map

View File

@@ -1,12 +0,0 @@
import type { Diagnostic } from '@volar/language-server';
export declare enum DiagnosticCodes {
IS_NOT_A_MODULE = 2306,// '{0}' is not a module.
CANNOT_FIND_MODULE = 2307,// Cannot find module '{0}' or its corresponding type declarations.
DUPLICATED_JSX_ATTRIBUTES = 17001,// JSX elements cannot have multiple attributes with the same name.
CANT_RETURN_OUTSIDE_FUNC = 1108,// A 'return' statement can only be used within a function body.
ISOLATED_MODULE_COMPILE_ERR = 1208,// '{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file.
TYPE_NOT_ASSIGNABLE = 2322,// Type '{0}' is not assignable to type '{1}'.
JSX_NO_CLOSING_TAG = 17008,// JSX element '{0}' has no corresponding closing tag.
JSX_ELEMENT_NO_CALL = 2604
}
export declare function enhancedProvideSemanticDiagnostics(originalDiagnostics: Diagnostic[], tsxLineCount?: number | undefined): Diagnostic[];

View File

@@ -1,104 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagnosticCodes = void 0;
exports.enhancedProvideSemanticDiagnostics = enhancedProvideSemanticDiagnostics;
// List of codes:
// https://github.com/Microsoft/TypeScript/blob/main/src/compiler/diagnosticMessages.json
var DiagnosticCodes;
(function (DiagnosticCodes) {
DiagnosticCodes[DiagnosticCodes["IS_NOT_A_MODULE"] = 2306] = "IS_NOT_A_MODULE";
DiagnosticCodes[DiagnosticCodes["CANNOT_FIND_MODULE"] = 2307] = "CANNOT_FIND_MODULE";
DiagnosticCodes[DiagnosticCodes["DUPLICATED_JSX_ATTRIBUTES"] = 17001] = "DUPLICATED_JSX_ATTRIBUTES";
DiagnosticCodes[DiagnosticCodes["CANT_RETURN_OUTSIDE_FUNC"] = 1108] = "CANT_RETURN_OUTSIDE_FUNC";
DiagnosticCodes[DiagnosticCodes["ISOLATED_MODULE_COMPILE_ERR"] = 1208] = "ISOLATED_MODULE_COMPILE_ERR";
DiagnosticCodes[DiagnosticCodes["TYPE_NOT_ASSIGNABLE"] = 2322] = "TYPE_NOT_ASSIGNABLE";
DiagnosticCodes[DiagnosticCodes["JSX_NO_CLOSING_TAG"] = 17008] = "JSX_NO_CLOSING_TAG";
DiagnosticCodes[DiagnosticCodes["JSX_ELEMENT_NO_CALL"] = 2604] = "JSX_ELEMENT_NO_CALL";
})(DiagnosticCodes || (exports.DiagnosticCodes = DiagnosticCodes = {}));
function enhancedProvideSemanticDiagnostics(originalDiagnostics, tsxLineCount) {
const diagnostics = originalDiagnostics
.filter((diagnostic) => (tsxLineCount ? diagnostic.range.start.line <= tsxLineCount : true) &&
isNoCantReturnOutsideFunction(diagnostic) &&
isNoIsolatedModuleError(diagnostic) &&
isNoJsxCannotHaveMultipleAttrsError(diagnostic))
.map((diag) => tsxLineCount ? generalEnhancements(astroEnhancements(diag)) : generalEnhancements(diag));
return diagnostics;
}
// General enhancements that apply to all files
function generalEnhancements(diagnostic) {
if (diagnostic.code === DiagnosticCodes.CANNOT_FIND_MODULE &&
diagnostic.message.includes('astro:content')) {
diagnostic.message +=
"\n\nIf you're using content collections, make sure to run `astro dev`, `astro build` or `astro sync` to first generate the types so you can import from them. If you already ran one of those commands, restarting the language server might be necessary in order for the change to take effect.";
return diagnostic;
}
return diagnostic;
}
/**
* Astro-specific enhancements. For instance, when the user tries to import a component from a framework that is not installed
* or a difference with JSX needing a different error message
*/
function astroEnhancements(diagnostic) {
// When the language integrations are not installed, the content of the imported snapshot is empty
// As such, it triggers the "is not a module error", which we can enhance with a more helpful message for the related framework
if (diagnostic.code === DiagnosticCodes.IS_NOT_A_MODULE) {
if (diagnostic.message.includes('.svelte')) {
diagnostic.message +=
'\n\nIs the `@astrojs/svelte` package installed? You can add it to your project by running the following command: `astro add svelte`. If already installed, restarting the language server might be necessary in order for the change to take effect.';
}
if (diagnostic.message.includes('.vue')) {
diagnostic.message +=
'\n\nIs the `@astrojs/vue` package installed? You can add it to your project by running the following command: `astro add vue`. If already installed, restarting the language server might be necessary in order for the change to take effect.';
}
return diagnostic;
}
// JSX element has no closing tag. JSX -> HTML
if (diagnostic.code === DiagnosticCodes.JSX_NO_CLOSING_TAG) {
return {
...diagnostic,
message: diagnostic.message.replace('JSX', 'HTML'),
};
}
// JSX Element can't be constructed or called. This happens on syntax errors / invalid components
if (diagnostic.code === DiagnosticCodes.JSX_ELEMENT_NO_CALL) {
return {
...diagnostic,
message: diagnostic.message
.replace('JSX element type', 'Component')
.replace('does not have any construct or call signatures.', 'is not a valid component.\n\nIf this is a Svelte or Vue component, it might have a syntax error that makes it impossible to parse.'),
};
}
// For the rare case where an user might try to put a client directive on something that is not a component
if (diagnostic.code === DiagnosticCodes.TYPE_NOT_ASSIGNABLE) {
if (diagnostic.message.includes("Property 'client:") &&
diagnostic.message.includes("to type 'HTMLAttributes")) {
return {
...diagnostic,
message: diagnostic.message + '\n\nClient directives are only available on framework components.',
};
}
}
return diagnostic;
}
/**
* Astro allows multiple attributes to have the same name
*/
function isNoJsxCannotHaveMultipleAttrsError(diagnostic) {
return diagnostic.code !== DiagnosticCodes.DUPLICATED_JSX_ATTRIBUTES;
}
/**
* Ignore "Can't return outside of function body"
* Since the frontmatter is at the top level, users trying to return a Response for SSR mode run into this
* TODO: Update the TSX shape so this is not an issue anymore
*/
function isNoCantReturnOutsideFunction(diagnostic) {
return diagnostic.code !== DiagnosticCodes.CANT_RETURN_OUTSIDE_FUNC;
}
/**
* When the content of the file is invalid and can't be parsed properly for TSX generation, TS will show an error about
* how the current module can't be compiled under --isolatedModule, this is confusing to users so let's ignore this
*/
function isNoIsolatedModuleError(diagnostic) {
return diagnostic.code !== DiagnosticCodes.ISOLATED_MODULE_COMPILE_ERR;
}
//# sourceMappingURL=diagnostics.js.map

View File

@@ -1,2 +0,0 @@
import type { LanguageServicePlugin } from '@volar/language-server';
export declare const create: (ts: typeof import("typescript")) => LanguageServicePlugin[];

View File

@@ -1,77 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const volar_service_typescript_1 = require("volar-service-typescript");
const vscode_uri_1 = require("vscode-uri");
const index_js_1 = require("../../core/index.js");
const codeActions_js_1 = require("./codeActions.js");
const completions_js_1 = require("./completions.js");
const diagnostics_js_1 = require("./diagnostics.js");
const create = (ts) => {
const tsServicePlugins = (0, volar_service_typescript_1.create)(ts, {});
return tsServicePlugins.map((plugin) => {
if (plugin.name === 'typescript-semantic') {
return {
...plugin,
create(context) {
const typeScriptPlugin = plugin.create(context);
return {
...typeScriptPlugin,
async provideFileRenameEdits(oldUri, newUri, token) {
const astroConfig = await context.env.getConfiguration?.('astro');
// Check for `false` explicitly, as the default value is `true`, but it might not be set explicitly depending on the editor
if (astroConfig?.updateImportsOnFileMove.enabled === false) {
return null;
}
return typeScriptPlugin.provideFileRenameEdits(oldUri, newUri, token);
},
async provideCompletionItems(document, position, completionContext, token) {
const originalCompletions = await typeScriptPlugin.provideCompletionItems(document, position, completionContext, token);
if (!originalCompletions)
return null;
return (0, completions_js_1.enhancedProvideCompletionItems)(originalCompletions);
},
async resolveCompletionItem(item, token) {
const resolvedCompletionItem = await typeScriptPlugin.resolveCompletionItem(item, token);
if (!resolvedCompletionItem)
return item;
return (0, completions_js_1.enhancedResolveCompletionItem)(resolvedCompletionItem, context);
},
async provideCodeActions(document, range, codeActionContext, token) {
const originalCodeActions = await typeScriptPlugin.provideCodeActions(document, range, codeActionContext, token);
if (!originalCodeActions)
return null;
return (0, codeActions_js_1.enhancedProvideCodeActions)(originalCodeActions, context);
},
async resolveCodeAction(codeAction, token) {
const resolvedCodeAction = await typeScriptPlugin.resolveCodeAction(codeAction, token);
if (!resolvedCodeAction)
return codeAction;
return (0, codeActions_js_1.enhancedResolveCodeAction)(resolvedCodeAction, context);
},
async provideDiagnostics(document, token) {
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const root = sourceScript?.generated?.root;
let tsxLineCount = undefined;
if (root instanceof index_js_1.AstroVirtualCode && decoded?.[1] === 'tsx') {
// If we have compiler errors, our TSX isn't valid so don't bother showing TS errors
if (root.hasCompilationErrors)
return null;
// We'll use this to filter out diagnostics that are outside the mapped range of the TSX
tsxLineCount = root.astroMeta.tsxRanges.body.end.line;
}
const diagnostics = await typeScriptPlugin.provideDiagnostics(document, token);
if (!diagnostics)
return null;
return (0, diagnostics_js_1.enhancedProvideSemanticDiagnostics)(diagnostics, tsxLineCount);
},
};
},
};
}
return plugin;
});
};
exports.create = create;
//# sourceMappingURL=index.js.map

View File

@@ -1,3 +0,0 @@
import type { TextEdit } from 'vscode-html-languageservice';
import type { AstroVirtualCode } from '../../core/index.js';
export declare function mapEdit(edit: TextEdit, code: AstroVirtualCode, languageId: string): TextEdit;

View File

@@ -1,20 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapEdit = mapEdit;
const utils_js_1 = require("../utils.js");
function mapEdit(edit, code, languageId) {
// Don't attempt to move the edit to the frontmatter if the file isn't the root TSX file, it means it's a script tag
if (languageId === 'typescriptreact') {
if ((0, utils_js_1.editShouldBeInFrontmatter)(edit.range, code.astroMeta).itShould) {
edit = (0, utils_js_1.ensureProperEditForFrontmatter)(edit, code.astroMeta, '\n');
}
}
else {
// If the edit is at the start of the file, add a newline before it, otherwise we'll get `<script>text`
if (edit.range.start.line === 0 && edit.range.start.character === 0) {
edit.newText = '\n' + edit.newText;
}
}
return edit;
}
//# sourceMappingURL=utils.js.map

View File

@@ -1,38 +0,0 @@
import type { HTMLDocument, Node, TextEdit } from 'vscode-html-languageservice';
import { Range } from 'vscode-html-languageservice';
import type { AstroMetadata, FrontmatterStatus } from '../core/parseAstro.js';
export declare function isJSDocument(languageId: string): languageId is "typescript" | "typescriptreact" | "javascript" | "javascriptreact";
/**
* Return true if a specific node could be a component.
* This is not a 100% sure test as it'll return false for any component that does not match the standard format for a component
*/
export declare function isPossibleComponent(node: Node): boolean;
/**
* Return if a given offset is inside the start tag of a component
*/
export declare function isInComponentStartTag(html: HTMLDocument, offset: number): boolean;
/**
* Return if a given position is inside a JSX expression
*/
export declare function isInsideExpression(html: string, tagStart: number, position: number): boolean;
/**
* Return if a given offset is inside the frontmatter
*/
export declare function isInsideFrontmatter(offset: number, frontmatter: FrontmatterStatus): boolean;
type FrontmatterEditPosition = 'top' | 'bottom';
export declare function ensureProperEditForFrontmatter(edit: TextEdit, metadata: AstroMetadata, newLine: string, position?: FrontmatterEditPosition): TextEdit;
/**
* Force a range to be at the start of the frontmatter if it is outside
*/
export declare function ensureRangeIsInFrontmatter(range: Range, metadata: AstroMetadata, position?: FrontmatterEditPosition): Range;
export declare function getNewFrontmatterEdit(edit: TextEdit, astroMetadata: AstroMetadata, newLine: string): TextEdit;
export declare function getOpenFrontmatterEdit(edit: TextEdit, astroMetadata: AstroMetadata, newLine: string): TextEdit;
type FrontmatterEditValidity = {
itShould: false;
position: undefined;
} | {
itShould: true;
position: FrontmatterEditPosition;
};
export declare function editShouldBeInFrontmatter(range: Range, astroMetadata: AstroMetadata): FrontmatterEditValidity;
export {};

View File

@@ -1,114 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJSDocument = isJSDocument;
exports.isPossibleComponent = isPossibleComponent;
exports.isInComponentStartTag = isInComponentStartTag;
exports.isInsideExpression = isInsideExpression;
exports.isInsideFrontmatter = isInsideFrontmatter;
exports.ensureProperEditForFrontmatter = ensureProperEditForFrontmatter;
exports.ensureRangeIsInFrontmatter = ensureRangeIsInFrontmatter;
exports.getNewFrontmatterEdit = getNewFrontmatterEdit;
exports.getOpenFrontmatterEdit = getOpenFrontmatterEdit;
exports.editShouldBeInFrontmatter = editShouldBeInFrontmatter;
const vscode_html_languageservice_1 = require("vscode-html-languageservice");
function isJSDocument(languageId) {
return (languageId === 'javascript' ||
languageId === 'typescript' ||
languageId === 'javascriptreact' ||
languageId === 'typescriptreact');
}
/**
* Return true if a specific node could be a component.
* This is not a 100% sure test as it'll return false for any component that does not match the standard format for a component
*/
function isPossibleComponent(node) {
if (!node.tag)
return false;
return !!/[A-Z]/.test(node.tag?.[0]) || !!/.+\.[A-Z]?/.test(node.tag);
}
/**
* Return if a given offset is inside the start tag of a component
*/
function isInComponentStartTag(html, offset) {
const node = html.findNodeAt(offset);
return isPossibleComponent(node) && (!node.startTagEnd || offset < node.startTagEnd);
}
/**
* Return if a given position is inside a JSX expression
*/
function isInsideExpression(html, tagStart, position) {
const charactersInNode = html.substring(tagStart, position);
return charactersInNode.lastIndexOf('{') > charactersInNode.lastIndexOf('}');
}
/**
* Return if a given offset is inside the frontmatter
*/
function isInsideFrontmatter(offset, frontmatter) {
switch (frontmatter.status) {
case 'closed':
return offset > frontmatter.position.start.offset && offset < frontmatter.position.end.offset;
case 'open':
return offset > frontmatter.position.start.offset;
case 'doesnt-exist':
return false;
}
}
function ensureProperEditForFrontmatter(edit, metadata, newLine, position = 'top') {
switch (metadata.frontmatter.status) {
case 'open':
return getOpenFrontmatterEdit(edit, metadata, newLine);
case 'closed':
const newRange = ensureRangeIsInFrontmatter(edit.range, metadata, position);
return {
newText: newRange.start.line === metadata.frontmatter.position.start.line &&
edit.newText.startsWith(newLine)
? edit.newText.trimStart()
: edit.newText,
range: newRange,
};
case 'doesnt-exist':
return getNewFrontmatterEdit(edit, metadata, newLine);
}
}
/**
* Force a range to be at the start of the frontmatter if it is outside
*/
function ensureRangeIsInFrontmatter(range, metadata, position = 'top') {
if (metadata.frontmatter.status === 'open' || metadata.frontmatter.status === 'closed') {
const frontmatterEndPosition = metadata.frontmatter.position.end
? metadata.tsxRanges.frontmatter.end
: undefined;
// If the range start is outside the frontmatter, return a range at the start of the frontmatter
if (range.start.line < metadata.tsxRanges.frontmatter.start.line ||
(frontmatterEndPosition && range.start.line > frontmatterEndPosition.line)) {
if (frontmatterEndPosition && position === 'bottom') {
return vscode_html_languageservice_1.Range.create(frontmatterEndPosition, frontmatterEndPosition);
}
return vscode_html_languageservice_1.Range.create(metadata.tsxRanges.frontmatter.start, metadata.tsxRanges.frontmatter.start);
}
return range;
}
return range;
}
function getNewFrontmatterEdit(edit, astroMetadata, newLine) {
edit.newText = `---${edit.newText.startsWith(newLine) ? '' : newLine}${edit.newText}---${newLine}${newLine}`;
edit.range = vscode_html_languageservice_1.Range.create(astroMetadata.tsxRanges.frontmatter.start, astroMetadata.tsxRanges.frontmatter.start);
return edit;
}
function getOpenFrontmatterEdit(edit, astroMetadata, newLine) {
edit.newText = edit.newText.startsWith(newLine)
? `${edit.newText}---`
: `${newLine}${edit.newText}---`;
edit.range = vscode_html_languageservice_1.Range.create(astroMetadata.tsxRanges.frontmatter.start, astroMetadata.tsxRanges.frontmatter.start);
return edit;
}
// Most edits that are at the beginning of the TSX, or outside the document are intended for the frontmatter
function editShouldBeInFrontmatter(range, astroMetadata) {
const isAtTSXStart = range.start.line < astroMetadata.tsxRanges.frontmatter.start.line;
const isPastFile = range.start.line > astroMetadata.tsxRanges.body.end.line;
const shouldIt = isAtTSXStart || isPastFile;
return shouldIt
? { itShould: true, position: isPastFile ? 'bottom' : 'top' }
: { itShould: false, position: undefined };
}
//# sourceMappingURL=utils.js.map

View File

@@ -1,7 +0,0 @@
import type { LanguageServicePlugin } from '@volar/language-service';
import type { Provide } from 'volar-service-yaml';
import type { CollectionConfig } from '../core/frontmatterHolders.js';
type LanguageSettings = Parameters<ReturnType<Provide['yaml/languageService']>['configure']>['0'];
export declare function getSettings(collectionConfig: CollectionConfig): LanguageSettings;
export declare const create: (collectionConfig: CollectionConfig) => LanguageServicePlugin;
export {};

View File

@@ -1,112 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
exports.getSettings = getSettings;
const language_server_1 = require("@volar/language-server");
const volar_service_yaml_1 = require("volar-service-yaml");
const vscode_uri_1 = require("vscode-uri");
const frontmatterHolders_js_1 = require("../core/frontmatterHolders.js");
function getSettings(collectionConfig) {
const schemas = collectionConfig.configs.flatMap((workspaceCollectionConfig) => {
return workspaceCollectionConfig.config.collections.flatMap((collection) => {
return {
fileMatch: frontmatterHolders_js_1.SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS.map((ext) => `volar-embedded-content://yaml_frontmatter_${collection.name}/**/*${ext}`),
uri: vscode_uri_1.Utils.joinPath(workspaceCollectionConfig.folder, '.astro/collections', `${collection.name}.schema.json`).toString(),
};
});
});
return {
completion: true,
format: false,
hover: true,
validate: true,
customTags: [],
yamlVersion: '1.2',
isKubernetes: false,
parentSkeletonSelectedFirst: false,
disableDefaultProperties: false,
schemas: schemas,
};
}
const create = (collectionConfig) => {
const yamlPlugin = (0, volar_service_yaml_1.create)({
getLanguageSettings: () => getSettings(collectionConfig),
});
return {
...yamlPlugin,
capabilities: {
...yamlPlugin.capabilities,
codeLensProvider: undefined,
},
create(context) {
const yamlPluginInstance = yamlPlugin.create(context);
const languageService = yamlPluginInstance.provide?.['yaml/languageService']();
if (languageService && context.env.onDidChangeWatchedFiles) {
context.env.onDidChangeWatchedFiles(async (events) => {
const changedSchemas = events.changes.filter((change) => change.uri.endsWith('.schema.json'));
const changedConfig = events.changes.some((change) => change.uri.endsWith('collections.json'));
if (changedConfig) {
collectionConfig.reload(
// For some reason, context.env.workspaceFolders is not an array of WorkspaceFolders nor the older format, strange
context.env.workspaceFolders.map((folder) => ({ uri: folder.toString() })));
languageService.configure(getSettings(collectionConfig));
}
for (const change of changedSchemas) {
languageService.resetSchema(change.uri);
}
});
}
return {
...yamlPluginInstance,
// Disable codelenses, we'll provide our own
provideCodeLenses: undefined,
resolveCodeLens: undefined,
async provideDiagnostics(document, token) {
const originalDiagnostics = await yamlPluginInstance.provideDiagnostics(document, token);
if (!originalDiagnostics) {
return null;
}
const decoded = context.decodeEmbeddedDocumentUri(vscode_uri_1.URI.parse(document.uri));
const sourceScript = decoded && context.language.scripts.get(decoded[0]);
const root = sourceScript?.generated?.root;
if (!(root instanceof frontmatterHolders_js_1.FrontmatterHolder))
return undefined;
// If we don't have a frontmatter, but there are errors, it probably means a frontmatter was required
if (!root.hasFrontmatter && originalDiagnostics.length > 0) {
return [
language_server_1.Diagnostic.create(language_server_1.Range.create(0, 0, 0, 0), 'Frontmatter is required for this file.', language_server_1.DiagnosticSeverity.Error),
];
}
return originalDiagnostics.map((diagnostic) => {
// The YAML schema source is not useful to users, since it's generated. Also, it's quite long.
if (diagnostic.source?.startsWith('yaml-schema:')) {
diagnostic.source = 'astro';
// In Astro, schema errors are always fatal
diagnostic.severity = language_server_1.DiagnosticSeverity.Error;
// Map missing properties to the entire frontmatte
if (diagnostic.message.startsWith('Missing property')) {
diagnostic.range = language_server_1.Range.create({ line: 0, character: 0 }, document.positionAt(document.getText().length));
}
}
return diagnostic;
});
},
async provideHover(document, position, token) {
const originalHover = await yamlPluginInstance.provideHover(document, position, token);
if (!originalHover) {
return null;
}
if (language_server_1.MarkupContent.is(originalHover.contents)) {
// Remove last line that contains the source schema, it's not useful to users since they're generated
originalHover.contents.value = originalHover.contents.value
.replace(/\nSource:.*$/, '')
.trim();
}
return originalHover;
},
};
},
};
};
exports.create = create;
//# sourceMappingURL=yaml.js.map