Title: A minimal custom transformer plugin proposal · Issue #54276 · microsoft/TypeScript · GitHub
Open Graph Title: A minimal custom transformer plugin proposal · Issue #54276 · microsoft/TypeScript
X Title: A minimal custom transformer plugin proposal · Issue #54276 · microsoft/TypeScript
Description: In the TypeScript compiler, we have the concept of a "transformer". A transformer is a function which "transforms" one AST to another. TypeScript ships many such transforms, including all of the various transformation steps needed to dow...
Open Graph Description: In the TypeScript compiler, we have the concept of a "transformer". A transformer is a function which "transforms" one AST to another. TypeScript ships many such transforms, including all of the va...
X Description: In the TypeScript compiler, we have the concept of a "transformer". A transformer is a function which "transforms" one AST to another. TypeScript ships many such transforms, inc...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/54276
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"A minimal custom transformer plugin proposal","articleBody":"In the TypeScript compiler, we have the concept of a \"transformer\". A transformer is a function which \"transforms\" one AST to another. TypeScript ships many such transforms, including all of the various transformation steps needed to downlevel newer syntax to older syntax, to convert from `import`/`export` to `require`/`module.exports`, and so on. Even the declaration emitter is a transformer, stripping away function bodies, filing in types, etc.\r\n\r\nSince TypeScript 2.3, TypeScript has had the following API:\r\n\r\n\u003c!-- dprint-ignore-start -->\r\n\r\n```ts\r\ninterface Program {\r\n emit(\r\n targetSourceFile?: SourceFile,\r\n writeFile?: WriteFileCallback,\r\n cancellationToken?: CancellationToken,\r\n emitOnlyDtsFiles?: boolean,\r\n customTransformers?: CustomTransformers, // \u003c--- 👀\r\n ): EmitResult;\r\n}\r\n\r\ninterface CustomTransformers {\r\n before?: (TransformerFactory\u003cSourceFile> | CustomTransformerFactory)[];\r\n after?: (TransformerFactory\u003cSourceFile> | CustomTransformerFactory)[];\r\n afterDeclarations?: (TransformerFactory\u003cBundle | SourceFile> | CustomTransformerFactory)[];\r\n}\r\n```\r\n\r\n\u003c!-- dprint-ignore-end -->\r\n\r\nThis API allows users to provide a set of \"custom transformers\" at `emit` time. These transformers run alongside TypeScript's own transformers, either before or after, depending on where they are placed in `CustomTransformers`.\r\n\r\nHowever, while this API exists and does work, a major gotcha is that custom transformers can only be provided to the _API_. There is no way to use custom transformers if you want to use `tsc` alone.\r\n\r\nThis has been a long-standing issue; [#14419](https://github.com/microsoft/TypeScript/issues/14419) is the fourth most upvoted issue on the repo.\r\n\r\n# What do people use custom transformers for?\r\n\r\nThis list can go on and on, but transformers are commonly used these days for:\r\n\r\n- Generating serialization / deserialization / runtime type checks\r\n - `typia`,`ts-runtime-checks`, which top the [benchmark charts](https://moltar.github.io/typescript-runtime-type-benchmarks/), but there are many more\r\n- Powering internationalization\r\n - `formatjs`\r\n- Generating database code\r\n - `ts-graphql-plugin`\r\n- Transforming paths (please don't do this one, though 😅)\r\n\r\nI also know of many ideas which _want_ to be implemented via plugins, but are not willing to do so without official support, including other runtime type checks, tracing code, and so on.\r\n\r\n# How do users currently use custom transformers?\r\n\r\nGiven the current constraints of custom transformers, there are two ways that downstream users have been able to use them:\r\n\r\n1. Build TypeScript code via the API, either directly or by using some system which uses the API.\r\n - `webpack`, `rollup`'s TS plugins, `nx`, all provide configuration which allows users to specify a set of custom transformers.\r\n1. Patch TypeScript.\r\n - `ttypescript`, `ts-patch` wholly replace TypeScript in a user's workflow.\r\n\r\nThe first one is obviously fine. The latter, eek!\r\n\r\n# What changed?\r\n\r\nIn TypeScript 5.0, we shipped the biggest architectural / packaging change in TypeScript's history; conversion of the entire project to modules, including the bundling of our code. The relevant side-effects are twofold:\r\n\r\n1. The structure of `tsc.js` (and other outputs) changed massively. This broke anyone who was patching the contents of the TypeScript package.\r\n1. The API is no longer runtime patchable; we use `esbuild` to bundle our code and the objects it creates are not \"configurable\", correctly emulating how \"real\" ES modules would behave. Any runtime patches were already extremely fragile, only functioning due to the structure of our old `namespace` emit.\r\n\r\nIn response to this, I did [an analysis](https://gist.github.com/jakebailey/3e73c7aab4da2044a95121467aa3b4e9) of as many TS \"patchers\" as I could find, and found that there are actually very few reasons to patch TypeScript at all:\r\n\r\n- `ttypescript`/`ts-patch`, which seem to be almost exclusively used to enable the use of custom transformers.\r\n- Language service plugins, mainly injecting their own module resolution and custom source file types (`vue`/`volar`, `css`, etc).\r\n- Build systems like `heft`.\r\n- Yarn PnP.\r\n- Those who want to tree shake out our parser (`prettier`).\r\n\r\nFor 5.0, I was able to fix many of these projects (or at least guide / warn maintainers ahead of time), but many of these patchers have no viable alternative.\r\n\r\nWe have been seriously considering ways that we can approach the problems that remain in hopes that we can eliminate the need for people to patch TypeScript. This includes (no promises):\r\n\r\n- Custom transformers.\r\n- Custom module resolution.\r\n- A future API that actually allows a consumer to tree shake out _just_ a parser (or similar).\r\n\r\nThis issue intends to address the first bullet.\r\n\r\n# A conservative, targeted proposal\r\n\r\nIn short, my proposal is to add to TypeScript the ability to define \"custom transformer plugins\". This new functionality is _targeted and minimal_. Its only intent is to satisfy those who just want to be able to add custom transformers.\r\n\r\nMany details still have yet to be expanded on, but in short:\r\n\r\n- These plugins are placed into the `plugins` array of `compilerOptions`, with a discriminator like `\"type\": \"transformer\"`.\r\n - This is the approach taken by `ttypescript`/`ts-patch`, and offers up a future base for additional `tsc` plugins (e.g. file watching plugins, module resolution plugins).\r\n - The choice in discriminator (`\"type\": \"transformer\"`, for now) is intended to avoid conflicting with existing plugins defined by `ttypescript` or `ts-patch`.\r\n- Plugins would take a form similar to language service plugin, receiving the `ts` object, returning a factory that can be used to create a `CustomTransformers` object. The factory would receive the `Program`, which is required for any type-using plugins.\r\n - The `ts` object must be a part of the API for similar reasons to the language service plugins; the APIs available within the core compiler are very, very limited, and the bundle is _not_ the same as `typescript.js`.\r\n - The plugin object entry is passed to the plugin for extra configuration, like LS plugins.\r\n- A new `tsclibrary.d.ts` file is added, describing the limited API within `tsc`. This is similar to `tsserverlibrary.d.ts`.\r\n- When invoking `tsc`, you must pass `--allowPlugins` to opt into executing plugins. When using the API or tsserver, plugins are enabled by default.\r\n - No sandbox is present otherwise. If you currently use a patching-based method to use plugins, you're already taking matters into your own hand. If you currently use `webpack` or `rollup`, your config files are executable anyway.\r\n - `--allowPlugins` is also a part of the watch plugin PR.\r\n- If multiple plugins are used, their returned `CustomTransformers` are merged.\r\n\r\nThere are almost assuredly other things that people want to be able to do with custom transformers or other plugins, however, I believe that we can serve the vast majority of those who want custom transformers with this API, and I do not want to let perfect be the enemy of the good.\r\n\r\nIn the future, we can expand `plugins` to do more, allowing the customization of other aspects of TypeScript, or simply add on to what custom transformer plugins can do. [Prior research](https://gist.github.com/rbuckton/090b2b5d27079dec5639e79c072a289e) has shown that there are more interested parties, which I believe that we can eventually support.\r\n\r\n# An example\r\n\r\nWith the above proposal, a `tsconfig.json` would look like this:\r\n\r\n```jsonc\r\n{\r\n \"compilerOptions\": {\r\n \"plugins\": [\r\n { \"type\": \"transformer\", \"path\": \"@jakebailey/cool-transformer\" }\r\n ]\r\n }\r\n}\r\n```\r\n\r\nThe transformer would look something like:\r\n\r\n```ts\r\nimport type * as ts from \"typescript/tsclibrary\";\r\n\r\nconst factory: CustomTransformersModuleFactory = ({ typescript }) => {\r\n return {\r\n create: ({ program }) => {\r\n return {\r\n before: [(context) => (file) => {/* ... */}],\r\n };\r\n },\r\n };\r\n};\r\n\r\nexport = factory;\r\n```\r\n\r\nOf course, the details may change.\r\n\r\n# Unsolved problems\r\n\r\n- It's very unfortunate to have to define _yet another_ random `d.ts` API used for one thing.\r\n - Can we do better?\r\n - What if the executables were ESM?\r\n- Like LS plugins, tsc plugins would need to be CJS.\r\n - Can we instead make use of `import`?\r\n - How do we do `async`? (This may already be \"solved\" in a prior WIP for plugins)\r\n- Should we do any sort of performance metric counting for plugins?\r\n - Like LS plugins, can we just say \"no warranty\" when plugins are involved?\r\n- How much of a problem is it going to be to need to use the `typescript` namespace passed into the plugin?\r\n - What happens to existing transformers which mistakenly import `typescript.js`'s API directly, even though that may not have always worked?\r\n - Will plugins unknowingly use the `typescript.js` API and rely on it, assuming users won't use `tsc`?\r\n - Should we try and attempt converting our binaries/libraries to ESM first?\r\n- Is the proposed API too factory-y?\r\n- Should we even do this?\r\n\r\n# Please give feedback!\r\n\r\nIf you are currently using transformers, creating transformers, or otherwise, I would appreciate your feedback.","author":{"url":"https://github.com/jakebailey","@type":"Person","name":"jakebailey"},"datePublished":"2023-05-16T21:34:04Z","url":"https://github.com/microsoft/TypeScript/issues/54276"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:eea53012-d105-7533-a6e5-78caa15985b5 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9BA2:1C6C3E:C99F43:10AF501:6B00F591 |
| html-safe-nonce | ac0e3f37480d92ab0ff030476069f269193e664a0c2098551a5a233042d032a4 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QkEyOjFDNkMzRTpDOTlGNDM6MTBBRjUwMTo2QjAwRjU5MSIsInZpc2l0b3JfaWQiOiIzNDE0NTgxNjY3MzUwNzcxMDg5IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | ad0ab4e8573e026ce098564fa55765d179de140705b6289e43d2419495bd6bc1 |
| hovercard-subject-tag | issue:1712767283 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/54276/issue_layout |
| twitter:image | https://opengraph.githubassets.com/3ef3a06ede3ad088fbab41edf7b74aaf6ee8daf1d82ebd6a35a595cc864360aa/microsoft/TypeScript/issues/54276 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/3ef3a06ede3ad088fbab41edf7b74aaf6ee8daf1d82ebd6a35a595cc864360aa/microsoft/TypeScript/issues/54276 |
| og:image:alt | In the TypeScript compiler, we have the concept of a "transformer". A transformer is a function which "transforms" one AST to another. TypeScript ships many such transforms, including all of the va... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | jakebailey |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4ef498cbabcbe3c50befc7a5b743e7072ee770b4daf0e15e54801180d1fa91fc |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9983dd5da06943f833c971dd5b6bc988e2858be5 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width