{"id":16870954,"url":"https://github.com/ryancavanaugh/sample-ts-plugin","last_synced_at":"2025-03-17T06:31:19.577Z","repository":{"id":73094711,"uuid":"81881019","full_name":"RyanCavanaugh/sample-ts-plugin","owner":"RyanCavanaugh","description":"Sample TypeScript Language Service Plugin","archived":false,"fork":false,"pushed_at":"2017-04-27T17:16:43.000Z","size":10,"stargazers_count":68,"open_issues_count":1,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-14T20:24:29.650Z","etag":null,"topics":["extensibility","plugin","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RyanCavanaugh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-02-13T23:02:18.000Z","updated_at":"2023-07-10T12:04:35.000Z","dependencies_parsed_at":"2023-03-11T14:25:12.812Z","dependency_job_id":null,"html_url":"https://github.com/RyanCavanaugh/sample-ts-plugin","commit_stats":{"total_commits":5,"total_committers":2,"mean_commits":2.5,"dds":"0.19999999999999996","last_synced_commit":"b06370ac6bc868e097887de5496a609acbfd5f3f"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RyanCavanaugh%2Fsample-ts-plugin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RyanCavanaugh%2Fsample-ts-plugin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RyanCavanaugh%2Fsample-ts-plugin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RyanCavanaugh%2Fsample-ts-plugin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RyanCavanaugh","download_url":"https://codeload.github.com/RyanCavanaugh/sample-ts-plugin/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243846978,"owners_count":20357297,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["extensibility","plugin","typescript"],"created_at":"2024-10-13T15:05:51.461Z","updated_at":"2025-03-17T06:31:18.776Z","avatar_url":"https://github.com/RyanCavanaugh.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Writing a TypeScript Language Service Plugin\n\nIn TypeScript 2.2 and later, developers can enable *language service plugins* to augment the TypeScript code editing experience. The purpose of this guide is to help you write your own plugin.\n\n## What's a Language Service Plugin?\n\nTypeScript Language Service Plugins (\"plugins\") are for changing the *editing experience* only. The core TypeScript language remains the same. Plugins can't add new language features such as new syntax or different typechecking behavior, and plugins aren't loaded during normal commandline typechecking or emitting.\n\nInstead, plugins are for augmenting the editing experience. Some examples of things plugins might do:\n * Provide errors from a linter inline in the editor\n * Filter the completion list to remove certain properties from `window`\n * Redirect \"Go to definition\" to go to a different location for certain identifiers\n * Enable new errors or completions in string literals for a custom templating language\n\nExamples of things language plugins cannot do:\n * Add new custom syntax to TypeScript\n * Change how the compiler emits JavaScript\n * Customize the type system to change what is or isn't an error when running `tsc`\n\nDevelopers using the plugin will `npm install --save-dev your_plugin_name` and edit their `tsconfig.json` file to enable your plugin.\n\n## Overview: Writing a Simple Plugin\n\nLet's write a simple plugin. Our plugin will remove a user-configurable list of property names from the completion list. You might use this sort of plugin on your team to help remind you which APIs are 'banned' (for example, using the `caller` property of `function` is discouraged).\n\n### Setup and Initialization\n\nWhen your plugin is loaded, it's first initialized as a factory function with its first parameter set to `{typescript: ts}`. It's important to use *this* value, rather than the imported `ts` module, because any version of TypeScript might be loaded by tsserver. If you use any other object, you'll run into compatibility problems later because enum values may change between versions.\n\nHere's the minimal code that handles this injected `ts` value:\n```ts\nimport * as ts_module from \"../node_modules/typescript/lib/tsserverlibrary\";\n\nfunction init(modules: {typescript: typeof ts_module}) {\n    const ts = modules.typescript;\n    /* More to come here */\n}\n\nexport = init;\n```\n\n### Decorator Creation\n\nTypeScript Language Service Plugins use the [Decorator Pattern](https://en.wikipedia.org/wiki/Decorator_pattern) to \"wrap\" the main TypeScript Language Service. When your plugin is initialized, it will be given a Language Service instance to wrap, and should return a new decorator wrapping this instance. This is exposed through the `create` function returned from your outer factory function.\n\nLet's fill in some more code to properly set up a decorator:\n```ts\nfunction init(modules: {typescript: typeof ts_module}) {\n    const ts = modules.typescript;\n\n    function create(info: ts.server.PluginCreateInfo) {\n        // Set up decorator\n        const proxy = Object.create(null) as ts.LanguageService;\n        const oldLS = info.languageService;\n        for (const k in oldLS) {\n            (\u003cany\u003eproxy)[k] = function () {\n                return oldLS[k].apply(oldLS, arguments);\n            }\n        }\n        return proxy;\n    }\n\n    return { create };\n}\n```\n\nThis sets up a \"pass-through\" decorator that invokes the underlying language service for all methods.\n\n### Enabling a plugin\n\nTo enable this plugin, users will add an entry to the `plugins` list in their `tsconfig.json` file:\n```json\n{\n    \"compilerOptions\": {\n        \"noImplicitAny\": true,\n        \"plugins\": [{ \"name\": \"sample-ts-plugin\" }]\n    }\n}\n```\n\n### Customizing Behavior\n\nLet's modify the above pass-through plugin to add some new behavior.\n\nWe'll change the `getCompletionsAtPosition` function to remove certain entries named `caller` from the completion list:\n```ts\n// Remove specified entries from completion list\nproxy.getCompletionsAtPosition = (fileName, position) =\u003e {\n    const prior = info.languageService.getCompletionsAtPosition(fileName, position);\n    prior.entries = prior.entries.filter(e =\u003e e.name !== 'caller');\n    return prior;\n};\n```\n\n## Handling User Configuration\n\nUsers can customize your plugin behavior by providing additional data in their `tsconfig.json` file. Your plugin is given its enabling entry from the `tsconfig.json` file in the `info.config` property.\n\nLet's allow the user to customize the list of names to remove from the completion list:\n```ts\nfunction create(info: ts.server.PluginCreateInfo) {\n    // Get a list of things to remove from the completion list from the config object.\n    // If nothing was specified, we'll just remove 'caller'\n    const whatToRemove: string[] = info.config.remove || ['caller'];\n    \n    // ... (set up decorator here) ...\n\n    // Remove specified entries from completion list\n    proxy.getCompletionsAtPosition = (fileName, position) =\u003e {\n        const prior = info.languageService.getCompletionsAtPosition(fileName, position);\n        prior.entries = prior.entries.filter(e =\u003e whatToRemove.indexOf(e.name) \u003c 0);\n        return prior;\n    };\n```\n\nThe new `tsconfig.json` file might look like this:\n```json\n{\n    \"compilerOptions\": {\n        \"noImplicitAny\": true,\n        \"plugins\": [{\n            \"name\": \"sample-ts-plugin\",\n            \"remove\": [\"caller\", \"callee\", \"getDay\"]\n        }]\n    }\n}\n```\n\n## Debugging\n\nYou'll probably want to add some logging to your plugin to help you during development. The TypeScript Server Log allows plugins to write to a common log file.\n\n### Setting up TypeScript Server Logging\n\nYour plugin code runs inside the TypeScript Server process. Its logging behavior can be enabled by setting the `TSS_LOG` environment variable. To log to a file, set `TSS_LOG` to:\n```\n-logToFile true -file C:\\SomeFolder\\MyTypeScriptLog.txt -level verbose\n```\nEnsure that the containing directory (`C:\\SomeFolder` in this example) exists and is writable.\n\n### Logging from your plugin\n\nYou can write to this log by calling into the TypeScript project's logging service:\n```ts\n    function create(info: ts.server.PluginCreateInfo) {\n        info.project.projectService.logger.info(\"I'm getting set up now! Check the log for this message.\");\n```\n\n## Putting it all together\n\n```ts\nimport * as ts_module from \"../node_modules/typescript/lib/tsserverlibrary\";\n\nfunction init(modules: {typescript: typeof ts_module}) {\n    const ts = modules.typescript;\n\n    function create(info: ts.server.PluginCreateInfo) {\n        // Get a list of things to remove from the completion list from the config object.\n        // If nothing was specified, we'll just remove 'caller'\n        const whatToRemove: string[] = info.config.remove || ['caller'];\n\n        // Diagnostic logging\n        info.project.projectService.logger.info(\"I'm getting set up now! Check the log for this message.\");\n\n        // Set up decorator\n   \t    const proxy = Object.create(null) as ts.LanguageService;\n\t    const oldLS = info.languageService;\n\t    for (const k in oldLS) {\n\t        (\u003cany\u003eproxy)[k] = function () {\n\t            return oldLS[k].apply(oldLS, arguments);\n\t        }\n\t    }\n\n        // Remove specified entries from completion list\n        proxy.getCompletionsAtPosition = (fileName, position) =\u003e {\n            const prior = info.languageService.getCompletionsAtPosition(fileName, position);\n            const oldLength = prior.entries.length;\n            prior.entries = prior.entries.filter(e =\u003e whatToRemove.indexOf(e.name) \u003c 0);\n\n            // Sample logging for diagnostic purposes\n            if (oldLength !== prior.entries.length) {\n                info.project.projectService.logger.info(`Removed ${oldLength - prior.entries.length} entries from the completion list`);\n            }\n\n            return prior;\n        };\n\n        return proxy;\n    }\n\n    return { create };\n}\n\nexport = init;\n```\n\n## Testing Locally\n\nLocal testing of your plugin is similar to testing other node modules. To set up a sample project where you can easily test plugin changes:\n\n * Run `npm link` from your plugin directory\n * In your sample project, run `npm link your_plugin_name`\n * Add an entry to the `plugins` field of the `tsconfig.json`\n * Rebuild your plugin and restart your editor to pick up code changes\n\n## Real-world Plugins\n\nSome other TypeScript Language Service Plugin implementations you can look at for reference:\n* https://github.com/angular/angular/blob/master/packages/language-service/src/ts_plugin.ts\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fryancavanaugh%2Fsample-ts-plugin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fryancavanaugh%2Fsample-ts-plugin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fryancavanaugh%2Fsample-ts-plugin/lists"}