@mdsvex/language-server 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.
package/package.json CHANGED
@@ -1,15 +1,44 @@
1
1
  {
2
2
  "name": "@mdsvex/language-server",
3
- "version": "0.0.0",
4
- "description": "Placeholder release so npm trusted publishing can be configured.",
5
- "license": "MIT",
6
- "homepage": "https://mdsvex.pngwn.io",
3
+ "version": "0.1.0-next.1",
7
4
  "repository": {
8
5
  "type": "git",
9
- "url": "https://github.com/pngwn/MDsveX",
6
+ "url": "git+https://github.com/pngwn/MDsveX.git",
10
7
  "directory": "language-tools/language-server"
11
8
  },
12
- "publishConfig": {
13
- "access": "public"
9
+ "description": "PFM Language Server — LSP binary for .pfm files",
10
+ "type": "module",
11
+ "bin": {
12
+ "pfm-language-server": "./bin/pfm-language-server.js"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "import": "./src/index.ts",
17
+ "types": "./src/index.ts"
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "@volar/language-core": "^2.4.28",
22
+ "@volar/language-server": "^2.4.28",
23
+ "@volar/typescript": "^2.4.28",
24
+ "volar-service-css": "^0.0.70",
25
+ "volar-service-markdown": "^0.0.70",
26
+ "svelte2tsx": "^0.7.53",
27
+ "volar-service-typescript": "^0.0.70",
28
+ "vscode-languageserver": "^9.0.1",
29
+ "vscode-uri": "^3.0.8",
30
+ "@mdsvex/language-core": "0.1.0-next.1"
31
+ },
32
+ "devDependencies": {
33
+ "@volar/test-utils": "^2.4.28",
34
+ "svelte": "^5.0.0",
35
+ "typescript": "^5.0.0"
36
+ },
37
+ "author": "pngwn <hello@pngwn.io>",
38
+ "license": "MIT",
39
+ "scripts": {
40
+ "test": "vitest --disableConsoleIntercept",
41
+ "test:run": "vitest run --silent",
42
+ "build": "vite build --config vite.config.build.ts"
14
43
  }
15
44
  }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Clean up svelte2tsx internal types in hover tooltips.
3
+ *
4
+ * 1. Strips `(alias) type X = SvelteComponent<...> & { $$bindings?: ... }\n`
5
+ * 2. Transforms `const X: __sveltets_2_IsomorphicComponent<{props}, ...>` into `const X<{props}>`
6
+ */
7
+ export function clean_svelte_hover(markdown: string): string {
8
+ markdown = strip_svelte_component_type(markdown);
9
+ markdown = strip_runes_component_type(markdown);
10
+ markdown = clean_isomorphic_component(markdown);
11
+ return markdown;
12
+ }
13
+
14
+ /** the $on and $set alias svelte2tsx declares beside a runes component */
15
+ function strip_runes_component_type(md: string): string {
16
+ const re = /^(?:\(alias\) )?type [\w$]+ = \{\n(?:[ \t]+\$(?:on|set)\?\(.*\n)+\}\n/m;
17
+ for (let m = re.exec(md); m !== null; m = re.exec(md))
18
+ md = md.slice(0, m.index) + md.slice(m.index + m[0].length);
19
+ return md;
20
+ }
21
+
22
+ /** Remove `(alias) type X = SvelteComponent<...> & { ... }\n` lines. */
23
+ function strip_svelte_component_type(md: string): string {
24
+ const marker = "type ";
25
+ let search_from = 0;
26
+ while (true) {
27
+ const type_idx = md.indexOf(marker, search_from);
28
+ if (type_idx === -1) return md;
29
+
30
+ // Check: does this type declaration use SvelteComponent?
31
+ const eq_idx = md.indexOf("= SvelteComponent<", type_idx);
32
+ if (eq_idx === -1 || eq_idx - type_idx > 80) {
33
+ search_from = type_idx + 1;
34
+ continue;
35
+ }
36
+
37
+ // Find the start of this declaration line (scan back to "(alias) " or newline)
38
+ let line_start = type_idx;
39
+ while (line_start > 0 && md[line_start - 1] !== "\n") line_start--;
40
+
41
+ // Find the end: track braces past the `& { $$bindings... }` block
42
+ let i = eq_idx + "= SvelteComponent<".length;
43
+ let angle_depth = 1;
44
+ // First pass: find closing > of SvelteComponent<...>
45
+ while (i < md.length && angle_depth > 0) {
46
+ if (md[i] === "<") angle_depth++;
47
+ else if (md[i] === ">" && md[i - 1] !== "=") angle_depth--;
48
+ i++;
49
+ }
50
+ // Check for `& { ... }` after the closing >
51
+ const after_angle = md.slice(i, i + 10).trimStart();
52
+ if (after_angle.startsWith("& {")) {
53
+ i = md.indexOf("& {", i) + 2;
54
+ let brace_depth = 0;
55
+ while (i < md.length) {
56
+ if (md[i] === "{") brace_depth++;
57
+ else if (md[i] === "}") {
58
+ brace_depth--;
59
+ if (brace_depth === 0) { i++; break; }
60
+ }
61
+ i++;
62
+ }
63
+ }
64
+ // Skip trailing newline
65
+ if (i < md.length && md[i] === "\n") i++;
66
+
67
+ md = md.slice(0, line_start) + md.slice(i);
68
+ search_from = line_start;
69
+ }
70
+ }
71
+
72
+ /** Transform `: __sveltets_2_IsomorphicComponent<{props}, ...>` into `<{props}>`. */
73
+ function clean_isomorphic_component(md: string): string {
74
+ const marker = ": __sveltets_2_IsomorphicComponent<";
75
+ const idx = md.indexOf(marker);
76
+ if (idx === -1) return md;
77
+
78
+ const args_start = idx + marker.length;
79
+
80
+ // Find end of first generic arg (props), first comma at brace depth 0
81
+ let depth = 0;
82
+ let first_arg_end = -1;
83
+ for (let i = args_start; i < md.length; i++) {
84
+ const ch = md[i];
85
+ if (ch === "{") depth++;
86
+ else if (ch === "}") depth--;
87
+ else if (ch === "," && depth === 0) { first_arg_end = i; break; }
88
+ }
89
+ if (first_arg_end === -1) return md;
90
+
91
+ // Find closing > (skip => arrow functions)
92
+ let angle_depth = 1;
93
+ let full_end = -1;
94
+ for (let i = args_start; i < md.length; i++) {
95
+ if (md[i] === "<") angle_depth++;
96
+ else if (md[i] === ">") {
97
+ if (i > 0 && md[i - 1] === "=") continue;
98
+ angle_depth--;
99
+ if (angle_depth === 0) { full_end = i + 1; break; }
100
+ }
101
+ }
102
+ if (full_end === -1) return md;
103
+
104
+ const first_arg = md.slice(args_start, first_arg_end).trim();
105
+ return md.slice(0, idx) + "<" + first_arg + ">" + md.slice(full_end);
106
+ }
@@ -0,0 +1,36 @@
1
+ /** what compile rejects or warns about, typescript reports the rest */
2
+
3
+ import type { LanguageServicePlugin } from '@volar/language-server';
4
+ import { root_code } from './root_code';
5
+
6
+ const ERROR = 1;
7
+ const WARNING = 2;
8
+
9
+ export function create_compile_diagnostics(): LanguageServicePlugin {
10
+ return {
11
+ name: 'mdsvex-compile',
12
+ capabilities: {
13
+ diagnosticProvider: {
14
+ interFileDependencies: false,
15
+ workspaceDiagnostics: false,
16
+ },
17
+ },
18
+ create(context) {
19
+ return {
20
+ provideDiagnostics(document) {
21
+ const root = root_code(context, document);
22
+ if (root?.diagnostics === undefined) return;
23
+ return root.diagnostics.map((d) => ({
24
+ range: {
25
+ start: document.positionAt(d.start),
26
+ end: document.positionAt(d.end),
27
+ },
28
+ message: d.message,
29
+ severity: d.severity === 'error' ? ERROR : WARNING,
30
+ source: 'mdsvex',
31
+ }));
32
+ },
33
+ };
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,163 @@
1
+ /** template names, frontmatter keys and values, and directive args, from the props of each component */
2
+
3
+ import { CompletionItemKind } from '@volar/language-server';
4
+ import type {
5
+ CompletionItem,
6
+ LanguageServicePlugin,
7
+ } from '@volar/language-server';
8
+ import type * as TS from 'typescript';
9
+ import type { Provide } from 'volar-service-typescript/lib/plugins/semantic';
10
+ import {
11
+ completion_context,
12
+ probe_for,
13
+ props_of,
14
+ template_named,
15
+ } from '@mdsvex/language-core';
16
+ import type { PfmVirtualCode, Prop } from '@mdsvex/language-core';
17
+ import { URI } from 'vscode-uri';
18
+ import { root_code } from './root_code';
19
+
20
+ const SUGGEST = { title: 'suggest', command: 'editor.action.triggerSuggest' };
21
+
22
+ /** a plain yaml scalar or arg value when it reads back as itself, quoted otherwise */
23
+ function written(value: string, plain: RegExp): string {
24
+ return plain.test(value) ? value : JSON.stringify(value);
25
+ }
26
+
27
+ export function create_completions(ts: typeof TS): LanguageServicePlugin {
28
+ return {
29
+ name: 'mdsvex-completions',
30
+ capabilities: {
31
+ // a value follows the space after a colon, args follow the paren, a comma or an equals sign
32
+ completionProvider: { triggerCharacters: [' ', '(', ',', '='] },
33
+ },
34
+ create(context) {
35
+ const props = (
36
+ root: PfmVirtualCode,
37
+ uri: string,
38
+ kind: 'template' | 'directive',
39
+ name: string | undefined,
40
+ template: string | undefined
41
+ ): Prop[] => {
42
+ if (name === undefined) return [];
43
+ const probe = probe_for(root.probes, kind, name, template);
44
+ const ls = context.inject<Provide, 'typescript/languageService'>(
45
+ 'typescript/languageService'
46
+ );
47
+ const decoded = context.decodeEmbeddedDocumentUri(URI.parse(uri));
48
+ if (!probe || !ls || !decoded) return [];
49
+ const file = context.inject<Provide, 'typescript/documentFileName'>(
50
+ 'typescript/documentFileName',
51
+ decoded[0]
52
+ );
53
+ const program = ls.getProgram();
54
+ if (!program || !file) return [];
55
+ // the program types against the typescript volar was built with
56
+ const typed = program as unknown as TS.Program;
57
+ return props_of(ts, typed, file, probe.alias) ?? [];
58
+ };
59
+
60
+ return {
61
+ provideCompletionItems(document, position) {
62
+ const root = root_code(context, document);
63
+ if (!root) return;
64
+ const source = document.getText();
65
+ const at = completion_context(
66
+ source,
67
+ document.offsetAt(position),
68
+ root.frontmatter
69
+ );
70
+ if (at === null) return;
71
+ const range = {
72
+ start: document.positionAt(at.range.start),
73
+ end: document.positionAt(at.range.end),
74
+ };
75
+ const named = template_named(source, root.frontmatter);
76
+ const template =
77
+ named === false ? undefined : (named ?? root.template);
78
+ let items: CompletionItem[] = [];
79
+
80
+ if (at.kind === 'template') {
81
+ items = root.templates.map((t, i) => ({
82
+ label: t.name,
83
+ kind: CompletionItemKind.EnumMember,
84
+ detail: t.file ?? 'template',
85
+ sortText: String(i).padStart(4, '0'),
86
+ textEdit: { range, newText: t.name },
87
+ }));
88
+ if (items.length !== 0)
89
+ items.push({
90
+ label: 'false',
91
+ kind: CompletionItemKind.Value,
92
+ detail: 'no template',
93
+ sortText: '9999',
94
+ textEdit: { range, newText: 'false' },
95
+ });
96
+ } else if (at.kind === 'frontmatter_key' || at.kind === 'arg_key') {
97
+ const list =
98
+ at.kind === 'frontmatter_key'
99
+ ? props(root, document.uri, 'template', template, undefined)
100
+ : props(
101
+ root,
102
+ document.uri,
103
+ 'directive',
104
+ at.directive,
105
+ template
106
+ );
107
+ // snippets, never props an author writes
108
+ const reserved =
109
+ at.kind === 'arg_key' && !at.inline
110
+ ? ['children', 'label']
111
+ : ['children'];
112
+ const sep = at.kind === 'frontmatter_key' ? ': ' : '=';
113
+ items = list
114
+ .filter(
115
+ (p) =>
116
+ !reserved.includes(p.name) && !at.existing.includes(p.name)
117
+ )
118
+ .map((p) => ({
119
+ label: p.name,
120
+ kind: CompletionItemKind.Property,
121
+ detail: p.optional ? `${p.type} (optional)` : p.type,
122
+ documentation: p.documentation || undefined,
123
+ sortText: (p.optional ? '1' : '0') + p.name,
124
+ textEdit: { range, newText: p.name + sep },
125
+ command: p.values.length !== 0 ? SUGGEST : undefined,
126
+ }));
127
+ } else {
128
+ const list =
129
+ at.kind === 'frontmatter_value'
130
+ ? props(root, document.uri, 'template', template, undefined)
131
+ : props(
132
+ root,
133
+ document.uri,
134
+ 'directive',
135
+ at.directive,
136
+ template
137
+ );
138
+ const prop = list.find((p) => p.name === at.key);
139
+ // yaml reads these plain scalars back as the same string, args stop at a comma or paren
140
+ const plain =
141
+ at.kind === 'frontmatter_value'
142
+ ? /^(?![-?:,[\]{}#&*!|>'"%@`]|true$|false$|null$|~$|[-+.\d])[^:#\n]*$/
143
+ : /^[^\s,)"']+$/;
144
+ items = (prop?.values ?? []).map((v, i) => {
145
+ const literal =
146
+ v === 'true' || v === 'false' || !Number.isNaN(Number(v));
147
+ return {
148
+ label: v,
149
+ kind: CompletionItemKind.EnumMember,
150
+ detail: prop!.type,
151
+ sortText: String(i).padStart(4, '0'),
152
+ textEdit: { range, newText: literal ? v : written(v, plain) },
153
+ };
154
+ });
155
+ }
156
+ return items.length === 0
157
+ ? undefined
158
+ : { isIncomplete: false, items };
159
+ },
160
+ };
161
+ },
162
+ };
163
+ }
@@ -0,0 +1,31 @@
1
+ import type {
2
+ Location,
3
+ LocationLink,
4
+ Position,
5
+ Range,
6
+ } from '@volar/language-server';
7
+
8
+ function contains(range: Range, at: Position): boolean {
9
+ const after_start =
10
+ at.line > range.start.line ||
11
+ (at.line === range.start.line && at.character >= range.start.character);
12
+ const before_end =
13
+ at.line < range.end.line ||
14
+ (at.line === range.end.line && at.character <= range.end.character);
15
+ return after_start && before_end;
16
+ }
17
+
18
+ /** drops the markdown self definition of a heading when another target exists, so a jump goes straight to its component */
19
+ export function without_self<T extends Location | LocationLink>(
20
+ results: T[] | null | undefined,
21
+ uri: string,
22
+ at: Position
23
+ ): T[] | null | undefined {
24
+ if (!Array.isArray(results) || results.length < 2) return results;
25
+ const others = results.filter((r) => {
26
+ const target = 'targetUri' in r ? r.targetUri : r.uri;
27
+ const range = 'targetUri' in r ? r.targetRange : r.range;
28
+ return target !== uri || !contains(range, at);
29
+ });
30
+ return others.length === 0 ? results : others;
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * PFM Language Server.
3
+ */
4
+
5
+ import {
6
+ createConnection,
7
+ createServer,
8
+ createTypeScriptProject,
9
+ loadTsdkByPath,
10
+ } from "@volar/language-server/node";
11
+ import { create as createTypeScriptServices } from "volar-service-typescript";
12
+ import { create as createCssService } from "volar-service-css";
13
+ import { create as createMarkdownService } from "volar-service-markdown";
14
+ import {
15
+ create_config_loader,
16
+ create_pfm_language_plugin,
17
+ create_svelte_language_plugin,
18
+ } from "@mdsvex/language-core";
19
+ import type { ConfigLoader } from "@mdsvex/language-core";
20
+ import { watch } from "node:fs";
21
+ import { clean_svelte_hover } from "./clean_hover";
22
+ import { without_self } from "./definitions";
23
+ import { create_compile_diagnostics } from "./compile_diagnostics";
24
+ import { create_completions } from "./completions";
25
+ import { URI } from "vscode-uri";
26
+ import { forEachEmbeddedCode } from "@volar/language-core";
27
+ import type { LanguagePlugin, VirtualCode } from "@volar/language-core";
28
+ import type { TypeScriptExtraServiceScript } from "@volar/typescript";
29
+ import type * as ts from "typescript";
30
+
31
+ /**
32
+ * Create the PFM LanguagePlugin for Volar's server (URI-based),
33
+ * with the critical `typescript` property that registers .pfm
34
+ * as a TypeScript-processable extension.
35
+ */
36
+ function createPfmLanguagePluginForServer(
37
+ typescript: typeof ts,
38
+ config: ConfigLoader,
39
+ ): LanguagePlugin<URI> {
40
+ const inner = create_pfm_language_plugin({ typescript, config });
41
+
42
+ return {
43
+ getLanguageId(scriptId: URI): string | undefined {
44
+ if (scriptId.scheme !== "file" && scriptId.scheme !== "untitled") {
45
+ return undefined;
46
+ }
47
+ return inner.getLanguageId(scriptId.fsPath);
48
+ },
49
+
50
+ createVirtualCode(scriptId, languageId, snapshot) {
51
+ if (languageId !== "pfm") return undefined;
52
+ try {
53
+ const result = inner.createVirtualCode!(
54
+ scriptId.fsPath,
55
+ languageId,
56
+ snapshot,
57
+ { getAssociatedScript: () => undefined },
58
+ );
59
+ return result as VirtualCode | undefined;
60
+ } catch (e: any) {
61
+ console.error("[PFM] createVirtualCode error:", e.message);
62
+ return undefined;
63
+ }
64
+ },
65
+
66
+ updateVirtualCode(scriptId, virtualCode, newSnapshot) {
67
+ try {
68
+ const result = inner.updateVirtualCode!(
69
+ scriptId.fsPath,
70
+ virtualCode as any,
71
+ newSnapshot,
72
+ { getAssociatedScript: () => undefined },
73
+ );
74
+ return result as VirtualCode | undefined;
75
+ } catch (e: any) {
76
+ console.error("[PFM] updateVirtualCode error:", e.message);
77
+ return undefined;
78
+ }
79
+ },
80
+
81
+ // tells typescript about the document extensions
82
+ typescript: {
83
+ extraFileExtensions: inner.typescript!.extraFileExtensions,
84
+ getServiceScript(root: VirtualCode) {
85
+ const tsCode = root.embeddedCodes?.find(
86
+ (c) => c.languageId === "typescript",
87
+ );
88
+ if (tsCode) {
89
+ return {
90
+ code: tsCode,
91
+ extension: ".ts" as any,
92
+ scriptKind: 3 satisfies ts.ScriptKind.TS,
93
+ };
94
+ }
95
+ return undefined;
96
+ },
97
+ getExtraServiceScripts() {
98
+ return [];
99
+ },
100
+ },
101
+ };
102
+ }
103
+
104
+ function createSvelteLanguagePluginForServer(): LanguagePlugin<URI> {
105
+ const inner = create_svelte_language_plugin();
106
+
107
+ return {
108
+ getLanguageId(scriptId: URI): string | undefined {
109
+ if (scriptId.path.endsWith(".svelte")) {
110
+ return "svelte";
111
+ }
112
+ return undefined;
113
+ },
114
+
115
+ createVirtualCode(scriptId, languageId, snapshot) {
116
+ if (languageId !== "svelte") return undefined;
117
+ try {
118
+ return inner.createVirtualCode!(
119
+ scriptId.fsPath,
120
+ languageId,
121
+ snapshot,
122
+ { getAssociatedScript: () => undefined },
123
+ ) as VirtualCode | undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ },
128
+
129
+ updateVirtualCode(scriptId, virtualCode, newSnapshot) {
130
+ try {
131
+ return inner.updateVirtualCode!(
132
+ scriptId.fsPath,
133
+ virtualCode as any,
134
+ newSnapshot,
135
+ { getAssociatedScript: () => undefined },
136
+ ) as VirtualCode | undefined;
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ },
141
+
142
+ typescript: inner.typescript as any,
143
+ };
144
+ }
145
+
146
+ const connection = createConnection();
147
+
148
+ // Intercept hover to clean up svelte2tsx internal type noise.
149
+ const _on_hover = connection.onHover.bind(connection);
150
+ (connection as any).onHover = (handler: Function) => {
151
+ _on_hover(async (params: any, token: any) => {
152
+ const result = await handler(params, token);
153
+ if (result?.contents?.kind === "markdown" && typeof result.contents.value === "string") {
154
+ result.contents.value = clean_svelte_hover(result.contents.value);
155
+ }
156
+ return result;
157
+ });
158
+ };
159
+
160
+ const _on_definition = connection.onDefinition.bind(connection);
161
+ (connection as any).onDefinition = (handler: Function) => {
162
+ _on_definition(
163
+ async (params: any, token: any) =>
164
+ without_self(await handler(params, token), params.textDocument.uri, params.position) as any,
165
+ );
166
+ };
167
+
168
+ const server = createServer(connection);
169
+
170
+ connection.listen();
171
+
172
+ // the manifest sits in node_modules, which editors do not watch, so the server does
173
+ const watched = new Set<string>();
174
+ let reload_timer: ReturnType<typeof setTimeout> | undefined;
175
+ function config_changed() {
176
+ clearTimeout(reload_timer);
177
+ reload_timer = setTimeout(() => {
178
+ server.project.reload();
179
+ server.languageFeatures.requestRefresh(false);
180
+ }, 100);
181
+ }
182
+ function watch_config(file: string) {
183
+ if (watched.has(file)) return;
184
+ watched.add(file);
185
+ try {
186
+ // a rename replaces the manifest, which ends a watch on its old inode
187
+ const watcher = watch(file, () => {
188
+ watcher.close();
189
+ watched.delete(file);
190
+ config_changed();
191
+ });
192
+ watcher.on("error", () => watched.delete(file));
193
+ } catch {
194
+ watched.delete(file);
195
+ }
196
+ }
197
+
198
+ connection.onInitialize((params) => {
199
+ const tsdk = loadTsdkByPath(
200
+ params.initializationOptions?.typescript?.tsdk,
201
+ params.locale,
202
+ );
203
+ // the tsdk types against the typescript volar was built with
204
+ const typescript = tsdk.typescript as unknown as typeof ts;
205
+ const config = create_config_loader({ typescript, on_read: watch_config });
206
+
207
+ return server.initialize(
208
+ params,
209
+ createTypeScriptProject(
210
+ tsdk.typescript,
211
+ tsdk.diagnosticMessages,
212
+ () => ({
213
+ languagePlugins: [
214
+ createPfmLanguagePluginForServer(typescript, config),
215
+ createSvelteLanguagePluginForServer(),
216
+ ],
217
+ }),
218
+ ),
219
+ [
220
+ ...createTypeScriptServices(tsdk.typescript),
221
+ createCssService(),
222
+ createMarkdownService(),
223
+ create_compile_diagnostics(),
224
+ create_completions(typescript),
225
+ ],
226
+ );
227
+ });
228
+
229
+ connection.onInitialized(() => {
230
+ server.initialized();
231
+ // a config that appears later, or one an editor does watch, reloads too
232
+ server.fileWatcher.watchFiles([
233
+ "**/mdsvex.config.json",
234
+ "**/node_modules/.mdsvex/manifest.json",
235
+ ]);
236
+ server.fileWatcher.onDidChangeWatchedFiles(({ changes }) => {
237
+ if (
238
+ changes.some(
239
+ (c) =>
240
+ c.uri.endsWith("/mdsvex.config.json") ||
241
+ c.uri.endsWith("/.mdsvex/manifest.json"),
242
+ )
243
+ ) {
244
+ config_changed();
245
+ }
246
+ });
247
+ });
248
+
249
+ connection.onShutdown(server.shutdown);
@@ -0,0 +1,16 @@
1
+ import type { LanguageServiceContext } from '@volar/language-server';
2
+ import type { PfmVirtualCode } from '@mdsvex/language-core';
3
+ import { URI } from 'vscode-uri';
4
+
5
+ /** the pfm root code of a document, whose offsets are those of the source */
6
+ export function root_code(
7
+ context: LanguageServiceContext,
8
+ document: { uri: string; languageId: string }
9
+ ): PfmVirtualCode | undefined {
10
+ if (document.languageId !== 'pfm') return;
11
+ const decoded = context.decodeEmbeddedDocumentUri(URI.parse(document.uri));
12
+ if (decoded === undefined) return;
13
+ return context.language.scripts.get(decoded[0])?.generated?.root as
14
+ | PfmVirtualCode
15
+ | undefined;
16
+ }