-
Notifications
You must be signed in to change notification settings - Fork 361
/
typescript.ts
535 lines (465 loc) · 14.5 KB
/
typescript.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import * as path from "path";
import * as semver from "semver";
import { PROJEN_DIR, PROJEN_RC } from "../common";
import { Component } from "../component";
import {
Eslint,
EslintOptions,
Jest,
NodeProject,
NodeProjectOptions,
TypeScriptCompilerOptions,
TypescriptConfig,
TypescriptConfigOptions,
} from "../javascript";
import { SampleDir } from "../sample-file";
import { Task } from "../task";
import { TextFile } from "../textfile";
import {
Projenrc as ProjenrcTs,
ProjenrcOptions as ProjenrcTsOptions,
TypedocDocgen,
} from "../typescript";
export interface TypeScriptProjectOptions extends NodeProjectOptions {
/**
* Typescript artifacts output directory
*
* @default "lib"
*/
readonly libdir?: string;
/**
* Typescript sources directory.
*
* @default "src"
*/
readonly srcdir?: string;
/**
* Jest tests directory. Tests files should be named `xxx.test.ts`.
*
* If this directory is under `srcdir` (e.g. `src/test`, `src/__tests__`),
* then tests are going to be compiled into `lib/` and executed as javascript.
* If the test directory is outside of `src`, then we configure jest to
* compile the code in-memory.
*
* @default "test"
*/
readonly testdir?: string;
/**
* Setup eslint.
*
* @default true
*/
readonly eslint?: boolean;
/**
* Eslint options
* @default - opinionated default options
*/
readonly eslintOptions?: EslintOptions;
/**
* TypeScript version to use.
*
* NOTE: Typescript is not semantically versioned and should remain on the
* same minor, so we recommend using a `~` dependency (e.g. `~1.2.3`).
*
* @default "latest"
*/
readonly typescriptVersion?: string;
/**
* Docgen by Typedoc
*
* @default false
*/
readonly docgen?: boolean;
/**
* Docs directory
*
* @default "docs"
*/
readonly docsDirectory?: string;
/**
* Custom TSConfig
* @default - default options
*/
readonly tsconfig?: TypescriptConfigOptions;
/**
* Custom tsconfig options for the development tsconfig.json file (used for testing).
* @default - use the production tsconfig options
*/
readonly tsconfigDev?: TypescriptConfigOptions;
/**
* The name of the development tsconfig.json file.
*
* @default "tsconfig.dev.json"
*/
readonly tsconfigDevFile?: string;
/**
* Do not generate a `tsconfig.json` file (used by jsii projects since
* tsconfig.json is generated by the jsii compiler).
*
* @default false
*/
readonly disableTsconfig?: boolean;
/**
* Generate one-time sample in `src/` and `test/` if there are no files there.
* @default true
*/
readonly sampleCode?: boolean;
/**
* The .d.ts file that includes the type declarations for this module.
* @default - .d.ts file derived from the project's entrypoint (usually lib/index.d.ts)
*/
readonly entrypointTypes?: string;
/**
* Use TypeScript for your projenrc file (`.projenrc.ts`).
*
* @default false
*/
readonly projenrcTs?: boolean;
/**
* Options for .projenrc.ts
*/
readonly projenrcTsOptions?: ProjenrcTsOptions;
}
/**
* TypeScript project
* @pjid typescript
*/
export class TypeScriptProject extends NodeProject {
public readonly docgen?: boolean;
public readonly docsDirectory: string;
public readonly eslint?: Eslint;
public readonly tsconfigEslint?: TypescriptConfig;
public readonly tsconfig?: TypescriptConfig;
/**
* A typescript configuration file which covers all files (sources, tests, projen).
*/
public readonly tsconfigDev: TypescriptConfig;
/**
* The directory in which the .ts sources reside.
*/
public readonly srcdir: string;
/**
* The directory in which compiled .js files reside.
*/
public readonly libdir: string;
/**
* The directory in which tests reside.
*/
public readonly testdir: string;
/**
* The "watch" task.
*/
public readonly watchTask: Task;
constructor(options: TypeScriptProjectOptions) {
super({
...options,
// disable .projenrc.js if typescript is enabled
projenrcJs: options.projenrcTs ? false : options.projenrcJs,
jestOptions: {
...options.jestOptions,
jestConfig: {
...options.jestOptions?.jestConfig,
testMatch: [],
},
},
});
this.srcdir = options.srcdir ?? "src";
this.libdir = options.libdir ?? "lib";
this.docgen = options.docgen;
this.docsDirectory = options.docsDirectory ?? "docs/";
this.compileTask.exec("tsc --build");
this.watchTask = this.addTask("watch", {
description: "Watch & compile in the background",
exec: "tsc --build -w",
});
this.testdir = options.testdir ?? "test";
this.gitignore.include(`/${this.testdir}/`);
this.npmignore?.exclude(`/${this.testdir}/`);
// if the test directory is under `src/`, then we will run our tests against
// the javascript files and not let jest compile it for us.
const compiledTests = this.testdir.startsWith(this.srcdir + path.posix.sep);
if (options.entrypointTypes || this.entrypoint !== "") {
const entrypointTypes =
options.entrypointTypes ??
`${path
.join(
path.dirname(this.entrypoint),
path.basename(this.entrypoint, ".js")
)
.replace(/\\/g, "/")}.d.ts`;
this.package.addField("types", entrypointTypes);
}
const compilerOptionDefaults: TypeScriptCompilerOptions = {
alwaysStrict: true,
declaration: true,
esModuleInterop: true,
experimentalDecorators: true,
inlineSourceMap: true,
inlineSources: true,
lib: ["es2019"],
module: "CommonJS",
noEmitOnError: false,
noFallthroughCasesInSwitch: true,
noImplicitAny: true,
noImplicitReturns: true,
noImplicitThis: true,
noUnusedLocals: true,
noUnusedParameters: true,
resolveJsonModule: true,
strict: true,
strictNullChecks: true,
strictPropertyInitialization: true,
stripInternal: true,
target: "ES2019",
};
if (!options.disableTsconfig) {
this.tsconfig = new TypescriptConfig(
this,
mergeTsconfigOptions(
{
include: [`${this.srcdir}/**/*.ts`],
// exclude: ['node_modules'], // TODO: shouldn't we exclude node_modules?
compilerOptions: {
rootDir: this.srcdir,
outDir: this.libdir,
...compilerOptionDefaults,
},
},
options.tsconfig
)
);
}
const tsconfigDevFile = options.tsconfigDevFile ?? "tsconfig.dev.json";
this.tsconfigDev = new TypescriptConfig(
this,
mergeTsconfigOptions(
{
fileName: tsconfigDevFile,
include: [
PROJEN_RC,
`${this.srcdir}/**/*.ts`,
`${this.testdir}/**/*.ts`,
],
exclude: ["node_modules"],
compilerOptions: compilerOptionDefaults,
},
options.tsconfig,
options.tsconfigDev
)
);
this.gitignore.include(`/${this.srcdir}/`);
this.npmignore?.exclude(`/${this.srcdir}/`);
if (this.srcdir !== this.libdir) {
// separated, can ignore the entire libdir
this.gitignore.exclude(`/${this.libdir}`);
} else {
// collocated, can only ignore the compiled output
this.gitignore.exclude(`/${this.libdir}/**/*.js`);
this.gitignore.exclude(`/${this.libdir}/**/*.d.ts`);
this.gitignore.exclude(`/${this.libdir}/**/*.d.ts.map`);
}
this.npmignore?.include(`/${this.libdir}/`);
this.npmignore?.include(`/${this.libdir}/**/*.js`);
this.npmignore?.include(`/${this.libdir}/**/*.d.ts`);
this.gitignore.exclude("/dist/");
this.npmignore?.exclude("dist"); // jsii-pacmak expects this to be "dist" and not "/dist". otherwise it will tamper with it
this.npmignore?.exclude("/tsconfig.json");
this.npmignore?.exclude("/.github/");
this.npmignore?.exclude("/.vscode/");
this.npmignore?.exclude("/.idea/");
this.npmignore?.exclude("/.projenrc.js");
this.npmignore?.exclude("tsconfig.tsbuildinfo");
if (this.jest) {
if (compiledTests) {
this.addJestCompiled(this.jest);
} else {
this.addJestNoCompile(this.jest);
}
}
const projenrcTypeScript = options.projenrcTs ?? false;
const projenRcFilename = projenrcTypeScript
? options.projenrcTsOptions?.filename ?? ".projenrc.ts"
: undefined;
if (options.eslint ?? true) {
const devdirs = [this.testdir, "build-tools"];
if (projenrcTypeScript) {
devdirs.push(options.projenrcTsOptions?.projenCodeDir ?? "projenrc");
}
this.eslint = new Eslint(this, {
tsconfigPath: `./${this.tsconfigDev.fileName}`,
dirs: [this.srcdir],
devdirs,
fileExtensions: [".ts", ".tsx"],
lintProjenRcFile: projenRcFilename,
...options.eslintOptions,
});
this.tsconfigEslint = this.tsconfigDev;
}
if (!this.parent && projenrcTypeScript) {
new ProjenrcTs(this, options.projenrcTsOptions);
}
const tsver = options.typescriptVersion
? `@${options.typescriptVersion}`
: "";
this.addDevDeps(
`typescript${tsver}`,
// @types/node versions numbers match the node runtime versions' major.minor, however, new
// releases are only created when API changes are included in a node release... We might for
// example have dependencies that require `node >= 12.22`, but as 12.21 and 12.22 did not
// include API changes, `@types/node@12.20.x` is the "correct" version to use. As it is not
// possible to easily determine the correct version to use, we pick up the latest version.
//
// Additionally, we default to tracking the 12.x line, as the current earliest LTS release of
// node is 12.x, so this is what corresponds to the broadest compatibility with supported node
// runtimes.
`@types/node@^${semver.major(this.package.minNodeVersion ?? "16.0.0")}`
);
// generate sample code in `src` and `lib` if these directories are empty or non-existent.
if (options.sampleCode ?? true) {
new SampleCode(this);
}
if (this.docgen) {
new TypedocDocgen(this);
}
}
/**
* Tests are compiled to `lib/TESTDIR`, so we don't need jest to compile them
* for us. just run them directly from javascript.
*/
private addJestCompiled(jest: Jest) {
this.addDevDeps(`@types/jest${jest.jestVersion}`);
const testout = path.posix.relative(this.srcdir, this.testdir);
const libtest = path.posix.join(this.libdir, testout);
const srctest = this.testdir;
this.npmignore?.exclude(`/${libtest}/`);
jest.addTestMatch(`**/${libtest}/**/?(*.)+(spec|test).js?(x)`);
jest.addWatchIgnorePattern(`/${this.srcdir}/`);
const resolveSnapshotPath = (test: string, ext: string) => {
const fullpath = test.replace(libtest, srctest);
return path.join(
path.dirname(fullpath),
"__snapshots__",
path.basename(fullpath, ".js") + ".ts" + ext
);
};
const resolveTestPath = (snap: string, ext: string) => {
const filename = path.basename(snap, ".ts" + ext) + ".js";
const dir = path.dirname(path.dirname(snap)).replace(srctest, libtest);
return path.join(dir, filename);
};
const resolver = new TextFile(
this,
path.posix.join(PROJEN_DIR, "jest-snapshot-resolver.js")
);
if (!resolver.marker) {
resolver.addLine(`// ${resolver.marker}`);
}
resolver.addLine('const path = require("path");');
resolver.addLine(`const libtest = "${libtest}";`);
resolver.addLine(`const srctest= "${srctest}";`);
resolver.addLine("module.exports = {");
resolver.addLine(
` resolveSnapshotPath: ${resolveSnapshotPath.toString()},`
);
resolver.addLine(` resolveTestPath: ${resolveTestPath.toString()},`);
resolver.addLine(
" testPathForConsistencyCheck: path.join('some', '__tests__', 'example.test.js')"
);
resolver.addLine("};");
jest.addSnapshotResolver(`./${resolver.path}`);
}
private addJestNoCompile(jest: Jest) {
this.addDevDeps(
`@types/jest${jest.jestVersion}`,
`ts-jest${jest.jestVersion}`
);
jest.addTestMatch(`<rootDir>/${this.srcdir}/**/__tests__/**/*.ts?(x)`);
jest.addTestMatch(
`<rootDir>/(${this.testdir}|${this.srcdir})/**/*(*.)@(spec|test).ts?(x)`
);
// add relevant deps
jest.config.preset = "ts-jest";
jest.config.globals = {
"ts-jest": {
tsconfig: this.tsconfigDev.fileName,
},
};
}
}
class SampleCode extends Component {
constructor(project: TypeScriptProject) {
super(project);
const srcCode = [
"export class Hello {",
" public sayHello() {",
" return 'hello, world!';",
" }",
"}",
].join("\n");
const testCode = [
"import { Hello } from '../src';",
"",
"test('hello', () => {",
" expect(new Hello().sayHello()).toBe('hello, world!');",
"});",
].join("\n");
new SampleDir(project, project.srcdir, {
files: {
"index.ts": srcCode,
},
});
if (project.jest) {
new SampleDir(project, project.testdir, {
files: {
"hello.test.ts": testCode,
},
});
}
}
}
/**
* TypeScript app.
*
* @pjid typescript-app
*/
export class TypeScriptAppProject extends TypeScriptProject {
constructor(options: TypeScriptProjectOptions) {
super({
allowLibraryDependencies: false,
releaseWorkflow: false,
entrypoint: "", // "main" is not needed in typescript apps
package: false,
...options,
});
}
}
/**
* @deprecated use `TypeScriptProject`
*/
export class TypeScriptLibraryProject extends TypeScriptProject {}
/**
* @deprecated use TypeScriptProjectOptions
*/
export interface TypeScriptLibraryProjectOptions
extends TypeScriptProjectOptions {}
/**
* @internal
*/
export function mergeTsconfigOptions(
...options: (TypescriptConfigOptions | undefined)[]
): TypescriptConfigOptions {
const definedOptions = options.filter(Boolean) as TypescriptConfigOptions[];
return definedOptions.reduce<TypescriptConfigOptions>(
(previous, current) => ({
...previous,
...current,
include: [...(previous.include ?? []), ...(current.include ?? [])],
exclude: [...(previous.exclude ?? []), ...(current.exclude ?? [])],
compilerOptions: {
...previous.compilerOptions,
...current.compilerOptions,
},
}),
{ compilerOptions: {} }
);
}