@mdsvex/language-core 0.1.0-next.0 → 0.1.0-next.2

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,53 @@
1
+ /**
2
+ * PFM Volar LanguagePlugin.
3
+ *
4
+ * Teaches Volar how to handle .pfm files by producing TypeScript
5
+ * VirtualCode through the pipeline:
6
+ *
7
+ * PFM source -> pfmToSvelte -> svelte2tsx -> compose mappings -> VirtualCode
8
+ */
9
+ import type { LanguagePlugin, VirtualCode, IScriptSnapshot, CodeMapping } from '@volar/language-core';
10
+ import type { PfmDiagnostic, PropsProbe } from '@mdsvex/source-map/pfm-to-svelte';
11
+ import type * as TS from 'typescript';
12
+ import type { ConfigLoader } from './config.js';
13
+ export interface PfmVirtualCode extends VirtualCode {
14
+ id: string;
15
+ languageId: string;
16
+ snapshot: IScriptSnapshot;
17
+ mappings: CodeMapping[];
18
+ embeddedCodes: VirtualCode[];
19
+ /** compile errors and warnings, typescript reports the rest */
20
+ diagnostics: PfmDiagnostic[];
21
+ /** the yaml of the frontmatter, null without any */
22
+ frontmatter: {
23
+ start: number;
24
+ end: number;
25
+ } | null;
26
+ /** the templates the frontmatter template key can name */
27
+ templates: TemplateChoice[];
28
+ /** the template the document compiled with */
29
+ template?: string;
30
+ /** type aliases in the typescript code holding the props of each template and directive */
31
+ probes: PropsProbe[];
32
+ }
33
+ export interface TemplateChoice {
34
+ name: string;
35
+ /** the template file relative to the document, when the config resolves it */
36
+ file?: string;
37
+ }
38
+ export interface PfmLanguagePluginOptions {
39
+ /** reads the exports of templates a mdsvex.config.json names, without it they replace nothing */
40
+ typescript?: typeof TS;
41
+ /** where the mdsvex config of a document comes from, by default the nearest manifest or json config */
42
+ config?: ConfigLoader;
43
+ }
44
+ /**
45
+ * Create a PFM LanguagePlugin for Volar.
46
+ *
47
+ * Usage:
48
+ * const plugin = createPfmLanguagePlugin();
49
+ * // Pass to @volar/language-server or @volar/kit
50
+ */
51
+ export declare function create_pfm_language_plugin(plugin_options?: PfmLanguagePluginOptions): LanguagePlugin<string, PfmVirtualCode>;
52
+ /** .pfm and .svx always, another extension when the config of the file lists it */
53
+ export declare function is_document(file: string, config: ConfigLoader): boolean;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Minimal Svelte LanguagePlugin.
3
+ *
4
+ * Runs svelte2tsx on .svelte files to produce TypeScript VirtualCode,
5
+ * enabling component prop types to resolve when imported from .pfm files.
6
+ *
7
+ * This is NOT a full Svelte language server, it only provides enough
8
+ * for cross-file type resolution.
9
+ */
10
+ import type { LanguagePlugin } from "@volar/language-core";
11
+ /**
12
+ * Create a minimal Svelte LanguagePlugin for cross-file type resolution.
13
+ */
14
+ export declare function create_svelte_language_plugin(): LanguagePlugin<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdsvex/language-core",
3
- "version": "0.1.0-next.0",
3
+ "version": "0.1.0-next.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/pngwn/MDsveX.git",
@@ -8,27 +8,37 @@
8
8
  },
9
9
  "description": "PFM Volar LanguagePlugin — teaches Volar how to handle .pfm files",
10
10
  "type": "module",
11
+ "files": [
12
+ "dist"
13
+ ],
11
14
  "exports": {
12
15
  ".": {
13
- "import": "./src/index.ts",
14
- "types": "./src/index.ts"
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
15
18
  }
16
19
  },
20
+ "types": "./dist/index.d.ts",
17
21
  "dependencies": {
18
22
  "@volar/language-core": "^2.4.28",
19
23
  "@volar/typescript": "^2.4.28",
20
24
  "svelte2tsx": "^0.7.53",
21
- "@mdsvex/source-map": "0.1.0-next.0",
22
- "@mdsvex/render": "1.0.0-next.0"
25
+ "temml": "^0.14.0",
26
+ "@mdsvex/render": "1.0.0-next.2",
27
+ "@mdsvex/source-map": "0.1.0-next.2",
28
+ "mdsvex": "1.0.0-next.2"
23
29
  },
24
30
  "devDependencies": {
25
31
  "svelte": "^5.0.0",
26
32
  "typescript": "^5.0.0"
27
33
  },
34
+ "peerDependencies": {
35
+ "typescript": "^5.0.0"
36
+ },
28
37
  "author": "pngwn <hello@pngwn.io>",
29
38
  "license": "MIT",
30
39
  "scripts": {
31
40
  "test": "vitest --disableConsoleIntercept",
32
- "test:run": "vitest run --silent"
41
+ "test:run": "vitest run --silent",
42
+ "build": "vite build --config vite.config.build.ts && tsc -p tsconfig.build.json"
33
43
  }
34
44
  }
package/CHANGELOG.md DELETED
@@ -1,13 +0,0 @@
1
- # @mdsvex/language-core
2
-
3
- ## 0.1.0-next.0
4
-
5
- ### Minor Changes
6
-
7
- - [#799](https://github.com/pngwn/MDsveX/pull/799) [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9) Thanks [@pngwn](https://github.com/pngwn)! - Add language tools
8
-
9
- ### Patch Changes
10
-
11
- - Updated dependencies [[`6ac3826`](https://github.com/pngwn/MDsveX/commit/6ac382615eb410230e8423d5ca4202005588869e), [`e5b7abe`](https://github.com/pngwn/MDsveX/commit/e5b7abe1ebf868b1df1e934fb96e1e363696f3e9), [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9)]:
12
- - @mdsvex/render@1.0.0-next.0
13
- - @mdsvex/source-map@0.1.0-next.0
@@ -1 +0,0 @@
1
- export const SVELTE_SHIMS = "// Whenever a ambient declaration changes, its number should be increased\n// This way, we avoid the situation where multiple ambient versions of svelte2tsx\n// are loaded and their declarations conflict each other\n// See https://github.com/sveltejs/language-tools/issues/1059 for an example bug that stems from it\n// If you change anything in this file, think about whether or not it should be backported to svelte-shims.d.ts\n\ntype AConstructorTypeOf<T, U extends any[] = any[]> = new (...args: U) => T;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteActionReturnType = {\n\tupdate?: (args: any) => void,\n\tdestroy?: () => void\n} | void\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteTransitionConfig = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteTransitionReturnType = SvelteTransitionConfig | (() => SvelteTransitionConfig)\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteAnimationReturnType = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteWithOptionalProps<Props, Keys extends keyof Props> = Omit<Props, Keys> & Partial<Pick<Props, Keys>>;\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteAllProps = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SveltePropsAnyFallback<Props> = {[K in keyof Props]: Props[K] extends never ? never : Props[K] extends undefined ? any : Props[K]}\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteSlotsAnyFallback<Slots> = {[K in keyof Slots]: {[S in keyof Slots[K]]: Slots[K][S] extends undefined ? any : Slots[K][S]}}\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteRestProps = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteSlots = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteStore<T> = { subscribe: (run: (value: T) => any, invalidate?: any) => any }\n\n// Forces TypeScript to look into the type which results in a better representation of it\n// which helps for error messages and is necessary for d.ts file transformation so that\n// no ambient type references are left in the output\n/** @internal PRIVATE API, DO NOT USE */\ntype Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype KeysMatching<Obj, V> = {[K in keyof Obj]-?: Obj[K] extends V ? K : never}[keyof Obj]\n/** @internal PRIVATE API, DO NOT USE */\ndeclare type __sveltets_2_CustomEvents<T> = {[K in KeysMatching<T, CustomEvent>]: T[K] extends CustomEvent ? T[K]['detail']: T[K]}\n\ndeclare function __sveltets_2_ensureRightProps<Props>(props: Props): {};\ndeclare function __sveltets_2_instanceOf<T = any>(type: AConstructorTypeOf<T>): T;\ndeclare function __sveltets_2_allPropsType(): SvelteAllProps\ndeclare function __sveltets_2_restPropsType(): SvelteRestProps\ndeclare function __sveltets_2_slotsType<Slots, Key extends keyof Slots>(slots: Slots): Record<Key, boolean>;\n\n// Overload of the following two functions is necessary.\n// An empty array of optionalProps makes OptionalProps type any, which means we lose the prop typing.\n// optionalProps need to be first or its type cannot be infered correctly.\n\ndeclare function __sveltets_2_partial<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SveltePropsAnyFallback<Props>>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\ndeclare function __sveltets_2_partial<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string, OptionalProps extends keyof Props = any>(\n optionalProps: OptionalProps[],\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps>>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_partial_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SveltePropsAnyFallback<Props> & SvelteAllProps>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\ndeclare function __sveltets_2_partial_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string, OptionalProps extends keyof Props = any>(\n optionalProps: OptionalProps[],\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps> & SvelteAllProps>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\n\n\ndeclare function __sveltets_2_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<Props & SvelteAllProps>, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_with_any_event<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Props, events: Events & {[evt: string]: CustomEvent<any>;}, slots: Slots, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_store_get<T = any>(store: SvelteStore<T>): T\ndeclare function __sveltets_2_store_get<Store extends SvelteStore<any> | undefined | null>(store: Store): Store extends SvelteStore<infer T> ? T : Store;\ndeclare function __sveltets_2_any(dummy: any): any;\ndeclare function __sveltets_2_invalidate<T>(getValue: () => T): T\n\ndeclare function __sveltets_2_mapWindowEvent<K extends keyof HTMLBodyElementEventMap>(\n event: K\n): HTMLBodyElementEventMap[K];\ndeclare function __sveltets_2_mapBodyEvent<K extends keyof WindowEventMap>(\n event: K\n): WindowEventMap[K];\ndeclare function __sveltets_2_mapElementEvent<K extends keyof HTMLElementEventMap>(\n event: K\n): HTMLElementEventMap[K];\n\ndeclare function __sveltets_2_bubbleEventDef<Events, K extends keyof Events>(\n events: Events, eventKey: K\n): Events[K];\ndeclare function __sveltets_2_bubbleEventDef(\n events: any, eventKey: string\n): any;\n\ndeclare const __sveltets_2_customEvent: CustomEvent<any>;\ndeclare function __sveltets_2_toEventTypings<Typings>(): {[Key in keyof Typings]: CustomEvent<Typings[Key]>};\n\ndeclare function __sveltets_2_unionType<T1, T2>(t1: T1, t2: T2): T1 | T2;\ndeclare function __sveltets_2_unionType<T1, T2, T3>(t1: T1, t2: T2, t3: T3): T1 | T2 | T3;\ndeclare function __sveltets_2_unionType<T1, T2, T3, T4>(t1: T1, t2: T2, t3: T3, t4: T4): T1 | T2 | T3 | T4;\ndeclare function __sveltets_2_unionType(...types: any[]): any;\n\ndeclare function __sveltets_2_createSvelte2TsxComponent<Props extends {}, Events extends {}, Slots extends {}>(\n render: {props: Props, events: Events, slots: Slots }\n): typeof import(\"svelte\").SvelteComponent<Props, Events, Slots>;\n\ndeclare function __sveltets_2_unwrapArr<T>(arr: ArrayLike<T>): T\ndeclare function __sveltets_2_unwrapPromiseLike<T>(promise: PromiseLike<T> | T): T\n\n// v2\ndeclare function __sveltets_2_createCreateSlot<Slots = Record<string, Record<string, any>>>(): <SlotName extends keyof Slots>(slotName: SlotName, attrs: Slots[SlotName]) => Record<string, any>;\ndeclare function __sveltets_2_createComponentAny(props: Record<string, any>): import(\"svelte\").SvelteComponent<any, any, any>;\n\ndeclare function __sveltets_2_any(...dummy: any[]): any;\ndeclare function __sveltets_2_empty(...dummy: any[]): {};\ndeclare function __sveltets_2_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(t1:T1,t2?:T2,t3?:T3,t4?:T4,t5?:T5,t6?:T6,t7?:T7,t8?:T8,t9?:T9,t10?:T10): T1 & T2 & T3 & T4 & T5 & T6 & T7 & T8 & T9 & T10;\ndeclare function __sveltets_2_nonNullable<T>(type: T): NonNullable<T>;\n\ndeclare function __sveltets_2_cssProp(prop: Record<string, any>): {};\n\n// @ts-ignore Svelte v3/v4 don't have this\ndeclare function __sveltets_2_ensureSnippet(val: ReturnType<import('svelte').Snippet> | undefined | null): any;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteAnimationReturnType = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\ndeclare var __sveltets_2_AnimationMove: { from: DOMRect, to: DOMRect }\ndeclare function __sveltets_2_ensureAnimation(animationCall: __sveltets_2_SvelteAnimationReturnType): {};\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteActionReturnType = {\n\tupdate?: (args: any) => void,\n\tdestroy?: () => void,\n $$_attributes?: Record<string, any>,\n} | void\ndeclare function __sveltets_2_ensureAction<T extends __sveltets_2_SvelteActionReturnType>(actionCall: T): T extends {$$_attributes?: any} ? T['$$_attributes'] : {};\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteTransitionConfig = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteTransitionReturnType = __sveltets_2_SvelteTransitionConfig | (() => __sveltets_2_SvelteTransitionConfig)\ndeclare function __sveltets_2_ensureTransition(transitionCall: __sveltets_2_SvelteTransitionReturnType): {};\n\n// Includes undefined and null for all types as all usages also allow these\ndeclare function __sveltets_2_ensureType<T>(type: AConstructorTypeOf<T>, el: T | undefined | null): {};\ndeclare function __sveltets_2_ensureType<T1, T2>(type1: AConstructorTypeOf<T1>, type2: AConstructorTypeOf<T2>, el: T1 | T2 | undefined | null): {};\n\n// The following is necessary because there are two clashing errors that can't be solved at the same time\n// when using Svelte2TsxComponent, more precisely the event typings in\n// __sveltets_2_ensureComponent<T extends new (..) => _SvelteComponent<any,||any||<-this,any>>(type: T): T;\n// If we type it as \"any\", we have an error when using sth like {a: CustomEvent<any>}\n// If we type it as \"{}\", we have an error when using sth like {[evt: string]: CustomEvent<any>}\n// If we type it as \"unknown\", we get all kinds of follow up errors which we want to avoid\n// Therefore introduce two more base classes just for this case.\n/**\n * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT\n */\ndeclare type ATypedSvelteComponent = {\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$prop_def: any;\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$events_def: any;\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$slot_def: any;\n\n $on(event: string, handler: any): () => void;\n}\n/**\n * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT.\n * \n * If you're looking for the type of a Svelte Component, use `SvelteComponent` and `ComponentType` instead:\n *\n * ```ts\n * import type { ComponentType, SvelteComponent } from \"svelte\";\n * let myComponentConstructor: ComponentType<SvelteComponent> = ..;\n * ```\n */\ndeclare type ConstructorOfATypedSvelteComponent = new (args: {target: any, props?: any}) => ATypedSvelteComponent\n// Usage note: Cannot properly transform generic function components to class components due to TypeScript limitations\ndeclare function __sveltets_2_ensureComponent<\n T extends\n | ConstructorOfATypedSvelteComponent\n | (typeof import('svelte') extends { mount: any }\n ? // @ts-ignore svelte.Component doesn't exist in Svelte 4\n import('svelte').Component<any, any, any>\n : never)\n | null\n | undefined\n>(\n type: T\n): NonNullable<\n T extends ConstructorOfATypedSvelteComponent\n ? T\n : typeof import('svelte') extends { mount: any }\n ? // @ts-ignore svelte.Component doesn't exist in Svelte 4\n T extends import('svelte').Component<\n infer Props extends Record<string, any>,\n infer Exports extends Record<string, any>,\n infer Bindings extends string\n >\n ? new (\n options: import('svelte').ComponentConstructorOptions<Props>\n ) => import('svelte').SvelteComponent<Props, Props['$$events'], Props['$$slots']> &\n Exports & { $$bindings: Bindings }\n : never\n : never\n>;\n\ndeclare function __sveltets_2_ensureArray<T extends ArrayLike<unknown> | Iterable<unknown>>(\n // Svelte 5 allows undefined or null here, Svelte 4 doesn't\n array: T | (typeof import('svelte') extends { mount: any } ? (undefined | null) : never)\n): T extends ArrayLike<infer U> ? U[] : T extends Iterable<infer U> ? Iterable<U> : any[];\n\ntype __sveltets_2_PropsWithChildren<Props, Slots> = Props &\n (Slots extends { default: any }\n // This is unfortunate because it means \"accepts no props\" turns into \"accepts any prop\"\n // but the alternative is non-fixable type errors because of the way TypeScript index\n // signatures work (they will always take precedence and make an impossible-to-satisfy children type).\n ? Props extends Record<string, never>\n ? any\n : { children?: any }\n : {});\ndeclare function __sveltets_2_runes_constructor<Props extends {}>(render: {props: Props }): import(\"svelte\").ComponentConstructorOptions<Props>;\n\ndeclare function __sveltets_2_get_set_binding<T>(get: (() => T) | null | undefined, set: (t: T) => void): T;\n\ndeclare function __sveltets_$$bindings<Bindings extends string[]>(...bindings: Bindings): Bindings[number];\n\ndeclare function __sveltets_2_fn_component<\n Props extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n // @ts-ignore Svelte 5 only\n>(klass: {props: Props, exports?: Exports, bindings?: Bindings }): import('svelte').Component<Props, Exports, Bindings>;\n\ninterface __sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {\n new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & { $$bindings?: Bindings } & Exports;\n (internal: unknown, props: Props extends Record<string, never> ? {$$events?: Events, $$slots?: Slots} : Props & {$$events?: Events, $$slots?: Slots}): Exports & { $set?: any, $on?: any };\n z_$$bindings?: Bindings;\n}\n\ndeclare function __sveltets_2_isomorphic_component<\n Props extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent<Props, Events, Slots, Exports, Bindings>;\n\ndeclare function __sveltets_2_isomorphic_component_slots<\n Props extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent<__sveltets_2_PropsWithChildren<Props, Slots>, Events, Slots, Exports, Bindings>;\n";
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export { create_pfm_language_plugin } from "./language_plugin";
2
- export { create_svelte_language_plugin } from "./svelte_plugin";
3
-
4
- export type { PfmVirtualCode } from "./language_plugin";
@@ -1,405 +0,0 @@
1
- /**
2
- * PFM Volar LanguagePlugin.
3
- *
4
- * Teaches Volar how to handle .pfm files by producing TypeScript
5
- * VirtualCode through the pipeline:
6
- *
7
- * PFM source -> pfmToSvelte -> svelte2tsx -> compose mappings -> VirtualCode
8
- */
9
-
10
- import type {
11
- LanguagePlugin,
12
- VirtualCode,
13
- IScriptSnapshot,
14
- CodeMapping,
15
- CodegenContext,
16
- } from "@volar/language-core";
17
- import { forEachEmbeddedCode } from "@volar/language-core";
18
- import type { TypeScriptExtraServiceScript } from "@volar/typescript";
19
-
20
- import { pfmToSvelte } from "@mdsvex/source-map/pfm-to-svelte";
21
- import { v3ToVolarMappings } from "@mdsvex/source-map/v3-to-volar";
22
- import { composeMappings } from "@mdsvex/source-map/compose-mappings";
23
- import { svelte2tsx as svelte_2_tsx } from "svelte2tsx";
24
- import type { CodeInformation } from "@mdsvex/render/mappings";
25
-
26
- const PFM_EXTENSION = ".pfm";
27
- const PFM_LANGUAGE_ID = "pfm";
28
-
29
- import { SVELTE_SHIMS } from "./_svelte_shims";
30
-
31
- /** Prepend shims content to svelte2tsx output and shift mappings. */
32
- function inject_shims(
33
- tsx_code: string,
34
- raw_mappings: ReturnType<typeof v3ToVolarMappings>,
35
- ): { code: string; mappings: typeof raw_mappings } {
36
- if (!SVELTE_SHIMS) return { code: tsx_code, mappings: raw_mappings };
37
- const prefix = SVELTE_SHIMS + "\n";
38
- const prefixLen = prefix.length;
39
- return {
40
- code: prefix + tsx_code,
41
- mappings: raw_mappings.map((m) => ({
42
- ...m,
43
- generatedOffsets: m.generatedOffsets.map((o) => o + prefixLen),
44
- })),
45
- };
46
- }
47
-
48
- export interface PfmVirtualCode extends VirtualCode {
49
- id: string;
50
- languageId: string;
51
- snapshot: IScriptSnapshot;
52
- mappings: CodeMapping[];
53
- embeddedCodes: VirtualCode[];
54
- }
55
-
56
- /** Create a simple IScriptSnapshot from a string. */
57
- function create_snapshot(text: string): IScriptSnapshot {
58
- return {
59
- getText: (start, end) => text.slice(start, end),
60
- getLength: () => text.length,
61
- getChangeRange: () => undefined,
62
- };
63
- }
64
-
65
- /** Build a minimal VirtualCode with no TS features (used as fallback on error). */
66
- function create_fallback_virtual_code(source: string): PfmVirtualCode {
67
- return {
68
- id: "root",
69
- languageId: PFM_LANGUAGE_ID,
70
- snapshot: create_snapshot(source),
71
- mappings: [{
72
- sourceOffsets: [0],
73
- generatedOffsets: [0],
74
- lengths: [source.length],
75
- data: { structure: true },
76
- }],
77
- embeddedCodes: [],
78
- };
79
- }
80
-
81
- /**
82
- * Run the full PFM to TypeScript pipeline and produce VirtualCode.
83
- * On any error (parse failure, svelte2tsx crash), returns a fallback
84
- * VirtualCode with no TS features instead of crashing the server.
85
- */
86
- function create_virtual_code_from_source(
87
- source: string,
88
- script_id: string,
89
- ): PfmVirtualCode {
90
- let svelte;
91
- try {
92
- // Step 1: PFM to Svelte
93
- svelte = pfmToSvelte(source);
94
- } catch {
95
- return create_fallback_virtual_code(source);
96
- }
97
-
98
- let tsx;
99
- try {
100
- // Step 2: Svelte to TypeScript via svelte2tsx
101
- tsx = svelte_2_tsx(svelte.code, {
102
- filename: script_id.replace(PFM_EXTENSION, ".svelte"),
103
- isTsFile: false,
104
- mode: "ts",
105
- });
106
- } catch {
107
- return create_fallback_virtual_code(source);
108
- }
109
-
110
- // Step 3: Convert svelte2tsx's v3 source map to Volar format + inject shims
111
- const v3_map = tsx.map.toJSON ? tsx.map.toJSON() : tsx.map;
112
- const raw_svelte_to_ts = v3ToVolarMappings(v3_map as any, tsx.code, svelte.code);
113
- const { code: ts_code, mappings: svelte_to_ts_mappings } = inject_shims(
114
- tsx.code,
115
- raw_svelte_to_ts,
116
- );
117
-
118
- // Step 4: Filter mappings for composition.
119
- // - Exclude "node" role (broadest spans cause duplicate hover results)
120
- // - Exclude zero-length source mappings
121
- // - Upgrade capabilities to full, let svelte2tsx's B-side gate features
122
- const ALL_CAPS: CodeInformation = {
123
- verification: true,
124
- completion: true,
125
- semantic: true,
126
- navigation: true,
127
- structure: true,
128
- };
129
- const filtered_mappings = svelte.mappings
130
- .filter((m) => (m.data as any).role !== "node" && m.lengths[0] > 0)
131
- .map((m) => ({ ...m, data: ALL_CAPS }));
132
-
133
- // Step 5: Compose PFM to Svelte + Svelte to TS = PFM to TS
134
- // Use B's capabilities but disable format (overlapping ranges crash the formatter).
135
- const pfm_to_ts = composeMappings(
136
- filtered_mappings as any,
137
- svelte_to_ts_mappings,
138
- (_a: CodeInformation, b: CodeInformation): CodeInformation => ({
139
- ...b,
140
- format: false,
141
- }),
142
- );
143
-
144
- // Step 5b: Merge single-char non-identity mappings into adjacent
145
- // neighbors. svelte2tsx splits attribute names at the first character
146
- // (e.g. "v" to '"' + "alue=" to 'alue"') and maps syntax chars to filler
147
- // spaces. These 1-char mappings cause two problems via Volar's
148
- // inclusive-end (<=) translateOffset:
149
- // 1. Diagnostic highlights bleed through whitespace (char to space anchors)
150
- // 2. Duplicate hover at attribute-name boundaries (v/alue overlap)
151
- // Merging them into the next mapping eliminates the boundary overlap
152
- // while preserving hover on the first character.
153
- pfm_to_ts.sort(
154
- (a, b) => a.sourceOffsets[0] - b.sourceOffsets[0],
155
- );
156
- for (let i = pfm_to_ts.length - 2; i >= 0; i--) {
157
- const m = pfm_to_ts[i];
158
- if (m.lengths[0] !== 1) continue;
159
- const gen_len = m.generatedLengths ? m.generatedLengths[0] : 1;
160
- if (gen_len !== 1) continue;
161
- const src_ch = source.charCodeAt(m.sourceOffsets[0]);
162
- const gen_ch = ts_code.charCodeAt(m.generatedOffsets[0]);
163
- if (src_ch === gen_ch) continue; // identity, leave as-is
164
-
165
- const next = pfm_to_ts[i + 1];
166
- const next_gen_len = next.generatedLengths ? next.generatedLengths[0] : next.lengths[0];
167
-
168
- // Merge into next if source-adjacent and generated gap <= 1
169
- if (m.sourceOffsets[0] + 1 === next.sourceOffsets[0] &&
170
- next.generatedOffsets[0] - (m.generatedOffsets[0] + 1) <= 1) {
171
- const new_gen_start = m.generatedOffsets[0];
172
- const new_gen_end = next.generatedOffsets[0] + next_gen_len;
173
- next.sourceOffsets[0] = m.sourceOffsets[0];
174
- next.lengths[0] += 1;
175
- next.generatedOffsets[0] = new_gen_start;
176
- const new_gen_len = new_gen_end - new_gen_start;
177
- next.generatedLengths = new_gen_len !== next.lengths[0] ? [new_gen_len] : undefined;
178
- pfm_to_ts.splice(i, 1);
179
- }
180
- }
181
-
182
- // Step 6: Shrink non-identity trailing boundaries at adjacency points.
183
- // Volar's translateOffset uses inclusive end (<=) so adjacent mappings
184
- // share boundary offsets. When the last source char differs from the
185
- // last generated char (e.g. "}" becomes ","), the previous mapping wrongly
186
- // claims the next token's start, causing diagnostic highlights to
187
- // bleed through inter-attribute whitespace. We only shrink when the
188
- // next mapping starts at exactly this mapping's generated end, to
189
- // avoid dropping diagnostics at the final mapping.
190
- const by_gen_offset = pfm_to_ts.slice().sort(
191
- (a, b) => a.generatedOffsets[0] - b.generatedOffsets[0],
192
- );
193
- for (let i = 0; i < by_gen_offset.length - 1; i++) {
194
- const m = by_gen_offset[i];
195
- const next = by_gen_offset[i + 1];
196
- const src_len = m.lengths[0];
197
- const gen_len = m.generatedLengths ? m.generatedLengths[0] : src_len;
198
- if (gen_len <= 1) continue;
199
- const gen_end = m.generatedOffsets[0] + gen_len;
200
- if (gen_end !== next.generatedOffsets[0]) continue;
201
- const last_src = source.charCodeAt(m.sourceOffsets[0] + src_len - 1);
202
- const last_gen = ts_code.charCodeAt(m.generatedOffsets[0] + gen_len - 1);
203
- if (last_src !== last_gen) {
204
- m.generatedLengths = [gen_len - 1];
205
- }
206
- }
207
-
208
- // Step 7: Deduplicate composed mappings that share the same source range.
209
- // svelte2tsx maps identifiers like `Test` to multiple TS positions
210
- // (import, type alias, constructor). Keeping only the first (lowest
211
- // generated offset) prevents Volar from combining all their hover
212
- // results into one noisy tooltip.
213
- {
214
- const seen = new Set<string>();
215
- let write = 0;
216
- for (let read = 0; read < pfm_to_ts.length; read++) {
217
- const m = pfm_to_ts[read];
218
- const key = m.sourceOffsets[0] + ":" + m.lengths[0];
219
- if (seen.has(key)) continue;
220
- seen.add(key);
221
- pfm_to_ts[write++] = m;
222
- }
223
- pfm_to_ts.length = write;
224
- }
225
-
226
- // Build the TypeScript embedded VirtualCode
227
- const ts_virtual_code: VirtualCode = {
228
- id: "ts",
229
- languageId: "typescript",
230
- snapshot: create_snapshot(ts_code),
231
- mappings: pfm_to_ts as CodeMapping[],
232
- embeddedCodes: [],
233
- };
234
-
235
- // Build CSS embedded VirtualCodes from <style> blocks
236
- const embedded_codes: VirtualCode[] = [ts_virtual_code];
237
- const all_caps = {
238
- verification: true,
239
- completion: true,
240
- semantic: true,
241
- navigation: true,
242
- structure: true,
243
- format: true,
244
- };
245
-
246
- for (let i = 0; i < svelte.styleBlocks.length; i++) {
247
- const sb = svelte.styleBlocks[i];
248
- const css_text = source.slice(sb.sourceStart, sb.sourceEnd);
249
- embedded_codes.push({
250
- id: "style_" + i,
251
- languageId: "css",
252
- snapshot: create_snapshot(css_text),
253
- mappings: [{
254
- sourceOffsets: [sb.sourceStart],
255
- generatedOffsets: [0],
256
- lengths: [css_text.length],
257
- data: all_caps,
258
- }],
259
- embeddedCodes: [],
260
- });
261
- }
262
-
263
- // Build markdown VirtualCode: PFM source with excluded regions
264
- // (frontmatter, script, style, imports) blanked out so the markdown
265
- // service sees clean markdown without setext-heading false positives.
266
- let md_source = source;
267
- for (const region of svelte.excludedRegions) {
268
- // Replace excluded bytes with spaces, preserving newlines for line alignment
269
- const chunk = source.slice(region.start, region.end);
270
- const blanked = chunk.replace(/[^\n]/g, " ");
271
- md_source = md_source.slice(0, region.start) + blanked + md_source.slice(region.end);
272
- }
273
-
274
- embedded_codes.push({
275
- id: "md",
276
- languageId: "markdown",
277
- snapshot: create_snapshot(md_source),
278
- mappings: [{
279
- sourceOffsets: [0],
280
- generatedOffsets: [0],
281
- lengths: [source.length],
282
- data: {
283
- structure: true,
284
- navigation: true,
285
- },
286
- }],
287
- embeddedCodes: [],
288
- });
289
-
290
- return {
291
- id: "root",
292
- languageId: PFM_LANGUAGE_ID,
293
- snapshot: create_snapshot(source),
294
- mappings: [{
295
- sourceOffsets: [0],
296
- generatedOffsets: [0],
297
- lengths: [source.length],
298
- data: { structure: true },
299
- }],
300
- embeddedCodes: embedded_codes,
301
- };
302
- }
303
-
304
- /** Simple string hash for content-based caching. */
305
- function hash_string(s: string): number {
306
- let h = 0;
307
- for (let i = 0; i < s.length; i++) {
308
- h = ((h << 5) - h + s.charCodeAt(i)) | 0;
309
- }
310
- return h;
311
- }
312
-
313
- /**
314
- * Create a PFM LanguagePlugin for Volar.
315
- *
316
- * Usage:
317
- * const plugin = createPfmLanguagePlugin();
318
- * // Pass to @volar/language-server or @volar/kit
319
- */
320
- export function create_pfm_language_plugin(): LanguagePlugin<string, PfmVirtualCode> {
321
- // Per-file cache: skip full pipeline if content hash hasn't changed
322
- const cache = new Map<string, { hash: number; result: PfmVirtualCode }>();
323
-
324
- return {
325
- getLanguageId(scriptId: string): string | undefined {
326
- if (scriptId.endsWith(PFM_EXTENSION)) {
327
- return PFM_LANGUAGE_ID;
328
- }
329
- return undefined;
330
- },
331
-
332
- createVirtualCode(
333
- scriptId: string,
334
- languageId: string,
335
- snapshot: IScriptSnapshot,
336
- _ctx: CodegenContext<string>,
337
- ): PfmVirtualCode | undefined {
338
- if (languageId !== PFM_LANGUAGE_ID) return undefined;
339
-
340
- const source = snapshot.getText(0, snapshot.getLength());
341
- const hash = hash_string(source);
342
- const cached = cache.get(scriptId);
343
- if (cached && cached.hash === hash) {
344
- return cached.result;
345
- }
346
-
347
- const result = create_virtual_code_from_source(source, scriptId);
348
- cache.set(scriptId, { hash, result });
349
- return result;
350
- },
351
-
352
- updateVirtualCode(
353
- scriptId: string,
354
- _virtualCode: PfmVirtualCode,
355
- newSnapshot: IScriptSnapshot,
356
- _ctx: CodegenContext<string>,
357
- ): PfmVirtualCode | undefined {
358
- const source = newSnapshot.getText(0, newSnapshot.getLength());
359
- const hash = hash_string(source);
360
- const cached = cache.get(scriptId);
361
- if (cached && cached.hash === hash) {
362
- return cached.result;
363
- }
364
-
365
- const result = create_virtual_code_from_source(source, scriptId);
366
- cache.set(scriptId, { hash, result });
367
- return result;
368
- },
369
-
370
- disposeVirtualCode(scriptId: string) {
371
- cache.delete(scriptId);
372
- },
373
-
374
- typescript: {
375
- extraFileExtensions: [
376
- {
377
- extension: "pfm",
378
- isMixedContent: true,
379
- scriptKind: 7 as any, // ts.ScriptKind.Deferred
380
- },
381
- ],
382
- getServiceScript(root: VirtualCode) {
383
- // Return the embedded TS code as the service script:
384
- // this tells TypeScript "when resolving this .pfm file
385
- // as a module, use this TS code for its exports"
386
- const ts_code = root.embeddedCodes?.find(
387
- (c) => c.languageId === "typescript",
388
- );
389
- if (ts_code) {
390
- return {
391
- code: ts_code,
392
- extension: ".ts" as any,
393
- scriptKind: 3 as any, // ts.ScriptKind.TS
394
- };
395
- }
396
- return undefined;
397
- },
398
- getExtraServiceScripts(_fileName: string, _root: VirtualCode) {
399
- // The main TS code is already returned by getServiceScript.
400
- // No extra scripts needed, returning it again causes duplicates.
401
- return [];
402
- },
403
- },
404
- };
405
- }