nonara / ts-patch

Augment the TypeScript compiler to support extended functionality
MIT License
760 stars 26 forks source link

Using the same node module to as a ts language server plugin and a ts-patch program transformer plugin #169

Open ChiriVulpes opened 2 months ago

ChiriVulpes commented 2 months ago

Apologies if I've missed documentation for this, I did look but didn't find anything, and there are vanishingly few examples of language servers combined with ts-patch.

This is what I want to be able to do:

"plugins": [
    { "name": "my-plugin-name" },
    { "transform": "my-plugin-name", "transformProgram": true },
]

I noticed that ts-patch tries to load commonjs plugins that follow the format export default function, and the typescript language server plugins try to load commonjs plugins that follow the format export = function. As such, I tried this as the entry point file:

interface EntryPoint {
    (modules: { typescript: typeof ts }): { create (info: ts.server.PluginCreateInfo): LanguageServicePlugin };
    default (program: ts.Program, host: ts.CompilerHost | undefined, config: PluginConfig, extras: ProgramTransformerExtras): ts.Program;
}

const createLanguageServicePlugin = (modules: { typescript: typeof ts }) => ({
    create: (info: ts.server.PluginCreateInfo) => new LanguageServicePlugin(modules.typescript as any, info),
}) as Partial<EntryPoint>;

createLanguageServicePlugin.default = transformProgram;

export = createLanguageServicePlugin;

But it doesn't work because ts-patch's plugin.ts wraps all commonjs export functions in { default: } via

const factoryModule = (typeof commonjsModule === 'function') ? { default: commonjsModule } : commonjsModule;

However, it works fine if I manually patch that line on my end to instead be

const factoryModule = (typeof commonjsModule === "function" && !commonjsModule.default) ? { default: commonjsModule } : commonjsModule;

Could this be changed, or if you don't want this maybe could there be a path option for a custom entry point in PluginPackageConfig?