@mdsvex/language-core 0.0.0 → 0.1.0-next.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.
@@ -0,0 +1,168 @@
1
+ /** a typescript language service decorated with the pfm and svelte plugins as tsserver is */
2
+
3
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import * as fs from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import ts from 'typescript';
9
+ import { createLanguage, FileMap } from '@volar/language-core';
10
+ import type { LanguagePlugin } from '@volar/language-core';
11
+ import {
12
+ createProxyLanguageService,
13
+ decorateLanguageServiceHost,
14
+ resolveFileLanguageId,
15
+ } from '@volar/typescript';
16
+
17
+ import {
18
+ create_pfm_language_plugin,
19
+ create_svelte_language_plugin,
20
+ } from '../src/index';
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url));
23
+
24
+ export interface Project {
25
+ root: string;
26
+ /** absolute path of a project file */
27
+ path(file: string): string;
28
+ write(file: string, content: string): void;
29
+ /** the plain text of the quick info at the first offset of needle in file */
30
+ hover(file: string, needle: string, delta?: number): string | undefined;
31
+ /** syntactic and semantic diagnostics of file, with the text they cover */
32
+ diagnostics(file: string): { text: string; message: string; code: number }[];
33
+ /** suggestion diagnostics of file, such as a declaration never read */
34
+ suggestions(file: string): { text: string; message: string; code: number }[];
35
+ /** where a rename at the first offset of needle in file edits, as file and offset */
36
+ rename(file: string, needle: string, delta?: number): [string, number][];
37
+ /** the program over the generated typescript, as the language server holds it */
38
+ program(): ts.Program;
39
+ dispose(): void;
40
+ }
41
+
42
+ /** files are written under the package, so svelte resolves from its node_modules */
43
+ export function project(files: Record<string, string>): Project {
44
+ const root = mkdtempSync(join(HERE, '.tmp-project-'));
45
+ const versions = new Map<string, number>();
46
+ const write = (file: string, content: string) => {
47
+ const at = join(root, file);
48
+ mkdirSync(dirname(at), { recursive: true });
49
+ writeFileSync(at, content);
50
+ versions.set(at, (versions.get(at) ?? 0) + 1);
51
+ };
52
+ for (const [file, content] of Object.entries(files)) write(file, content);
53
+
54
+ const plugins: LanguagePlugin<string>[] = [
55
+ create_pfm_language_plugin({ typescript: ts }),
56
+ create_svelte_language_plugin(),
57
+ { getLanguageId: resolveFileLanguageId },
58
+ ];
59
+ const snapshot = (file: string) =>
60
+ fs.existsSync(file)
61
+ ? ts.ScriptSnapshot.fromString(readFileSync(file, 'utf8'))
62
+ : undefined;
63
+ const language = createLanguage(
64
+ plugins,
65
+ new FileMap(ts.sys.useCaseSensitiveFileNames),
66
+ (file) => {
67
+ const snap = snapshot(file);
68
+ if (snap) language.scripts.set(file, snap);
69
+ else language.scripts.delete(file);
70
+ }
71
+ );
72
+ const options: ts.CompilerOptions = {
73
+ target: ts.ScriptTarget.ESNext,
74
+ module: ts.ModuleKind.ESNext,
75
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
76
+ strict: true,
77
+ allowJs: true,
78
+ checkJs: false,
79
+ skipLibCheck: true,
80
+ types: [],
81
+ noEmit: true,
82
+ allowImportingTsExtensions: true,
83
+ verbatimModuleSyntax: false,
84
+ // what tsserver sets for extensions a plugin adds
85
+ allowNonTsExtensions: true,
86
+ };
87
+ const host: ts.LanguageServiceHost = {
88
+ getCompilationSettings: () => options,
89
+ getScriptFileNames: () =>
90
+ [...versions.keys()].filter((f) => /\.(pfm|svx|ts)$/.test(f)),
91
+ getScriptVersion: (file) => String(versions.get(file) ?? 0),
92
+ getScriptSnapshot: snapshot,
93
+ getCurrentDirectory: () => root,
94
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
95
+ fileExists: ts.sys.fileExists,
96
+ readFile: ts.sys.readFile,
97
+ readDirectory: ts.sys.readDirectory,
98
+ directoryExists: ts.sys.directoryExists,
99
+ getDirectories: ts.sys.getDirectories,
100
+ realpath: ts.sys.realpath,
101
+ // the decoration resolves plugin extensions and gives their script kind through these
102
+ getScriptKind(file) {
103
+ if (file.endsWith('.ts')) return ts.ScriptKind.TS;
104
+ if (file.endsWith('.js')) return ts.ScriptKind.JS;
105
+ if (file.endsWith('.json')) return ts.ScriptKind.JSON;
106
+ return ts.ScriptKind.Deferred;
107
+ },
108
+ resolveModuleNameLiterals(literals, containing, redirected, options) {
109
+ return literals.map((literal) =>
110
+ ts.resolveModuleName(literal.text, containing, options, ts.sys)
111
+ );
112
+ },
113
+ };
114
+ // volar types against its own typescript version
115
+ decorateLanguageServiceHost(ts as any, language, host as any);
116
+ const { proxy, initialize } = createProxyLanguageService(
117
+ ts.createLanguageService(host) as any
118
+ );
119
+ initialize(language);
120
+
121
+ const text = (file: string) => readFileSync(join(root, file), 'utf8');
122
+ return {
123
+ root,
124
+ path: (file) => join(root, file),
125
+ write,
126
+ hover(file, needle, delta = 0) {
127
+ const at = text(file).indexOf(needle);
128
+ if (at < 0) throw new Error(`${needle} is not in ${file}`);
129
+ const info = proxy.getQuickInfoAtPosition(join(root, file), at + delta);
130
+ return info && ts.displayPartsToString(info.displayParts);
131
+ },
132
+ diagnostics(file) {
133
+ const at = join(root, file);
134
+ const source = text(file);
135
+ return [
136
+ ...proxy.getSyntacticDiagnostics(at),
137
+ ...proxy.getSemanticDiagnostics(at),
138
+ ].map((d) => ({
139
+ text: source.slice(d.start!, d.start! + d.length!),
140
+ message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
141
+ code: d.code,
142
+ }));
143
+ },
144
+ suggestions(file) {
145
+ const source = text(file);
146
+ return proxy.getSuggestionDiagnostics(join(root, file)).map((d) => ({
147
+ text: source.slice(d.start!, d.start! + d.length!),
148
+ message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
149
+ code: d.code,
150
+ }));
151
+ },
152
+ rename(file, needle, delta = 0) {
153
+ const at = text(file).indexOf(needle);
154
+ if (at < 0) throw new Error(`${needle} is not in ${file}`);
155
+ const found =
156
+ proxy.findRenameLocations(join(root, file), at + delta, false, false, {}) ??
157
+ [];
158
+ return found.map((l) => [
159
+ l.fileName.slice(root.length + 1),
160
+ l.textSpan.start,
161
+ ]);
162
+ },
163
+ program: () => proxy.getProgram()!,
164
+ dispose() {
165
+ rmSync(root, { recursive: true, force: true });
166
+ },
167
+ };
168
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "include": ["src/**/*", "test/**/*"],
3
+ "compilerOptions": {
4
+ "target": "es2020",
5
+ "module": "esnext",
6
+ "moduleResolution": "bundler",
7
+ "forceConsistentCasingInFileNames": true,
8
+ "esModuleInterop": true,
9
+ "strict": true
10
+ }
11
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # @mdsvex/language-core
2
-
3
- Placeholder. The first real release is published from CI.