New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@astrojs/ts-plugin

Package Overview
Dependencies
Maintainers
3
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@astrojs/ts-plugin - npm Package Compare versions

Comparing version 1.0.10 to 1.1.0

dist/language.d.ts

17

dist/astro2tsx.d.ts

@@ -1,2 +0,15 @@

import type { TSXResult } from '@astrojs/compiler/types';
export declare function astro2tsx(content: string, fileName: string): TSXResult;
import { VirtualFile } from '@volar/language-core';
export declare function astro2tsx(input: string, fileName: string, ts: typeof import('typescript/lib/tsserverlibrary.js')): {
virtualFile: VirtualFile;
diagnostics: import("@astrojs/compiler").DiagnosticMessage[] | {
code: 1000;
location: {
file: string;
line: number;
column: number;
length: number;
};
severity: 1;
text: string;
}[];
};
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.astro2tsx = void 0;
const sync_1 = require("@astrojs/compiler/sync");
function astro2tsx(content, fileName) {
const sourcemap_codec_1 = require("@jridgewell/sourcemap-codec");
const language_core_1 = require("@volar/language-core");
const node_path_1 = __importDefault(require("node:path"));
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
function safeConvertToTSX(content, options) {
try {
const tsx = (0, sync_1.convertToTSX)(content, { filename: fileName });
const tsx = (0, sync_1.convertToTSX)(content, { filename: options.filename });
return tsx;
}
catch (e) {
console.error(`There was an error transforming ${fileName} to TSX. An empty file will be returned instead. Please create an issue: https://github.com/withastro/language-tools/issues\nError: ${e}.`);
console.error(`There was an error transforming ${options.filename} to TSX. An empty file will be returned instead. Please create an issue: https://github.com/withastro/language-tools/issues\nError: ${e}.`);
return {
code: '',
map: {
file: fileName,
file: options.filename ?? '',
sources: [],

@@ -22,6 +29,115 @@ sourcesContent: [],

},
diagnostics: [],
diagnostics: [
{
code: 1000,
location: { file: options.filename, line: 1, column: 1, length: content.length },
severity: 1,
text: `The Astro compiler encountered an unknown error while parsing this file. Please create an issue with your code and the error shown in the server's logs: https://github.com/withastro/language-tools/issues`,
},
],
};
}
}
function astro2tsx(input, fileName, ts) {
const tsx = safeConvertToTSX(input, { filename: fileName });
return {
virtualFile: getVirtualFileTSX(input, tsx, fileName, ts),
diagnostics: tsx.diagnostics,
};
}
exports.astro2tsx = astro2tsx;
function getVirtualFileTSX(input, tsx, fileName, ts) {
tsx.code = patchTSX(tsx.code, fileName);
const v3Mappings = (0, sourcemap_codec_1.decode)(tsx.map.mappings);
const sourcedDoc = vscode_languageserver_textdocument_1.TextDocument.create(fileName, 'astro', 0, input);
const genDoc = vscode_languageserver_textdocument_1.TextDocument.create(fileName + '.tsx', 'typescriptreact', 0, tsx.code);
const mappings = [];
let current;
for (let genLine = 0; genLine < v3Mappings.length; genLine++) {
for (const segment of v3Mappings[genLine]) {
const genCharacter = segment[0];
const genOffset = genDoc.offsetAt({ line: genLine, character: genCharacter });
if (current) {
let length = genOffset - current.genOffset;
const sourceText = input.substring(current.sourceOffset, current.sourceOffset + length);
const genText = tsx.code.substring(current.genOffset, current.genOffset + length);
if (sourceText !== genText) {
length = 0;
for (let i = 0; i < genOffset - current.genOffset; i++) {
if (sourceText[i] === genText[i]) {
length = i + 1;
}
else {
break;
}
}
}
if (length > 0) {
const lastMapping = mappings.length ? mappings[mappings.length - 1] : undefined;
if (lastMapping &&
lastMapping.generatedRange[1] === current.genOffset &&
lastMapping.sourceRange[1] === current.sourceOffset) {
lastMapping.generatedRange[1] = current.genOffset + length;
lastMapping.sourceRange[1] = current.sourceOffset + length;
}
else {
mappings.push({
sourceRange: [current.sourceOffset, current.sourceOffset + length],
generatedRange: [current.genOffset, current.genOffset + length],
data: language_core_1.FileRangeCapabilities.full,
});
}
}
current = undefined;
}
if (segment[2] !== undefined && segment[3] !== undefined) {
const sourceOffset = sourcedDoc.offsetAt({ line: segment[2], character: segment[3] });
current = {
genOffset,
sourceOffset,
};
}
}
}
const ast = ts.createSourceFile('/a.tsx', tsx.code, ts.ScriptTarget.ESNext);
if (ast.statements[0]) {
mappings.push({
sourceRange: [0, input.length],
generatedRange: [ast.statements[0].getStart(ast), tsx.code.length],
data: {},
});
}
return {
fileName: fileName + '.tsx',
kind: language_core_1.FileKind.TypeScriptHostFile,
capabilities: {
codeAction: true,
documentFormatting: false,
diagnostic: true,
documentSymbol: true,
inlayHint: true,
foldingRange: true,
},
codegenStacks: [],
snapshot: {
getText: (start, end) => tsx.code.substring(start, end),
getLength: () => tsx.code.length,
getChangeRange: () => undefined,
},
mappings: mappings,
embeddedFiles: [],
};
}
function patchTSX(code, fileName) {
const basename = node_path_1.default.basename(fileName, node_path_1.default.extname(fileName));
const isDynamic = basename.startsWith('[') && basename.endsWith(']');
return code.replace(/\b(\S*)__AstroComponent_/gm, (fullMatch, m1) => {
// If we don't have a match here, it usually means the file has a weird name that couldn't be expressed with valid identifier characters
if (!m1) {
if (basename === '404')
return 'FourOhFour';
return fullMatch;
}
return isDynamic ? `_${m1}_` : m1[0].toUpperCase() + m1.slice(1);
});
}

7

dist/index.d.ts
import type ts from 'typescript/lib/tsserverlibrary';
declare function init(modules: {
typescript: typeof import('typescript/lib/tsserverlibrary');
}): {
create: (info: ts.server.PluginCreateInfo) => ts.LanguageService;
getExternalFiles: (project: ts.server.ConfiguredProject) => string[];
};
declare const init: ts.server.PluginModuleFactory;
export = init;
"use strict";
const astro_snapshots_js_1 = require("./astro-snapshots.js");
const index_js_1 = require("./language-service/index.js");
const logger_js_1 = require("./logger.js");
const module_loader_js_1 = require("./module-loader.js");
const project_astro_files_js_1 = require("./project-astro-files.js");
const utils_js_1 = require("./utils.js");
function init(modules) {
const ts = modules.typescript;
function create(info) {
const logger = new logger_js_1.Logger(info.project.projectService.logger);
const parsedCommandLine = info.languageServiceHost.getParsedCommandLine?.((0, utils_js_1.getConfigPathForProject)(info.project));
if (!isAstroProject(info.project, parsedCommandLine)) {
logger.log('Detected that this is not an Astro project, abort patching TypeScript');
const language_core_1 = require("@volar/language-core");
const typescript_1 = require("@volar/typescript");
const language_js_1 = require("./language.js");
const externalFiles = new WeakMap();
const init = (modules) => {
const { typescript: ts } = modules;
const pluginModule = {
create(info) {
const virtualFiles = (0, language_core_1.createVirtualFiles)([(0, language_js_1.getLanguageModule)(ts)]);
(0, typescript_1.decorateLanguageService)(virtualFiles, info.languageService, true);
(0, typescript_1.decorateLanguageServiceHost)(virtualFiles, info.languageServiceHost, ts, ['.astro']);
return info.languageService;
}
if ((0, index_js_1.isPatched)(info.languageService)) {
return info.languageService;
}
logger.log('Starting Astro plugin');
const snapshotManager = new astro_snapshots_js_1.AstroSnapshotManager(modules.typescript, info.project.projectService, logger);
if (parsedCommandLine) {
new project_astro_files_js_1.ProjectAstroFilesManager(modules.typescript, info.project, info.serverHost, snapshotManager, parsedCommandLine);
}
(0, module_loader_js_1.patchModuleLoader)(logger, snapshotManager, modules.typescript, info.languageServiceHost, info.project);
return (0, index_js_1.decorateLanguageService)(info.languageService, snapshotManager, ts, logger);
}
function getExternalFiles(project) {
return project_astro_files_js_1.ProjectAstroFilesManager.getInstance(project.getProjectName())?.getFiles() ?? [];
}
function isAstroProject(project, parsedCommandLine) {
if (parsedCommandLine) {
const astroFiles = (0, utils_js_1.readProjectAstroFilesFromFs)(ts, project, parsedCommandLine);
if (astroFiles.length > 0)
return true;
}
try {
const compilerOptions = project.getCompilerOptions();
const hasAstroInstalled = typeof compilerOptions.configFilePath !== 'string' ||
require.resolve('astro', { paths: [compilerOptions.configFilePath] });
return hasAstroInstalled;
}
catch (e) {
project.projectService.logger.info(e);
return false;
}
}
return { create, getExternalFiles };
}
},
getExternalFiles(project) {
if (!externalFiles.has(project)) {
externalFiles.set(project, (0, typescript_1.getExternalFiles)(ts, project, ['.astro']));
}
return externalFiles.get(project);
},
};
return pluginModule;
};
module.exports = init;
{
"name": "@astrojs/ts-plugin",
"version": "1.0.10",
"version": "1.1.0",
"description": "A TypeScript Plugin providing Astro intellisense",

@@ -25,4 +25,7 @@ "main": "dist/index.js",

"dependencies": {
"@astrojs/compiler": "^1.5.1",
"@jridgewell/trace-mapping": "^0.3.18"
"@volar/language-core": "~1.9.0",
"@volar/typescript": "~1.9.0",
"@astrojs/compiler": "1.5.7",
"@jridgewell/sourcemap-codec": "^1.4.15",
"vscode-languageserver-textdocument": "^1.0.8"
},

@@ -29,0 +32,0 @@ "devDependencies": {

# @astrojs/ts-plugin
Work in progress TypeScript plugin adding support for `.astro` imports in `.ts` files
> Using the Astro VS Code extension? This plugin is automatically installed and configured for you.
TypeScript plugin adding support for `.astro` imports in `.ts` files. This plugin also adds support for renaming symbols and finding references across `.ts` and `.astro` files.
## Installation
```bash
npm install --save-dev @astrojs/ts-plugin
```
## Usage
Add the plugin to your `tsconfig.json`:
```json
{
"compilerOptions": {
"plugins": [
{
"name": "@astrojs/ts-plugin"
}
]
}
}
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc