ttsc 0.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,2 @@
1
+ # Change Log
2
+
package/README.md ADDED
@@ -0,0 +1,395 @@
1
+ # ttsc
2
+
3
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/solar-religion/ttsc/blob/main/LICENSE)
4
+ [![npm version](https://img.shields.io/npm/v/ttsc.svg)](https://www.npmjs.com/package/ttsc)
5
+ [![Downloads](https://img.shields.io/npm/dm/ttsc.svg)](https://www.npmjs.com/package/ttsc)
6
+ This repository was created due to a perceived lack of management of ttypescript.
7
+
8
+ Also, we don't currently support ts-node and cache systems, as they weren't supported in the original, and we need time to figure out a way around that.
9
+
10
+ And it supports TS5.
11
+
12
+ [![npm version](https://badge.fury.io/js/ttypescript.svg)](https://badge.fury.io/js/ttypescript) [![Build Status](https://travis-ci.org/cevek/ttypescript.svg?branch=master)](https://travis-ci.org/cevek/ttypescript)
13
+
14
+ # ttypescript
15
+
16
+ ## Existing contributors
17
+
18
+ - @cevek
19
+ - @zerkalica
20
+ - @SalvatorePreviti
21
+ - @timocov
22
+ - @SlurpTheo
23
+ - @samchon
24
+ - @henriquehbr
25
+ - @JiangWeixian
26
+ - @mdmitry01
27
+ - @jirutka
28
+ - @alexgorbatchev
29
+ - @oscard0m
30
+ - @sveyret
31
+ - @Jack-Works
32
+ - @MicahZoltu
33
+ - @Igorbek
34
+ - @gfx
35
+ - @danielpza
36
+ - @mikeyhew
37
+ - @huafu
38
+ - @dsherret
39
+ - @SupernaviX
40
+ - @HitkoDev
41
+
42
+ ## What it is
43
+
44
+ Currently TypeScript doesn't support custom transformers in the tsconfig.json, but supports it programmatically.
45
+
46
+ And there is no way to compile your files using custom transformers using `tsc` command.
47
+
48
+ TTypescript (Transformer TypeScript) solves this problem by patching on the fly the compile module to use transformers from `tsconfig.json`.
49
+
50
+ <!---
51
+ TTypescript is a drop-in replacement for all typescript modules, located in ``` node_modules/typescript/lib ``` directory:
52
+
53
+ ```ts
54
+ import * as ts from 'ttypescript'
55
+ import * as tsServer from 'ttypescript/lib/tsserver'
56
+ import * as watchGuard from 'ttypescript/lib/watchGuard'
57
+ ```
58
+ --->
59
+
60
+ Instead of tsc and tsserver, use ttsc and ttsserver wrappers. This wrappers try to use locally installed typescript first.
61
+
62
+ No version lock-ins - typescript used as peer dependency.
63
+
64
+ ## How to install
65
+
66
+ ```
67
+ npm i ttypescript -D
68
+ ```
69
+
70
+ ttypescript uses your installed `typescript` in your `node_modules`
71
+
72
+ ## How to use
73
+
74
+ ### tsconfig.json
75
+
76
+ Set a transformer path to the `tsconfig.json` in `compilerOptions` section `plugin` array:
77
+
78
+ ```
79
+ {
80
+ "compilerOptions": {
81
+ "plugins": [
82
+ { "transform": "transformer-module" },
83
+ ]
84
+ }
85
+ }
86
+ ```
87
+
88
+ plugin entries described in `PluginConfig`:
89
+
90
+ ```ts
91
+ export interface PluginConfig {
92
+ /**
93
+ * Path to transformer or transformer module name
94
+ */
95
+ transform?: string;
96
+
97
+ /**
98
+ * The optional name of the exported transform plugin in the transform module.
99
+ */
100
+ import?: string;
101
+
102
+ /**
103
+ * Plugin entry point format type, default is program
104
+ */
105
+ type?: 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions';
106
+
107
+ /**
108
+ * Should transformer applied after all ones
109
+ */
110
+ after?: boolean;
111
+
112
+ /**
113
+ * Should transformer applied for d.ts files, supports from TS2.9
114
+ */
115
+ afterDeclarations?: boolean;
116
+ /**
117
+ * any other properties provided to the transformer as config argument
118
+ * */
119
+ [options: string]: any;
120
+ }
121
+ ```
122
+
123
+ You just need to add the `transform` block with optional `import`, `type`, `after`, `afterDeclarations` and plugin-related options.
124
+
125
+ `transform` can accept npm module or local file path (.ts or .js) related to `tsconfig.json`
126
+
127
+ ### PluginConfig.type
128
+
129
+ Because currently transformers can run only programmatically, most of them use factory wrapper with different signatures.
130
+ For the possible to work with any of them you can specify `type` in the plugin config.
131
+
132
+ By default will be used a `program` type.
133
+
134
+ <!---
135
+
136
+ Most of transformers exports ``` ts.TransformerFactory<ts.SourceFile> ```.
137
+ But better to export TransformerBasePlugin, described below. In most cases it's a plugin responsibility to when run a transformer.
138
+
139
+ ```ts
140
+ export interface TransformerBasePlugin {
141
+ before?: ts.TransformerFactory<ts.SourceFile>;
142
+ after?: ts.TransformerFactory<ts.SourceFile>;
143
+ afterDeclarations?: ts.TransformerFactory<ts.SourceFile>;
144
+ }
145
+
146
+ export type TransformerPlugin = TransformerBasePlugin | ts.TransformerFactory<ts.SourceFile>;
147
+ ```
148
+ --->
149
+
150
+ #### program
151
+
152
+ If the transformer has a factory signature using `program` as first argument:
153
+
154
+ ```ts
155
+ (program: ts.Program, config?: PluginConfig) => ts.TransformerFactory;
156
+ where;
157
+ ts.TransformerFactory = (context: ts.TransformationContext) => (sourceFile: ts.SourceFile) => ts.SourceFile;
158
+ ```
159
+
160
+ Plugin config entry: `{ "transform": "transformer-module" }`.
161
+
162
+ #### config
163
+
164
+ For the signature with transformer's config:
165
+
166
+ ```ts
167
+ (config: PluginConfig) => ts.TransformerFactory;
168
+ ```
169
+
170
+ Plugin config entry: `{ "transform": "transformer-module", type: "config" }`.
171
+
172
+ #### checker
173
+
174
+ For the signature with ts.TypeChecker:
175
+
176
+ ```ts
177
+ (checker: ts.TypeChecker, config?: PluginConfig) => ts.TransformerFactory;
178
+ ```
179
+
180
+ Plugin config entry: `{ "transform": "transformer-module", type: "checker" }`.
181
+
182
+ #### raw
183
+
184
+ For the signature without factory wrapper:
185
+
186
+ ```ts
187
+ ts.TransformerFactory;
188
+ ```
189
+
190
+ Plugin config entry: `{ "transform": "transformer-module", type: "raw" }`.
191
+
192
+ #### compilerOptions
193
+
194
+ ```ts
195
+ (compilerOpts: ts.CompilerOptions, config?: PluginConfig) => ts.TransformerFactory;
196
+ ```
197
+
198
+ Plugin config entry: `{ "transform": "transformer-module", type: "compilerOptions" }`.
199
+
200
+ ```json
201
+ {
202
+ "compilerOptions": {
203
+ "plugins": [
204
+ { "transform": "transformer-module", "someOption1": 123, "someOption2": 321 },
205
+ { "transform": "./transformers/my-transformer.ts" },
206
+ { "transform": "transformer-module", "after": true },
207
+ { "transform": "transformer-module", "afterDeclarations": true },
208
+ { "transform": "transformer-module", "type": "ls" }
209
+ ]
210
+ }
211
+ }
212
+ ```
213
+
214
+ ### Command line
215
+
216
+ Like usual `tsc`, all arguments work the same way.
217
+
218
+ ```
219
+ ttsc
220
+ ```
221
+
222
+ ### ts-node
223
+
224
+ ```
225
+ ts-node --compiler ttypescript index.ts
226
+ or
227
+ ts-node -C ttypescript index.ts
228
+ ```
229
+
230
+ ### Parcel
231
+
232
+ Just install a parcel plugin
233
+
234
+ ```
235
+ npm i parcel-plugin-ttypescript
236
+ ```
237
+
238
+ ### Webpack
239
+
240
+ ```js
241
+ {
242
+ test: /\.(ts|tsx)$/,
243
+ loader: require.resolve('awesome-typescript-loader'),
244
+ // or
245
+ loader: require.resolve('ts-loader'),
246
+ options: {
247
+ compiler: 'ttypescript'
248
+ }
249
+ }
250
+ ```
251
+
252
+ ### Rollup
253
+
254
+ ```js
255
+ // rollup.config.js
256
+ import ttypescript from 'ttypescript';
257
+ import tsPlugin from 'rollup-plugin-typescript2';
258
+
259
+ export default {
260
+ // ...
261
+ plugins: [
262
+ // ...
263
+ tsPlugin({
264
+ typescript: ttypescript,
265
+ }),
266
+ ],
267
+ };
268
+ ```
269
+
270
+ ### VS Code
271
+
272
+ If you want to compile your project with VS Code task runner you need to overwrite the config `typescript.tsdk` to path of the installed `ttypescript`:
273
+
274
+ ```
275
+ "typescript.tsdk": "/usr/local/lib/node_modules/ttypescript/lib",
276
+ or
277
+ "typescript.tsdk": "node_modules/ttypescript/lib",
278
+ ```
279
+
280
+ ### Jest, ts-jest
281
+
282
+ ```js
283
+ module.exports = {
284
+ // [...]
285
+ globals: {
286
+ 'ts-jest': {
287
+ compiler: 'ttypescript',
288
+ },
289
+ },
290
+ };
291
+ ```
292
+
293
+ or in `package.json`
294
+
295
+ ```json
296
+ {
297
+ "jest": {
298
+ "globals": {
299
+ "ts-jest": {
300
+ "compiler": "ttypescript"
301
+ }
302
+ }
303
+ }
304
+ }
305
+ ```
306
+
307
+ ## Transformers
308
+
309
+ You can use transformers written in ts or js
310
+
311
+ ```ts
312
+ // transformer1-module
313
+ import * as ts from 'typescript';
314
+ export default function (program: ts.Program, pluginOptions: {}) {
315
+ return (ctx: ts.TransformationContext) => {
316
+ return (sourceFile: ts.SourceFile) => {
317
+ function visitor(node: ts.Node): ts.Node {
318
+ // if (ts.isCallExpression(node)) {
319
+ // return ts.createLiteral('call');
320
+ // }
321
+ return ts.visitEachChild(node, visitor, ctx);
322
+ }
323
+ return ts.visitEachChild(sourceFile, visitor, ctx);
324
+ };
325
+ };
326
+ }
327
+ ```
328
+
329
+ Examples of transformers:
330
+
331
+ [`{ "transform": "ts-nameof", type: "raw"}`](https://github.com/dsherret/ts-nameof)
332
+
333
+ [`{ "transform": "ts-optchain/transform" }`](https://github.com/rimeto/ts-optchain)
334
+
335
+ [`{ "transform": "ts-transform-asset" }`](https://github.com/slune-org/ts-transform-asset)
336
+
337
+ [`{ "transform": "ts-transform-auto-require" }`](https://github.com/slune-org/ts-transform-auto-require)
338
+
339
+ [`{ "transform": "ts-transform-css-modules/dist/transform", type: "config" }`](https://github.com/longlho/ts-transform-css-modules)
340
+
341
+ [`{ "transform": "ts-transform-graphql-tag/dist/transformer" }`](https://github.com/firede/ts-transform-graphql-tag)
342
+
343
+ [`{ "transform": "ts-transform-img/dist/transform", type: "config" }`](https://github.com/longlho/ts-transform-img)
344
+
345
+ [`{ "transform": "ts-transform-react-intl/dist/transform", import: "transform", type: "config" }`](https://github.com/longlho/ts-transform-react-intl)
346
+
347
+ [`{ "transform": "ts-transformer-enumerate/transformer" }`](https://github.com/kimamula/ts-transformer-enumerate)
348
+
349
+ [`{ "transform": "ts-transformer-keys/transformer" }`](https://github.com/kimamula/ts-transformer-keys)
350
+
351
+ [`{ "transform": "ts-transformer-minify-privates" }`](https://github.com/timocov/ts-transformer-minify-privates)
352
+
353
+ [`{ "transform": "typescript-is/lib/transform-inline/transformer" }`](https://github.com/woutervh-/typescript-is)
354
+
355
+ [`{ "transform": "typescript-plugin-styled-components", type: "config" }`](https://github.com/Igorbek/typescript-plugin-styled-components#ttypescript-compiler)
356
+
357
+ [`{ "transform": "typescript-transform-jsx" }`](https://github.com/LeDDGroup/typescript-transform-jsx)
358
+
359
+ [`{ "transform": "typescript-transform-macros" }`](https://github.com/LeDDGroup/typescript-transform-macros)
360
+
361
+ [`{ "transform": "typescript-transform-paths" }`](https://github.com/LeDDGroup/typescript-transform-paths)
362
+
363
+ [`{ "transform": "@zerollup/ts-transform-paths" }`](https://github.com/zerkalica/zerollup/tree/master/packages/ts-transform-paths)
364
+
365
+ [`{ "transform": "@zoltu/typescript-transformer-append-js-extension" }`](https://github.com/Zoltu/typescript-transformer-append-js-extension)
366
+
367
+ [`{ "transform": "@magic-works/ttypescript-browser-like-import-transformer" }`](https://github.com/Jack-Works/ttypescript-browser-like-import-transformer)
368
+
369
+ [`{ "transform": "typescript-transform-react-jsx-source" }`](https://github.com/alexgorbatchev/typescript-transform-react-jsx-source)
370
+
371
+ [`{ "transform": "ts-transformer-remove-named-export" }`](https://github.com/dominguezcelada/ts-transformer-remove-named-export)
372
+
373
+ [`{ "transform": "ts-transformer-export-default-name" }`](https://github.com/jirutka/ts-transformer-export-default-name)
374
+
375
+ [`{ "transform": "ts-transformer-inline-file/transformer" }`](https://github.com/jirutka/ts-transformer-inline-file)
376
+
377
+ [`{ "transform": "ts-transformer-strip-const-enums", "entrySourceFiles": ["./src/index.ts" }`](https://github.com/timocov/ts-transformer-strip-const-enums)
378
+
379
+ [`{ "transform": "ts-transformer-properties-rename", "entrySourceFiles": ["./src/index.ts"] }`](https://github.com/timocov/ts-transformer-properties-rename)
380
+
381
+ [`{ "transform": "tsc-progress", "name": "TSC", "color": "green" }`](https://github.com/JiangWeixian/tsc-progress)
382
+
383
+ [Tutorial how to write a typescript transformer](https://dev.doctorevidence.com/how-to-write-a-typescript-transform-plugin-fc5308fdd943)
384
+
385
+ - [Tutorial how to write a typescript transformer](https://dev.doctorevidence.com/how-to-write-a-typescript-transform-plugin-fc5308fdd943)
386
+ - [Transformer framework](https://github.com/slune-org/simple-ts-transform)
387
+ - [Unit testing transformer compiler](https://github.com/slune-org/ts-transform-test-compiler)
388
+
389
+ ## Example
390
+
391
+ An example project is in the [example](./packages/ttypescript-examples) directory
392
+
393
+ ## License
394
+
395
+ MIT License
package/bin/tsc ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../lib/tsc.js')
package/bin/tsserver ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../lib/tsserver.js')
@@ -0,0 +1,67 @@
1
+ import * as ts from 'typescript';
2
+ export interface PluginConfig {
3
+ /**
4
+ * Language Server TypeScript Plugin name
5
+ */
6
+ name?: string;
7
+ /**
8
+ * Path to transformer or transformer module name
9
+ */
10
+ transform?: string;
11
+ /**
12
+ * The optional name of the exported transform plugin in the transform module.
13
+ */
14
+ import?: string;
15
+ /**
16
+ * Plugin entry point format type, default is program
17
+ */
18
+ type?: 'ls' | 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions';
19
+ /**
20
+ * Should transformer applied after all ones
21
+ */
22
+ after?: boolean;
23
+ /**
24
+ * Should transformer applied for d.ts files, supports from TS2.9
25
+ */
26
+ afterDeclarations?: boolean;
27
+ }
28
+ export interface TransformerBasePlugin {
29
+ before?: ts.TransformerFactory<ts.SourceFile>;
30
+ after?: ts.TransformerFactory<ts.SourceFile>;
31
+ afterDeclarations?: ts.TransformerFactory<ts.SourceFile | ts.Bundle>;
32
+ }
33
+ export type TransformerList = Required<ts.CustomTransformers>;
34
+ export type TransformerPlugin = TransformerBasePlugin | ts.TransformerFactory<ts.SourceFile>;
35
+ export type LSPattern = (ls: ts.LanguageService, config: {}) => TransformerPlugin;
36
+ export type ProgramPattern = (program: ts.Program, config: {}, helpers?: {
37
+ ts: typeof ts;
38
+ addDiagnostic: (diag: ts.Diagnostic) => void;
39
+ }) => TransformerPlugin;
40
+ export type CompilerOptionsPattern = (compilerOpts: ts.CompilerOptions, config: {}) => TransformerPlugin;
41
+ export type ConfigPattern = (config: {}) => TransformerPlugin;
42
+ export type TypeCheckerPattern = (checker: ts.TypeChecker, config: {}) => TransformerPlugin;
43
+ export type RawPattern = (context: ts.TransformationContext, program: ts.Program, config: {}) => ts.Transformer<ts.SourceFile>;
44
+ export type PluginFactory = LSPattern | ProgramPattern | ConfigPattern | CompilerOptionsPattern | TypeCheckerPattern | RawPattern;
45
+ /**
46
+ * @example
47
+ *
48
+ * new PluginCreator([
49
+ * {transform: '@zerollup/ts-transform-paths', someOption: '123'},
50
+ * {transform: '@zerollup/ts-transform-paths', type: 'ls', someOption: '123'},
51
+ * {transform: '@zerollup/ts-transform-paths', type: 'ls', after: true, someOption: '123'}
52
+ * ]).createTransformers({ program })
53
+ */
54
+ export declare class PluginCreator {
55
+ private typescript;
56
+ private configs;
57
+ private resolveBaseDir;
58
+ constructor(typescript: typeof ts, configs: PluginConfig[], resolveBaseDir?: string);
59
+ mergeTransformers(into: TransformerList, source: ts.CustomTransformers | TransformerBasePlugin): this;
60
+ createTransformers(params: {
61
+ program: ts.Program;
62
+ } | {
63
+ ls: ts.LanguageService;
64
+ }, customTransformers?: ts.CustomTransformers): Required<ts.CustomTransformers>;
65
+ private resolveFactory;
66
+ private validateConfigs;
67
+ }
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.PluginCreator = void 0;
15
+ var resolve = require("resolve");
16
+ var util_1 = require("util");
17
+ var patchCreateProgram_1 = require("./patchCreateProgram");
18
+ function createTransformerFromPattern(_a) {
19
+ var typescript = _a.typescript, factory = _a.factory, config = _a.config, program = _a.program, ls = _a.ls;
20
+ var transform = config.transform, after = config.after, afterDeclarations = config.afterDeclarations, name = config.name, type = config.type, cleanConfig = __rest(config, ["transform", "after", "afterDeclarations", "name", "type"]);
21
+ if (!transform)
22
+ throw new Error('Not a valid config entry: "transform" key not found');
23
+ var ret;
24
+ switch (config.type) {
25
+ case 'ls':
26
+ if (!ls)
27
+ throw new Error("Plugin ".concat(transform, " need a LanguageService"));
28
+ ret = factory(ls, cleanConfig);
29
+ break;
30
+ case 'config':
31
+ ret = factory(cleanConfig);
32
+ break;
33
+ case 'compilerOptions':
34
+ ret = factory(program.getCompilerOptions(), cleanConfig);
35
+ break;
36
+ case 'checker':
37
+ ret = factory(program.getTypeChecker(), cleanConfig);
38
+ break;
39
+ case undefined:
40
+ case 'program':
41
+ ret = factory(program, cleanConfig, {
42
+ ts: typescript,
43
+ addDiagnostic: (0, patchCreateProgram_1.addDiagnosticFactory)(program),
44
+ });
45
+ break;
46
+ case 'raw':
47
+ ret = function (ctx) { return factory(ctx, program, cleanConfig); };
48
+ break;
49
+ default:
50
+ return never(config.type);
51
+ }
52
+ if (typeof ret === 'function') {
53
+ if (after)
54
+ return { after: ret };
55
+ else if (afterDeclarations) {
56
+ return { afterDeclarations: ret };
57
+ }
58
+ else
59
+ return { before: ret };
60
+ }
61
+ return ret;
62
+ }
63
+ function never(n) {
64
+ throw new Error('Unexpected type: ' + n);
65
+ }
66
+ var tsNodeIncluded = false;
67
+ // to fix recursion bug, see usage below
68
+ var requireStack = [];
69
+ /**
70
+ * @example
71
+ *
72
+ * new PluginCreator([
73
+ * {transform: '@zerollup/ts-transform-paths', someOption: '123'},
74
+ * {transform: '@zerollup/ts-transform-paths', type: 'ls', someOption: '123'},
75
+ * {transform: '@zerollup/ts-transform-paths', type: 'ls', after: true, someOption: '123'}
76
+ * ]).createTransformers({ program })
77
+ */
78
+ var PluginCreator = /** @class */ (function () {
79
+ function PluginCreator(typescript, configs, resolveBaseDir) {
80
+ if (resolveBaseDir === void 0) { resolveBaseDir = process.cwd(); }
81
+ this.typescript = typescript;
82
+ this.configs = configs;
83
+ this.resolveBaseDir = resolveBaseDir;
84
+ this.validateConfigs(configs);
85
+ }
86
+ PluginCreator.prototype.mergeTransformers = function (into, source) {
87
+ var _a, _b, _c;
88
+ var slice = function (input) { return (Array.isArray(input) ? input.slice() : [input]); };
89
+ if (source.before) {
90
+ (_a = into.before).push.apply(_a, slice(source.before));
91
+ }
92
+ if (source.after) {
93
+ (_b = into.after).push.apply(_b, slice(source.after));
94
+ }
95
+ if (source.afterDeclarations) {
96
+ (_c = into.afterDeclarations).push.apply(_c, slice(source.afterDeclarations));
97
+ }
98
+ return this;
99
+ };
100
+ PluginCreator.prototype.createTransformers = function (params, customTransformers) {
101
+ var chain = {
102
+ before: [],
103
+ after: [],
104
+ afterDeclarations: [],
105
+ };
106
+ var ls;
107
+ var program;
108
+ if ('ls' in params) {
109
+ ls = params.ls;
110
+ program = ls.getProgram();
111
+ }
112
+ else {
113
+ program = params.program;
114
+ }
115
+ for (var _i = 0, _a = this.configs; _i < _a.length; _i++) {
116
+ var config = _a[_i];
117
+ if (!config.transform) {
118
+ continue;
119
+ }
120
+ var factory = this.resolveFactory(config.transform, config.import);
121
+ // if recursion
122
+ if (factory === undefined)
123
+ continue;
124
+ var transformer = createTransformerFromPattern({
125
+ typescript: this.typescript,
126
+ factory: factory,
127
+ config: config,
128
+ program: program,
129
+ ls: ls,
130
+ });
131
+ this.mergeTransformers(chain, transformer);
132
+ }
133
+ // if we're given some custom transformers, they must be chained at the end
134
+ if (customTransformers) {
135
+ this.mergeTransformers(chain, customTransformers);
136
+ }
137
+ return chain;
138
+ };
139
+ PluginCreator.prototype.resolveFactory = function (transform, importKey) {
140
+ if (importKey === void 0) { importKey = 'default'; }
141
+ if (!tsNodeIncluded &&
142
+ transform.match(/\.tsx?$/) &&
143
+ (module.parent.parent === null ||
144
+ module.parent.parent.parent === null ||
145
+ module.parent.parent.parent.id.split(/[\/\\]/).indexOf('ts-node') === -1)) {
146
+ require('ts-node').register({
147
+ transpileOnly: true,
148
+ skipProject: true,
149
+ compilerOptions: {
150
+ target: 'ES2018',
151
+ jsx: 'react',
152
+ esModuleInterop: true,
153
+ module: 'commonjs',
154
+ },
155
+ });
156
+ tsNodeIncluded = true;
157
+ }
158
+ var modulePath = resolve.sync(transform, { basedir: this.resolveBaseDir });
159
+ // in ts-node occurs error cause recursion:
160
+ // ts-node file.ts -> createTransformers -> require transformer.ts
161
+ // -> createTransformers -> require transformer.ts -> ...
162
+ // this happens cause ts-node uses to compile transformers the same config included this transformer
163
+ // so this stack checks that if we already required this file we are in the reqursion
164
+ if (requireStack.indexOf(modulePath) > -1)
165
+ return;
166
+ requireStack.push(modulePath);
167
+ var commonjsModule = require(modulePath);
168
+ requireStack.pop();
169
+ var factoryModule = typeof commonjsModule === 'function' ? { default: commonjsModule } : commonjsModule;
170
+ var factory = factoryModule[importKey];
171
+ if (!factory) {
172
+ throw new Error("tsconfig.json > plugins: \"".concat(transform, "\" does not have an export \"").concat(importKey, "\": ") +
173
+ (0, util_1.inspect)(factoryModule));
174
+ }
175
+ if (typeof factory !== 'function') {
176
+ throw new Error("tsconfig.json > plugins: \"".concat(transform, "\" export \"").concat(importKey, "\" is not a plugin: \"").concat((0, util_1.inspect)(factory), "\""));
177
+ }
178
+ return factory;
179
+ };
180
+ PluginCreator.prototype.validateConfigs = function (configs) {
181
+ for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {
182
+ var config = configs_1[_i];
183
+ if (!config.name && !config.transform) {
184
+ throw new Error('tsconfig.json plugins error: transform must be present');
185
+ }
186
+ }
187
+ };
188
+ return PluginCreator;
189
+ }());
190
+ exports.PluginCreator = PluginCreator;
File without changes
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ module.exports = require('typescript/lib/cancellationToken');
@@ -0,0 +1,7 @@
1
+ import * as TS from 'typescript';
2
+ type ts = typeof TS;
3
+ export declare function loadTypeScript(filename: string, { folder, forceConfigLoad }?: {
4
+ folder?: string;
5
+ forceConfigLoad?: boolean;
6
+ }): ts;
7
+ export {};
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.loadTypeScript = void 0;
15
+ var fs_1 = require("fs");
16
+ var resolve_1 = require("resolve");
17
+ var patchCreateProgram_1 = require("./patchCreateProgram");
18
+ var path_1 = require("path");
19
+ var vm_1 = require("vm");
20
+ var Module = require("module");
21
+ function loadTypeScript(filename, _a) {
22
+ var _b;
23
+ var _c = _a === void 0 ? {} : _a, _d = _c.folder, folder = _d === void 0 ? __dirname : _d, _e = _c.forceConfigLoad, forceConfigLoad = _e === void 0 ? false : _e;
24
+ var libFilename = (0, resolve_1.sync)('typescript/lib/' + filename, { basedir: folder });
25
+ if (!require.cache[libFilename]) {
26
+ var temp = TSModuleFactory(libFilename);
27
+ require.cache = __assign(__assign({}, require.cache), (_b = {}, _b[libFilename] = temp, _b));
28
+ }
29
+ var ts = TSModuleFactory(libFilename).exports;
30
+ var _f = ts.versionMajorMinor.split('.'), major = _f[0], minor = _f[1];
31
+ if (+major < 3 && +minor < 7) {
32
+ throw new Error('ttypescript supports typescript from 2.7 version');
33
+ }
34
+ var result = (0, patchCreateProgram_1.patchCreateProgram)(ts, forceConfigLoad);
35
+ if (+major >= 5 && result.args) {
36
+ result.args.this = result.args.exports;
37
+ }
38
+ return result;
39
+ }
40
+ exports.loadTypeScript = loadTypeScript;
41
+ var typeScriptFactoryCache = new Map();
42
+ function TSModuleFactory(filename) {
43
+ var factory = typeScriptFactoryCache.get(filename);
44
+ if (!factory) {
45
+ var code = (0, fs_1.readFileSync)(filename, 'utf8');
46
+ factory = (0, vm_1.runInThisContext)("(function (exports, require, module, __filename, __dirname) {".concat(code, "\n});"), {
47
+ filename: filename,
48
+ lineOffset: 0,
49
+ displayErrors: true,
50
+ });
51
+ typeScriptFactoryCache.set(filename, factory);
52
+ }
53
+ var newModule = new Module(filename, module);
54
+ factory.call(newModule, newModule.exports, require, newModule, filename, (0, path_1.dirname)(filename));
55
+ return newModule;
56
+ }
@@ -0,0 +1,21 @@
1
+ import * as ts from 'typescript';
2
+ import { Diagnostic } from 'typescript/lib/tsserverlibrary';
3
+ declare module 'typescript' {
4
+ interface CreateProgramOptions {
5
+ rootNames: ReadonlyArray<string>;
6
+ options: ts.CompilerOptions;
7
+ projectReferences?: ReadonlyArray<ts.ProjectReference>;
8
+ host?: ts.CompilerHost;
9
+ oldProgram?: ts.Program;
10
+ configFileParsingDiagnostics?: ReadonlyArray<ts.Diagnostic>;
11
+ }
12
+ interface ProjectReference {
13
+ path: string;
14
+ originalPath?: string;
15
+ prepend?: boolean;
16
+ circular?: boolean;
17
+ }
18
+ }
19
+ export declare const transformerErrors: WeakMap<ts.Program, Diagnostic[]>;
20
+ export declare function addDiagnosticFactory(program: ts.Program): (diag: ts.Diagnostic) => void;
21
+ export declare function patchCreateProgram(tsm: typeof ts, forceReadConfig?: boolean, projectDir?: string): typeof ts;
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __rest = (this && this.__rest) || function (s, e) {
14
+ var t = {};
15
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
+ t[p] = s[p];
17
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
+ t[p[i]] = s[p[i]];
21
+ }
22
+ return t;
23
+ };
24
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
25
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
26
+ if (ar || !(i in from)) {
27
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
28
+ ar[i] = from[i];
29
+ }
30
+ }
31
+ return to.concat(ar || Array.prototype.slice.call(from));
32
+ };
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.patchCreateProgram = exports.addDiagnosticFactory = exports.transformerErrors = void 0;
35
+ var path_1 = require("path");
36
+ var PluginCreator_1 = require("./PluginCreator");
37
+ exports.transformerErrors = new WeakMap();
38
+ function addDiagnosticFactory(program) {
39
+ return function (diag) {
40
+ var arr = exports.transformerErrors.get(program) || [];
41
+ arr.push(diag);
42
+ exports.transformerErrors.set(program, arr);
43
+ };
44
+ }
45
+ exports.addDiagnosticFactory = addDiagnosticFactory;
46
+ function patchCreateProgram(tsm, forceReadConfig, projectDir) {
47
+ if (forceReadConfig === void 0) { forceReadConfig = false; }
48
+ if (projectDir === void 0) { projectDir = process.cwd(); }
49
+ var originCreateProgram = tsm.createProgram;
50
+ var _ = tsm.createProgram, rest1 = __rest(tsm, ["createProgram"]);
51
+ function hackCreateProgram(rootNamesOrOptions, options, host, oldProgram, configFileParsingDiagnostics) {
52
+ var rootNames;
53
+ var createOpts;
54
+ if (!Array.isArray(rootNamesOrOptions)) {
55
+ createOpts = rootNamesOrOptions;
56
+ }
57
+ if (createOpts) {
58
+ rootNames = createOpts.rootNames;
59
+ options = createOpts.options;
60
+ host = createOpts.host;
61
+ oldProgram = createOpts.oldProgram;
62
+ configFileParsingDiagnostics = createOpts.configFileParsingDiagnostics;
63
+ }
64
+ else {
65
+ options = options;
66
+ rootNames = rootNamesOrOptions;
67
+ }
68
+ if (forceReadConfig) {
69
+ var info = getConfig(tsm, options, rootNames, projectDir);
70
+ options = info.compilerOptions;
71
+ if (createOpts) {
72
+ createOpts.options = options;
73
+ }
74
+ projectDir = info.projectDir;
75
+ }
76
+ var program = createOpts
77
+ ? originCreateProgram(createOpts)
78
+ : originCreateProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics);
79
+ var plugins = preparePluginsFromCompilerOptions(options.plugins);
80
+ var pluginCreator = new PluginCreator_1.PluginCreator(tsm, plugins, projectDir);
81
+ var originEmit = program.emit;
82
+ /**
83
+ * The emit method has the following declaration:
84
+ * https://github.com/microsoft/TypeScript/blob/bfc55b5762443c37ecdef08a3b5a4e057b4d1e85/src/compiler/builderPublic.ts#L101
85
+ * The declaration specifies 5 arguments, but it's not true. Sometimes the emit method takes 6 arguments.
86
+ */
87
+ program.emit = function newEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, arg) {
88
+ var mergedTransformers = pluginCreator.createTransformers({ program: program }, customTransformers);
89
+ var result = originEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, mergedTransformers, arg);
90
+ // todo: doesn't work with 3.7
91
+ // result.diagnostics = [...result.diagnostics, ...transformerErrors.get(program)!];
92
+ return result;
93
+ };
94
+ return program;
95
+ }
96
+ rest1.createProgram = hackCreateProgram;
97
+ return injectionShadowedValues(rest1);
98
+ }
99
+ exports.patchCreateProgram = patchCreateProgram;
100
+ function getConfig(tsm, compilerOptions, rootFileNames, defaultDir) {
101
+ if (compilerOptions.configFilePath === undefined) {
102
+ var dir = rootFileNames.length > 0 ? (0, path_1.dirname)(rootFileNames[0]) : defaultDir;
103
+ var tsconfigPath = tsm.findConfigFile(dir, tsm.sys.fileExists);
104
+ if (tsconfigPath) {
105
+ var projectDir = (0, path_1.dirname)(tsconfigPath);
106
+ var config = readConfig(tsm, tsconfigPath, (0, path_1.dirname)(tsconfigPath));
107
+ compilerOptions = __assign(__assign({}, config.options), compilerOptions);
108
+ return {
109
+ projectDir: projectDir,
110
+ compilerOptions: compilerOptions,
111
+ };
112
+ }
113
+ }
114
+ return {
115
+ projectDir: (0, path_1.dirname)(compilerOptions.configFilePath),
116
+ compilerOptions: compilerOptions,
117
+ };
118
+ }
119
+ function readConfig(tsm, configFileNamePath, projectDir) {
120
+ var result = tsm.readConfigFile(configFileNamePath, tsm.sys.readFile);
121
+ if (result.error) {
122
+ throw new Error('tsconfig.json error: ' + result.error.messageText);
123
+ }
124
+ return tsm.parseJsonConfigFileContent(result.config, tsm.sys, projectDir, undefined, configFileNamePath);
125
+ }
126
+ function preparePluginsFromCompilerOptions(plugins) {
127
+ if (!plugins)
128
+ return [];
129
+ // old transformers system
130
+ if (plugins.length === 1 && plugins[0].customTransformers) {
131
+ var _a = plugins[0].customTransformers, _b = _a.before, before = _b === void 0 ? [] : _b, _c = _a.after, after = _c === void 0 ? [] : _c;
132
+ return __spreadArray(__spreadArray([], before.map(function (item) { return ({ transform: item }); }), true), after.map(function (item) { return ({ transform: item, after: true }); }), true);
133
+ }
134
+ return plugins;
135
+ }
136
+ function injectionShadowedValues(target) {
137
+ target.getDefaultCompilerOptions2 = function getDefaultCompilerOptions2() {
138
+ return {
139
+ target: 1 /* ES5 */,
140
+ jsx: 1 /* Preserve */,
141
+ };
142
+ };
143
+ function fail(message, stackCrawlMark) {
144
+ debugger;
145
+ var e = new Error(message ? "Debug Failure. ".concat(message) : 'Debug Failure.');
146
+ if (Error.captureStackTrace) {
147
+ Error.captureStackTrace(e, stackCrawlMark || fail);
148
+ }
149
+ throw e;
150
+ }
151
+ function assertEqual(a, b, msg, msg2, stackCrawlMark) {
152
+ if (a !== b) {
153
+ var message = msg ? (msg2 ? "".concat(msg, " ").concat(msg2) : msg) : '';
154
+ fail("Expected ".concat(a, " === ").concat(b, ". ").concat(message), stackCrawlMark || assertEqual);
155
+ }
156
+ }
157
+ target.assertEqual = assertEqual;
158
+ function fileExtensionIs(path, extension) {
159
+ return path.length > extension.length && path.endsWith(extension);
160
+ }
161
+ try {
162
+ var originTranspileModule = target.transpileModule
163
+ .toString()
164
+ .replace(/(?<!function)\s([a-z][A-Za-z0-9]+)\(/g, ' target.$1(')
165
+ .replace('hasProperty', 'target.hasProperty')
166
+ .replace(/Debug\./g, 'target.')
167
+ .replace('transpileOptionValueCompilerOptions', 'target.transpileOptionValueCompilerOptions');
168
+ var __ = target.transpileModule, _target = __rest(target, ["transpileModule"]);
169
+ _target.transpileModule = eval('(' + originTranspileModule + ')');
170
+ return _target;
171
+ }
172
+ catch (e) {
173
+ return target;
174
+ }
175
+ }
package/lib/tsc.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/tsc.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var fs = require("fs");
4
+ var resolve = require("resolve");
5
+ var loadTypescript_1 = require("./loadTypescript");
6
+ var path_1 = require("path");
7
+ var vm_1 = require("vm");
8
+ var ts = (0, loadTypescript_1.loadTypeScript)('typescript', { folder: process.cwd(), forceConfigLoad: true });
9
+ var tscFileName = resolve.sync('typescript/lib/tsc', { basedir: process.cwd() });
10
+ var _a = ts.version.split('.').map(function (str) { return Number(str); }), major = _a[0], minor = _a[1];
11
+ var commandLineTsCode = fs
12
+ .readFileSync(tscFileName, 'utf8')
13
+ .replace(major >= 4 && minor >= 9
14
+ ? /^[\s\S]+(\(function \(ts\) {\s+var StatisticType;[\s\S]+)$/
15
+ : /^[\s\S]+(\(function \(ts\) \{\s+function countLines[\s\S]+)$/, '$1');
16
+ if (major >= 5) {
17
+ commandLineTsCode = commandLineTsCode.replace(/\= createProgram\(/g, '= ts.createProgram(');
18
+ }
19
+ var globalCode = (fs.readFileSync(tscFileName, 'utf8').match(/^([\s\S]*?)var ts;/) || ['', ''])[1];
20
+ (0, vm_1.runInThisContext)("(function (exports, require, module, __filename, __dirname, ts) {".concat(globalCode).concat(commandLineTsCode, "\n});"), {
21
+ filename: tscFileName,
22
+ lineOffset: 0,
23
+ displayErrors: true,
24
+ }).call(ts, ts, require, { exports: ts }, tscFileName, (0, path_1.dirname)(tscFileName), ts);
File without changes
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ module.exports = require('typescript/lib/tsserver');
@@ -0,0 +1,3 @@
1
+ import * as TSSL from 'typescript/lib/tsserverlibrary';
2
+ declare const ts: typeof TSSL;
3
+ export = ts;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ var loadTypescript_1 = require("./loadTypescript");
3
+ var ts = (0, loadTypescript_1.loadTypeScript)('tsserverlibrary');
4
+ module.exports = ts;
@@ -0,0 +1,3 @@
1
+ import * as TS from 'typescript';
2
+ declare const ts: typeof TS;
3
+ export = ts;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ var loadTypescript_1 = require("./loadTypescript");
3
+ var ts = (0, loadTypescript_1.loadTypeScript)('typescript');
4
+ module.exports = ts;
@@ -0,0 +1,3 @@
1
+ import * as TS from 'typescript';
2
+ declare const ts: typeof TS;
3
+ export = ts;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ var loadTypescript_1 = require("./loadTypescript");
3
+ var ts = (0, loadTypescript_1.loadTypeScript)('typescriptServices');
4
+ module.exports = ts;
File without changes
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ module.exports = require('typescript/lib/typingsInstaller');
File without changes
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ module.exports = require('typescript/lib/watchGuard');
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "ttsc",
3
+ "bin": {
4
+ "ttsc": "./bin/tsc",
5
+ "ttsserver": "./bin/tsserver"
6
+ },
7
+ "version": "0.0.1",
8
+ "description": "Over TypeScript tool to use custom transformers in the tsconfig.json",
9
+ "main": "lib/typescript.js",
10
+ "files": [
11
+ "*.md",
12
+ "bin",
13
+ "lib",
14
+ "ts-node-config"
15
+ ],
16
+ "author": "cevek",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/solar-religion/ttsc.git"
20
+ },
21
+ "homepage": "https://github.com/solar-religion/ttsc/tree/main/packages/ttypescript",
22
+ "keywords": [
23
+ "typescript",
24
+ "wrapper",
25
+ "transform",
26
+ "transformer",
27
+ "plugin",
28
+ "config"
29
+ ],
30
+ "license": "MIT",
31
+ "dependencies": {
32
+ "resolve": ">=1.9.0"
33
+ },
34
+ "devDependencies": {
35
+ "ts-node": ">=8.0.2",
36
+ "typescript": ">=3.2.2"
37
+ },
38
+ "peerDependencies": {
39
+ "ts-node": ">=8.0.2",
40
+ "typescript": ">=3.2.2"
41
+ }
42
+ }