jsii 6.0.22-dev.0 → 7.1.0-dev.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.
Files changed (107) hide show
  1. package/lib/assembler.d.ts +254 -196
  2. package/lib/assembler.js +2105 -2327
  3. package/lib/assembler.js.map +1 -1
  4. package/lib/case.js.map +1 -1
  5. package/lib/common/find-utils.js.map +1 -1
  6. package/lib/common/index.d.ts +1 -1
  7. package/lib/common/index.js +2 -1
  8. package/lib/common/index.js.map +1 -1
  9. package/lib/common/symbol-id.d.ts +23 -4
  10. package/lib/common/symbol-id.js +13 -9
  11. package/lib/common/symbol-id.js.map +1 -1
  12. package/lib/compiler-host.d.ts +60 -0
  13. package/lib/compiler-host.js +201 -0
  14. package/lib/compiler-host.js.map +1 -0
  15. package/lib/compiler.d.ts +74 -62
  16. package/lib/compiler.js +332 -254
  17. package/lib/compiler.js.map +1 -1
  18. package/lib/diagnostic.d.ts +34 -0
  19. package/lib/diagnostic.js +141 -0
  20. package/lib/diagnostic.js.map +1 -0
  21. package/lib/emitter.d.ts +40 -10
  22. package/lib/emitter.js +188 -0
  23. package/lib/emitter.js.map +1 -1
  24. package/lib/helpers.d.ts +1 -1
  25. package/lib/helpers.js +2 -2
  26. package/lib/helpers.js.map +1 -1
  27. package/lib/index.js.map +1 -1
  28. package/lib/jsii-diagnostic.d.ts +27 -22
  29. package/lib/jsii-diagnostic.js +22 -38
  30. package/lib/jsii-diagnostic.js.map +1 -1
  31. package/lib/literate.js.map +1 -1
  32. package/lib/main.js +3 -2
  33. package/lib/main.js.map +1 -1
  34. package/lib/project-info.d.ts +23 -4
  35. package/lib/project-info.js +5 -5
  36. package/lib/project-info.js.map +1 -1
  37. package/lib/support-types.d.ts +2 -0
  38. package/lib/support-types.js +3 -0
  39. package/lib/support-types.js.map +1 -0
  40. package/lib/support.js.map +1 -1
  41. package/lib/tsconfig/compiler-options.d.ts +12 -46
  42. package/lib/tsconfig/compiler-options.js +45 -87
  43. package/lib/tsconfig/compiler-options.js.map +1 -1
  44. package/lib/tsconfig/index.d.ts +24 -5
  45. package/lib/tsconfig/index.js.map +1 -1
  46. package/lib/tsconfig/read.d.ts +15 -0
  47. package/lib/tsconfig/read.js +196 -0
  48. package/lib/tsconfig/read.js.map +1 -0
  49. package/lib/tsconfig/rule-set-format.js.map +1 -1
  50. package/lib/tsconfig/rulesets/configurable-options.js.map +1 -1
  51. package/lib/tsconfig/rulesets/deprecated-options.js.map +1 -1
  52. package/lib/tsconfig/rulesets/generated.public.js.map +1 -1
  53. package/lib/tsconfig/rulesets/incompatible-options.js.map +1 -1
  54. package/lib/tsconfig/rulesets/jsii-configured-options.js.map +1 -1
  55. package/lib/tsconfig/rulesets/minimal.public.js.map +1 -1
  56. package/lib/tsconfig/rulesets/strict-family-options.js.map +1 -1
  57. package/lib/tsconfig/rulesets/strict.public.js.map +1 -1
  58. package/lib/tsconfig/tsconfig-validator.js +2 -50
  59. package/lib/tsconfig/tsconfig-validator.js.map +1 -1
  60. package/lib/tsconfig/validator.js.map +1 -1
  61. package/lib/type-analysis.js.map +1 -1
  62. package/lib/type-reference.js.map +1 -1
  63. package/lib/type-visitor.js.map +1 -1
  64. package/lib/utils.d.ts +6 -6
  65. package/lib/utils.js +8 -13
  66. package/lib/utils.js.map +1 -1
  67. package/lib/version.d.ts +3 -3
  68. package/lib/version.js +4 -4
  69. package/lib/version.js.map +1 -1
  70. package/lib/warnings.d.ts +2 -2
  71. package/lib/warnings.js +3 -77
  72. package/lib/warnings.js.map +1 -1
  73. package/package.json +15 -11
  74. package/scripts/ts7-compare-jsii.mjs +101 -0
  75. package/lib/directives.d.ts +0 -24
  76. package/lib/directives.js +0 -139
  77. package/lib/directives.js.map +0 -1
  78. package/lib/docs.d.ts +0 -64
  79. package/lib/docs.js +0 -293
  80. package/lib/docs.js.map +0 -1
  81. package/lib/node-bindings.d.ts +0 -19
  82. package/lib/node-bindings.js +0 -49
  83. package/lib/node-bindings.js.map +0 -1
  84. package/lib/reserved-words.d.ts +0 -6
  85. package/lib/reserved-words.js +0 -258
  86. package/lib/reserved-words.js.map +0 -1
  87. package/lib/sets.d.ts +0 -16
  88. package/lib/sets.js +0 -41
  89. package/lib/sets.js.map +0 -1
  90. package/lib/transforms/deprecated-remover.d.ts +0 -44
  91. package/lib/transforms/deprecated-remover.js +0 -545
  92. package/lib/transforms/deprecated-remover.js.map +0 -1
  93. package/lib/transforms/deprecation-warnings.d.ts +0 -37
  94. package/lib/transforms/deprecation-warnings.js +0 -616
  95. package/lib/transforms/deprecation-warnings.js.map +0 -1
  96. package/lib/transforms/runtime-info.d.ts +0 -39
  97. package/lib/transforms/runtime-info.js +0 -128
  98. package/lib/transforms/runtime-info.js.map +0 -1
  99. package/lib/transforms/utils.d.ts +0 -11
  100. package/lib/transforms/utils.js +0 -31
  101. package/lib/transforms/utils.js.map +0 -1
  102. package/lib/type-tracker.d.ts +0 -13
  103. package/lib/type-tracker.js +0 -67
  104. package/lib/type-tracker.js.map +0 -1
  105. package/lib/validator.d.ts +0 -19
  106. package/lib/validator.js +0 -602
  107. package/lib/validator.js.map +0 -1
package/lib/compiler.js CHANGED
@@ -37,31 +37,42 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.Compiler = exports.JSII_DIAGNOSTICS_CODE = exports.DIAGNOSTICS = void 0;
40
+ exports.buildProject = buildProject;
41
+ exports.toDiagnostic = toDiagnostic;
42
+ const crypto = __importStar(require("node:crypto"));
40
43
  const fs = __importStar(require("node:fs"));
41
44
  const path = __importStar(require("node:path"));
45
+ const spec_1 = require("@jsii/spec");
42
46
  const chalk_1 = __importDefault(require("chalk"));
43
47
  const log4js = __importStar(require("log4js"));
44
- const ts = __importStar(require("typescript"));
45
48
  const assembler_1 = require("./assembler");
46
49
  const find_utils_1 = require("./common/find-utils");
50
+ const compiler_host_1 = require("./compiler-host");
51
+ const diagnostic_1 = require("./diagnostic");
52
+ const emitter_1 = require("./emitter");
47
53
  const jsii_diagnostic_1 = require("./jsii-diagnostic");
48
- const deprecation_warnings_1 = require("./transforms/deprecation-warnings");
54
+ const literate = __importStar(require("./literate"));
49
55
  const tsconfig_1 = require("./tsconfig");
50
56
  const compiler_options_1 = require("./tsconfig/compiler-options");
57
+ const read_1 = require("./tsconfig/read");
51
58
  const tsconfig_validator_1 = require("./tsconfig/tsconfig-validator");
52
59
  const validator_1 = require("./tsconfig/validator");
53
60
  const utils = __importStar(require("./utils"));
54
- const warnings_1 = require("./warnings");
55
61
  const LOG = log4js.getLogger('jsii/compiler');
56
62
  exports.DIAGNOSTICS = 'diagnostics';
57
63
  exports.JSII_DIAGNOSTICS_CODE = 9999;
64
+ /**
65
+ * Compiles a jsii project with the TypeScript 7 programmatic API.
66
+ *
67
+ * The compiler owns the `tsconfig.json` handling (generating one from the
68
+ * project's `package.json`, or validating a user-provided one) and delegates the
69
+ * type analysis, assembly generation and emit to `buildProject`, which drives the
70
+ * out-of-process TypeScript 7 compiler.
71
+ */
58
72
  class Compiler {
59
73
  options;
60
- system;
61
- compilerHost;
62
74
  userProvidedTypeScriptConfig;
63
75
  tsconfig;
64
- rootFiles = [];
65
76
  configPath;
66
77
  projectRoot;
67
78
  constructor(options) {
@@ -73,75 +84,57 @@ class Compiler {
73
84
  const configFileName = options.typeScriptConfig ?? options.generateTypeScriptConfig ?? 'tsconfig.json';
74
85
  this.configPath = path.join(this.projectRoot, configFileName);
75
86
  this.userProvidedTypeScriptConfig = Boolean(options.typeScriptConfig);
76
- this.system = {
77
- ...ts.sys,
78
- getCurrentDirectory: () => this.projectRoot,
79
- createDirectory: (pth) => ts.sys.createDirectory(path.resolve(this.projectRoot, pth)),
80
- deleteFile: ts.sys.deleteFile && ((pth) => ts.sys.deleteFile(path.join(this.projectRoot, pth))),
81
- fileExists: (pth) => ts.sys.fileExists(path.resolve(this.projectRoot, pth)),
82
- getFileSize: ts.sys.getFileSize && ((pth) => ts.sys.getFileSize(path.resolve(this.projectRoot, pth))),
83
- readFile: (pth, encoding) => ts.sys.readFile(path.resolve(this.projectRoot, pth), encoding),
84
- watchFile: ts.sys.watchFile &&
85
- ((pth, callback, pollingInterval, watchOptions) => ts.sys.watchFile(path.resolve(this.projectRoot, pth), callback, pollingInterval, watchOptions)),
86
- writeFile: (pth, data, writeByteOrderMark) => ts.sys.writeFile(path.resolve(this.projectRoot, pth), data, writeByteOrderMark),
87
- };
88
87
  this.tsconfig = this.configureTypeScript();
89
- this.compilerHost = ts.createIncrementalCompilerHost(this.tsconfig.compilerOptions, this.system);
90
88
  }
89
+ /** The name of the tsconfig file this compiler builds from (relative to the project root). */
90
+ get configFileName() {
91
+ return path.relative(this.projectRoot, this.configPath);
92
+ }
93
+ /**
94
+ * Compiles the configured project once.
95
+ */
91
96
  /**
92
- * Compiles the configured program.
97
+ * Compiles the configured project once.
93
98
  *
94
- * @param files can be specified to override the standard source code location logic. Useful for example when testing "negatives".
99
+ * @param files can be specified to override the standard source code location
100
+ * logic (the generated tsconfig then lists exactly these files).
101
+ * Useful for example when testing "negatives".
95
102
  */
96
103
  emit(...files) {
97
- this.prepareForBuild(...files);
98
- return this.buildOnce();
99
- }
100
- async watch(opts) {
101
- this.prepareForBuild();
102
- const host = ts.createWatchCompilerHost(this.configPath, {
103
- ...this.tsconfig.compilerOptions,
104
- noEmitOnError: false,
105
- }, this.system, ts.createEmitAndSemanticDiagnosticsBuilderProgram, opts?.reportDiagnostics, opts?.reportWatchStatus, this.tsconfig.watchOptions);
106
- if (!host.getDefaultLibLocation) {
107
- throw new Error('No default library location was found on the TypeScript compiler host!');
104
+ if (this.options.watch) {
105
+ throw new utils.JsiiError('--watch is not supported by the TypeScript 7 based compiler', true);
108
106
  }
109
- const orig = host.afterProgramCreate;
110
- // This is a callback cascade, so it's "okay" to return an unhandled promise there. This may
111
- // cause an unhandled promise rejection warning, but that's not a big deal.
112
- //
113
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
114
- host.afterProgramCreate = (builderProgram) => {
115
- const startTime = Date.now();
116
- const emitResult = this.consumeProgram(builderProgram.getProgram(), host.getDefaultLibLocation());
117
- for (const diag of emitResult.diagnostics.filter((d) => d.code === exports.JSII_DIAGNOSTICS_CODE)) {
118
- utils.logDiagnostic(diag, this.projectRoot);
119
- }
120
- console.log(utils.formatCompilationSummary(emitResult.diagnostics, emitResult.emitSkipped, Date.now() - startTime));
121
- if (orig) {
122
- orig.call(host, builderProgram);
123
- }
124
- if (opts?.compilationComplete) {
125
- opts.compilationComplete(emitResult);
126
- }
127
- };
128
- const watch = ts.createWatchProgram(host);
129
- if (opts?.nonBlocking) {
130
- // In non-blocking mode, returns the handle to the TypeScript watch interface.
131
- return watch;
107
+ if (this.options.addDeprecationWarnings) {
108
+ throw new utils.JsiiError('--add-deprecation-warnings is not supported by the TypeScript 7 based compiler yet');
109
+ }
110
+ if (files.length > 0 && this.userProvidedTypeScriptConfig) {
111
+ throw new utils.JsiiError('Explicit source files cannot be combined with a user-provided tsconfig');
112
+ }
113
+ if (!this.userProvidedTypeScriptConfig) {
114
+ this.writeTypeScriptConfig(files);
115
+ }
116
+ const result = buildProject({
117
+ projectRoot: this.projectRoot,
118
+ projectInfo: this.options.projectInfo,
119
+ tsconfigFileName: this.configFileName,
120
+ generatedTsconfig: !this.userProvidedTypeScriptConfig,
121
+ stripDeprecated: this.options.stripDeprecated,
122
+ stripDeprecatedAllowListFile: this.options.stripDeprecatedAllowListFile,
123
+ compressAssembly: this.options.compressAssembly,
124
+ });
125
+ if (!result.emitSkipped) {
126
+ LOG.info(`assembled ${result.typeCount} types, emitted ${result.emittedFiles.length} files`);
132
127
  }
133
- // In blocking mode, returns a never-resolving promise.
134
- return new Promise(() => null);
128
+ const hasWarnings = result.diagnostics.some((d) => d.category === 0 /* Warning */);
129
+ return {
130
+ emitSkipped: result.emitSkipped || (this.options.failOnWarnings === true && hasWarnings),
131
+ diagnostics: result.diagnostics,
132
+ emittedFiles: result.emittedFiles,
133
+ };
135
134
  }
136
- /**
137
- * Prepares the project for build, by creating the necessary configuration
138
- * file(s), and assigning the relevant root file(s).
139
- *
140
- * @param files the files that were specified as input in the CLI invocation.
141
- */
142
135
  configureTypeScript() {
143
136
  if (this.userProvidedTypeScriptConfig) {
144
- const config = this.readTypeScriptConfig();
137
+ const config = (0, read_1.readTypeScriptConfigFile)(this.configPath);
145
138
  // emit a warning if validation is disabled
146
139
  const rules = this.options.validateTypeScriptConfig ?? tsconfig_1.TypeScriptConfigValidationRuleSet.NONE;
147
140
  if (rules === tsconfig_1.TypeScriptConfigValidationRuleSet.NONE) {
@@ -152,11 +145,7 @@ class Compiler {
152
145
  const configName = path.relative(this.projectRoot, this.configPath);
153
146
  try {
154
147
  const validator = new tsconfig_validator_1.TypeScriptConfigValidator(rules);
155
- validator.validate({
156
- ...config,
157
- // convert the internal format to the user format which is what the validator operates on
158
- compilerOptions: (0, compiler_options_1.convertForJson)(config.compilerOptions),
159
- });
148
+ validator.validate(config);
160
149
  }
161
150
  catch (error) {
162
151
  if (error instanceof validator_1.ValidationError) {
@@ -171,100 +160,10 @@ class Compiler {
171
160
  return this.buildTypeScriptConfig();
172
161
  }
173
162
  /**
174
- * Final preparations of the project for build.
175
- *
176
- * These are preparations that either
177
- * - must happen immediately before the build, or
178
- * - can be different for every build like assigning the relevant root file(s).
179
- *
180
- * @param files the files that were specified as input in the CLI invocation.
181
- */
182
- prepareForBuild(...files) {
183
- if (!this.userProvidedTypeScriptConfig) {
184
- this.writeTypeScriptConfig();
185
- }
186
- this.rootFiles = this.determineSources(files);
187
- }
188
- /**
189
- * Do a single build
190
- */
191
- buildOnce() {
192
- if (!this.compilerHost.getDefaultLibLocation) {
193
- throw new Error('No default library location was found on the TypeScript compiler host!');
194
- }
195
- const tsconf = this.tsconfig;
196
- const prog = ts.createIncrementalProgram({
197
- rootNames: this.rootFiles.concat(_pathOfLibraries(tsconf.compilerOptions, this.compilerHost)),
198
- options: tsconf.compilerOptions,
199
- // Make the references absolute for the compiler
200
- projectReferences: tsconf.references?.map((ref) => ({
201
- path: path.resolve(path.dirname(this.configPath), ref.path),
202
- })),
203
- host: this.compilerHost,
204
- });
205
- return this.consumeProgram(prog.getProgram(), this.compilerHost.getDefaultLibLocation());
206
- }
207
- consumeProgram(program, stdlib) {
208
- const diagnostics = [...ts.getPreEmitDiagnostics(program)];
209
- let hasErrors = false;
210
- if (!hasErrors && this.diagsHaveAbortableErrors(diagnostics)) {
211
- hasErrors = true;
212
- LOG.error('Compilation errors prevented the JSII assembly from being created');
213
- }
214
- // Do the "Assembler" part first because we need some of the analysis done in there
215
- // to post-process the AST
216
- const assembler = new assembler_1.Assembler(this.options.projectInfo, this.system, program, stdlib, {
217
- stripDeprecated: this.options.stripDeprecated,
218
- stripDeprecatedAllowListFile: this.options.stripDeprecatedAllowListFile,
219
- addDeprecationWarnings: this.options.addDeprecationWarnings,
220
- compressAssembly: this.options.compressAssembly,
221
- });
222
- try {
223
- const assmEmit = assembler.emit();
224
- if (!hasErrors && (assmEmit.emitSkipped || this.diagsHaveAbortableErrors(assmEmit.diagnostics))) {
225
- hasErrors = true;
226
- LOG.error('Type model errors prevented the JSII assembly from being created');
227
- }
228
- diagnostics.push(...assmEmit.diagnostics);
229
- }
230
- catch (e) {
231
- diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9997_UNKNOWN_ERROR.createDetached(e));
232
- hasErrors = true;
233
- }
234
- // Do the emit, but add in transformers which are going to replace real
235
- // comments with synthetic ones.
236
- const emit = program.emit(undefined, // targetSourceFile
237
- undefined, // writeFile
238
- undefined, // cancellationToken
239
- undefined, // emitOnlyDtsFiles
240
- assembler.customTransformers);
241
- diagnostics.push(...emit.diagnostics);
242
- if (!hasErrors && (emit.emitSkipped || this.diagsHaveAbortableErrors(emit.diagnostics))) {
243
- hasErrors = true;
244
- LOG.error('Compilation errors prevented the JSII assembly from being created');
245
- }
246
- // Some extra validation on the config.
247
- // Make sure that { "./.warnings.jsii.js": "./.warnings.jsii.js" } is in the set of
248
- // exports, if they are specified.
249
- if (this.options.addDeprecationWarnings && this.options.projectInfo.exports !== undefined) {
250
- const expected = `./${deprecation_warnings_1.WARNINGSCODE_FILE_NAME}`;
251
- const warningsExport = Object.entries(this.options.projectInfo.exports).filter(([k, v]) => k === expected && v === expected);
252
- if (warningsExport.length === 0) {
253
- hasErrors = true;
254
- diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0007_MISSING_WARNINGS_EXPORT.createDetached());
255
- }
256
- }
257
- return {
258
- emitSkipped: hasErrors,
259
- diagnostics: ts.sortAndDeduplicateDiagnostics(diagnostics),
260
- emittedFiles: emit.emittedFiles,
261
- };
262
- }
263
- /**
264
- * Build the TypeScript config object from jsii config
163
+ * Builds the TypeScript config object from jsii config.
265
164
  *
266
- * This is the object that will be written to disk
267
- * unless an existing tsconfig was provided.
165
+ * This is the object that will be written to disk unless an existing tsconfig
166
+ * is passed in.
268
167
  */
269
168
  buildTypeScriptConfig() {
270
169
  let references;
@@ -302,46 +201,28 @@ class Compiler {
302
201
  references: references?.map((p) => ({ path: p })),
303
202
  };
304
203
  }
305
- /**
306
- * Load the TypeScript config object from a provided file
307
- */
308
- readTypeScriptConfig() {
309
- const projectRoot = this.options.projectInfo.projectRoot;
310
- const { config, error } = ts.readConfigFile(this.configPath, ts.sys.readFile);
311
- if (error) {
312
- utils.logDiagnostic(error, projectRoot);
313
- throw new utils.JsiiError(`Failed to load tsconfig at ${this.configPath}`);
314
- }
315
- const extended = ts.parseJsonConfigFileContent(config, ts.sys, projectRoot);
316
- // the tsconfig parser adds this in, but it is not an expected compilerOption
317
- delete extended.options.configFilePath;
318
- return {
319
- compilerOptions: extended.options,
320
- watchOptions: extended.watchOptions,
321
- include: extended.fileNames,
322
- };
323
- }
324
204
  /**
325
205
  * Creates a `tsconfig.json` file to improve the IDE experience.
326
- *
327
- * @return the fully qualified path to the `tsconfig.json` file
328
206
  */
329
- writeTypeScriptConfig() {
207
+ writeTypeScriptConfig(files = []) {
330
208
  const commentKey = '_generated_by_jsii_';
331
209
  const commentValue = 'Generated by jsii - safe to delete, and ideally should be in .gitignore';
332
210
  this.tsconfig[commentKey] = commentValue;
333
211
  if (fs.existsSync(this.configPath)) {
334
- const { config: currentConfig } = ts.readConfigFile(this.configPath, ts.sys.readFile);
212
+ const currentConfig = (0, read_1.parseTsconfigJson)(fs.readFileSync(this.configPath, 'utf8'), this.configPath);
335
213
  if (currentConfig && !(commentKey in currentConfig)) {
336
214
  throw new utils.JsiiError(`A '${this.configPath}' file that was not generated by jsii is in ${this.options.projectInfo.projectRoot}. Aborting instead of overwriting.`);
337
215
  }
338
216
  }
339
- const outputConfig = {
340
- ...this.tsconfig,
341
- compilerOptions: (0, compiler_options_1.convertForJson)(this.tsconfig?.compilerOptions),
342
- };
217
+ const config = files.length > 0
218
+ ? {
219
+ ...this.tsconfig,
220
+ files: files.map((f) => path.relative(this.projectRoot, path.resolve(this.projectRoot, f))),
221
+ include: undefined,
222
+ }
223
+ : this.tsconfig;
343
224
  LOG.debug(`Creating or updating ${chalk_1.default.blue(this.configPath)}`);
344
- fs.writeFileSync(this.configPath, JSON.stringify(outputConfig, null, 2), 'utf8');
225
+ fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf8');
345
226
  }
346
227
  /**
347
228
  * Find all dependencies that look like TypeScript projects.
@@ -369,16 +250,15 @@ class Compiler {
369
250
  if (!tsconfigFile) {
370
251
  continue;
371
252
  }
372
- const { config: tsconfig } = ts.readConfigFile(tsconfigFile, this.system.readFile);
253
+ const tsconfig = (0, read_1.parseTsconfigJson)(fs.readFileSync(tsconfigFile, 'utf8'), tsconfigFile);
373
254
  // Add references to any TypeScript package we find that is 'composite' enabled.
374
255
  // Make it relative.
375
256
  if (tsconfig.compilerOptions?.composite) {
376
257
  ret.push(path.relative(this.options.projectInfo.projectRoot, path.dirname(tsconfigFile)));
377
258
  }
378
259
  else {
379
- // Not a composite package--if this package is in a node_modules directory, that is most
380
- // likely correct, otherwise it is most likely an error (heuristic here, I don't know how to
381
- // properly check this).
260
+ // Not a composite package--if this package is in a 'node_modules' directory, that is most
261
+ // likely correct, otherwise it is most likely an error (heuristic).
382
262
  if (tsconfigFile.includes('node_modules')) {
383
263
  LOG.warn('%s: not a composite TypeScript package, but it probably should be', path.dirname(tsconfigFile));
384
264
  }
@@ -387,41 +267,12 @@ class Compiler {
387
267
  return ret;
388
268
  }
389
269
  /**
390
- * Find source files using the same mechanism that the TypeScript compiler itself uses.
391
- *
392
- * Respects includes/excludes/etc.
393
- *
394
- * This makes it so that running 'typescript' and running 'jsii' has the same behavior.
395
- */
396
- determineSources(files) {
397
- // explicitly requested files
398
- if (files.length > 0) {
399
- return [...files];
400
- }
401
- // for user provided config we already have parsed the full list of files
402
- if (this.userProvidedTypeScriptConfig) {
403
- return [...(this.tsconfig.include ?? [])];
404
- }
405
- // finally get the file list for the generated config
406
- const parseConfigHost = parseConfigHostFromCompilerHost(this.compilerHost);
407
- const parsed = ts.parseJsonConfigFileContent(this.tsconfig, parseConfigHost, this.options.projectInfo.projectRoot);
408
- return [...parsed.fileNames];
409
- }
410
- /**
411
- * Resolve the given dependency name from the current package, and find the associated tsconfig.json location
412
- *
413
- * Because we have the following potential directory layout:
414
- *
415
- * package/node_modules/some_dependency
416
- * package/tsconfig.json
417
- *
418
- * We resolve symlinks and only find a "TypeScript" dependency if doesn't have 'node_modules' in
419
- * the path after resolving symlinks (i.e., if it's a peer package in the same monorepo).
270
+ * Find source files for a dependency that is also a sibling in a monorepo.
420
271
  *
421
- * Returns undefined if no such tsconfig could be found.
272
+ * This method is used to find project references.
422
273
  */
423
274
  findMonorepoPeerTsconfig(depName) {
424
- // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires
275
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
425
276
  const { builtinModules } = require('node:module');
426
277
  if ((builtinModules ?? []).includes(depName)) {
427
278
  // Can happen for modules like 'punycode' which are declared as dependency for polyfill purposes
@@ -433,7 +284,7 @@ class Compiler {
433
284
  if (!fs.existsSync(dep)) {
434
285
  return undefined;
435
286
  }
436
- // Resolve symlinks, to check if this is a monorepo peer
287
+ // Resolve symlinks, to get a correct relative path
437
288
  const dependencyRealPath = fs.realpathSync(dep);
438
289
  if (dependencyRealPath.split(path.sep).includes('node_modules')) {
439
290
  return undefined;
@@ -448,39 +299,266 @@ class Compiler {
448
299
  throw e;
449
300
  }
450
301
  }
451
- diagsHaveAbortableErrors(diags) {
452
- return diags.some((d) => d.category === ts.DiagnosticCategory.Error ||
453
- (this.options.failOnWarnings && d.category === ts.DiagnosticCategory.Warning && !(0, warnings_1.isSilenced)(d)));
454
- }
455
302
  }
456
303
  exports.Compiler = Compiler;
457
- function _pathOfLibraries(options, host) {
458
- // Prefer user libraries, falling back to a library based on the target if not supplied by the user.
459
- // This matches tsc behavior.
460
- const libs = options.lib ?? [ts.getDefaultLibFileName(options)];
461
- if (libs.length === 0) {
462
- return [];
304
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
305
+ const sortJson = require('sort-json');
306
+ /**
307
+ * Derive the entrypoint .ts from the project's declared `types` entry.
308
+ *
309
+ * Mirrors the classic Assembler's `mainFile` computation: start from the
310
+ * declared `types`, turn the `.d.ts`/`.js` into `.ts`, then — if an
311
+ * out-of-source build is configured (tsc `outDir`) — re-root the path from the
312
+ * `outDir` into the `rootDir`. This correctly handles both conventional
313
+ * `src`->`lib` layouts and in-place (`rootDir === outDir`) layouts.
314
+ */
315
+ function deriveEntry(projectRoot, projectInfo, rootDir, outDir) {
316
+ const dts = projectInfo.types ?? 'index.d.ts';
317
+ let mainFile = dts.replace(/\.d\.ts(x?)$/, '.ts$1').replace(/\.js$/, '.ts');
318
+ if (outDir != null) {
319
+ // strip the outDir prefix, then prepend rootDir (if any)
320
+ const rel = path.relative(outDir, mainFile);
321
+ mainFile = rootDir != null ? path.join(rootDir, rel) : rel;
463
322
  }
464
- const libDir = host.getDefaultLibLocation?.();
465
- if (!libDir) {
466
- throw new Error(`Compiler host doesn't have a default library directory available for ${libs.join(', ')}`);
323
+ return path.resolve(projectRoot, mainFile);
324
+ }
325
+ /**
326
+ * Run the ts backend for a package: produce and write the `.jsii` assembly.
327
+ */
328
+ function buildProject(options) {
329
+ const { projectRoot, projectInfo } = options;
330
+ let host = compiler_host_1.CompilerHost.open(options.projectRoot, options.tsconfigFileName);
331
+ let project = host.getProject();
332
+ let tsDiagnostics = collectTsDiagnostics(project.program);
333
+ let tscRootDir = projectInfo.tsc?.rootDir;
334
+ const tscOutDir = projectInfo.tsc?.outDir;
335
+ // TypeScript 7 no longer infers `rootDir` from the common directory of the
336
+ // sources when `outDir` is set (TS5011). The classic compiler relied on that
337
+ // inference for the output layout and recorded the inferred directory as
338
+ // `metadata.tscRootDir`; do the same for generated configs: infer it from the
339
+ // program's root files, write it into the tsconfig and open the project again.
340
+ if (options.generatedTsconfig && tscRootDir == null && tsDiagnostics.some((d) => d.code === 5011)) {
341
+ const inferred = inferRootDir(project.rootFileNames, projectRoot);
342
+ if (inferred != null) {
343
+ const tsconfigPath = path.join(projectRoot, options.tsconfigFileName ?? 'tsconfig.json');
344
+ const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8'));
345
+ tsconfig.compilerOptions = { ...tsconfig.compilerOptions, rootDir: inferred };
346
+ fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2), 'utf8');
347
+ host.close();
348
+ host = compiler_host_1.CompilerHost.open(options.projectRoot, options.tsconfigFileName);
349
+ project = host.getProject();
350
+ tsDiagnostics = collectTsDiagnostics(project.program);
351
+ tscRootDir = inferred;
352
+ }
353
+ }
354
+ const entry = deriveEntry(projectRoot, projectInfo, tscRootDir, tscOutDir);
355
+ try {
356
+ // Surface TypeScript compilation errors BEFORE assembling, with the same
357
+ // reject-on-error behaviour as the default backend: a program that does not
358
+ // compile must not produce an assembly.
359
+ if (tsDiagnostics.some((d) => d.category === diagnostic_1.DiagnosticCategory.Error)) {
360
+ return { typeCount: 0, emittedFiles: [], emitSkipped: true, diagnostics: tsDiagnostics };
361
+ }
362
+ const assembler = new assembler_1.Assembler(host.ts, project, {
363
+ packageJson: projectInfo.packageJson,
364
+ projectInfo,
365
+ projectRoot,
366
+ entry,
367
+ assemblyName: projectInfo.name,
368
+ defaultStability: projectInfo.stability,
369
+ stripDeprecated: options.stripDeprecated ?? !!projectInfo.packageJson['cdk-build']?.stripDeprecated,
370
+ stripDeprecatedAllowListFile: options.stripDeprecatedAllowListFile,
371
+ tscRootDir,
372
+ tscOutDir,
373
+ readme: loadReadme(projectRoot),
374
+ });
375
+ let assembly;
376
+ try {
377
+ assembly = assembler.assemble();
378
+ }
379
+ catch (e) {
380
+ // Same contract as the classic compiler: a failure while assembling is
381
+ // reported as a JSII9997 error diagnostic rather than crashing the build.
382
+ return {
383
+ typeCount: 0,
384
+ emittedFiles: [],
385
+ emitSkipped: true,
386
+ diagnostics: [
387
+ ...tsDiagnostics,
388
+ ...assembler.diagnostics,
389
+ jsii_diagnostic_1.JsiiDiagnostic.JSII_9997_UNKNOWN_ERROR.createDetached(e),
390
+ ],
391
+ };
392
+ }
393
+ const jsiiDiagnostics = assembler.diagnostics;
394
+ if (jsiiDiagnostics.some((d) => d.category === diagnostic_1.DiagnosticCategory.Error)) {
395
+ return {
396
+ typeCount: 0,
397
+ emittedFiles: [],
398
+ emitSkipped: true,
399
+ diagnostics: [...tsDiagnostics, ...jsiiDiagnostics],
400
+ };
401
+ }
402
+ if (process.env.JSII_TS7_TIMING) {
403
+ LOG.info(`ts doc-cache hits (RPCs avoided): ${assembler.docCacheHits}`);
404
+ }
405
+ // Write the assembly first (the parity artifact), reusing @jsii/spec's writer
406
+ // so the on-disk format (incl. the compressed file-redirect variant) matches
407
+ // the strada path exactly.
408
+ (0, spec_1.writeAssembly)(projectRoot, fingerprint(assembly), { compress: options.compressAssembly ?? false });
409
+ // Then emit JS/d.ts and inject jsii rtti (post-emit pass). An emit failure
410
+ // fails the build (emitSkipped + a synthetic diagnostic); the assembly file
411
+ // is left on disk to aid debugging, but the exit status reflects the error.
412
+ let emittedFiles = [];
413
+ try {
414
+ ({ emittedFiles } = (0, emitter_1.emitProject)(project, {
415
+ projectRoot,
416
+ assembly,
417
+ outDir: tscOutDir,
418
+ rootDir: tscRootDir,
419
+ }));
420
+ }
421
+ catch (err) {
422
+ LOG.error(`ts backend: emit pipeline failed: ${err.stack ?? err.message}`);
423
+ return {
424
+ assembly,
425
+ typeCount: Object.keys(assembly.types ?? {}).length,
426
+ emittedFiles: [],
427
+ emitSkipped: true,
428
+ diagnostics: [syntheticErrorDiagnostic(`ts backend: emit pipeline failed: ${err.message}`)],
429
+ };
430
+ }
431
+ return {
432
+ assembly,
433
+ typeCount: Object.keys(assembly.types ?? {}).length,
434
+ emittedFiles,
435
+ emitSkipped: false,
436
+ diagnostics: [...tsDiagnostics, ...jsiiDiagnostics], // non-error diagnostics (warnings/suggestions) pass through
437
+ };
438
+ }
439
+ finally {
440
+ if (process.env.JSII_TS7_TIMING) {
441
+ const t = host.getTimingInfo?.();
442
+ if (t?.totals) {
443
+ LOG.info(`ts timing: requests=${t.totals.requestCount} roundTripMs=${Math.round(t.totals.roundTripMs)} ` +
444
+ `serverTimeMs=${Math.round(t.totals.serverTimeMs ?? 0)} transportOverheadMs=${Math.round(t.totals.transportOverheadMs ?? 0)} ` +
445
+ `sent=${t.totals.bytesSent} recv=${t.totals.bytesReceived}`);
446
+ }
447
+ }
448
+ host.close();
467
449
  }
468
- return libs.map((name) => path.join(libDir, name));
469
450
  }
470
- function parseConfigHostFromCompilerHost(host) {
471
- // Copied from upstream
472
- // https://github.com/Microsoft/TypeScript/blob/9e05abcfd3f8bb3d6775144ede807daceab2e321/src/compiler/program.ts#L3105
473
- return {
474
- fileExists: (f) => host.fileExists(f),
475
- readDirectory(root, extensions, excludes, includes, depth) {
476
- if (host.readDirectory === undefined) {
477
- throw new Error("'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
451
+ /**
452
+ * Collect the program's pre-emit diagnostics (options, global, syntactic and
453
+ * semantic) from the program and map them to jsii's `Diagnostic` for the
454
+ * standard reporting pipeline.
455
+ */
456
+ function collectTsDiagnostics(program) {
457
+ const call = (name) => (typeof program[name] === 'function' ? program[name]() ?? [] : []);
458
+ const raw = [
459
+ ...call('getProgramDiagnostics'),
460
+ ...call('getGlobalDiagnostics'),
461
+ ...call('getSyntacticDiagnostics'),
462
+ ...call('getSemanticDiagnostics'),
463
+ ];
464
+ const texts = new Map();
465
+ const readSource = (fileName) => {
466
+ if (!texts.has(fileName)) {
467
+ try {
468
+ texts.set(fileName, fs.readFileSync(fileName, 'utf8'));
478
469
  }
479
- return host.readDirectory(root, extensions, excludes, includes, depth);
480
- },
481
- readFile: (f) => host.readFile(f),
482
- useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
483
- trace: host.trace ? (s) => host.trace(s) : undefined,
470
+ catch {
471
+ texts.set(fileName, undefined);
472
+ }
473
+ }
474
+ return texts.get(fileName);
484
475
  };
476
+ return raw.map((d) => toDiagnostic(d, readSource));
477
+ }
478
+ /**
479
+ * Map one TypeScript 7 API diagnostic (`{ fileName, pos, end, code, category, text }`)
480
+ * to jsii's `Diagnostic`. The file text is attached so the formatter renders the
481
+ * same `file:line:col - error TSxxxx:` layout, with source context, that the
482
+ * classic compiler produced. Exported for unit tests.
483
+ */
484
+ function toDiagnostic(d, readSource) {
485
+ const category = Object.values(diagnostic_1.DiagnosticCategory).includes(d.category)
486
+ ? d.category
487
+ : diagnostic_1.DiagnosticCategory.Error;
488
+ const fileName = typeof d.fileName === 'string' ? d.fileName : undefined;
489
+ const file = fileName != null ? { fileName, text: readSource(fileName) } : undefined;
490
+ const hasRange = file != null && typeof d.pos === 'number' && typeof d.end === 'number' && d.end >= d.pos;
491
+ return {
492
+ category,
493
+ code: typeof d.code === 'number' ? d.code : 0,
494
+ file,
495
+ start: hasRange ? d.pos : undefined,
496
+ length: hasRange ? d.end - d.pos : undefined,
497
+ messageText: typeof d.text === 'string' ? d.text : d.messageText ?? d.message ?? String(d),
498
+ };
499
+ }
500
+ /** An error diagnostic with no source location. */
501
+ function syntheticErrorDiagnostic(messageText) {
502
+ return {
503
+ category: diagnostic_1.DiagnosticCategory.Error,
504
+ code: 0,
505
+ file: undefined,
506
+ start: undefined,
507
+ length: undefined,
508
+ messageText,
509
+ };
510
+ }
511
+ /**
512
+ * Load and render the package README the same way the default backend does
513
+ * (including literate example inclusion), so `assembly.readme` matches.
514
+ */
515
+ function loadReadme(projectRoot) {
516
+ const fileName = fs.readdirSync(projectRoot).find((file) => file.toLocaleLowerCase() === 'readme.md');
517
+ if (fileName == null) {
518
+ return undefined;
519
+ }
520
+ const readmePath = path.join(projectRoot, fileName);
521
+ return {
522
+ markdown: literate
523
+ .includeAndRenderExamples(literate.loadFromFile(readmePath), literate.fileSystemLoader(projectRoot), projectRoot)
524
+ .join('\n'),
525
+ };
526
+ }
527
+ /**
528
+ * Port of the classic `inferRootDir`: the longest directory (relative to the
529
+ * project root) shared by all root files of the configuration, or `undefined`
530
+ * when they only share the project root itself.
531
+ */
532
+ function inferRootDir(rootFileNames, projectRoot) {
533
+ const directories = rootFileNames
534
+ .filter((fileName) => !fileName.split(path.sep).includes('node_modules'))
535
+ .map((fileName) => path.relative(projectRoot, path.dirname(fileName)))
536
+ .map(segmentPath);
537
+ if (directories.length === 0) {
538
+ return undefined;
539
+ }
540
+ const maxPrefix = Math.min(...directories.map((segments) => segments.length - 1));
541
+ let commonIndex = -1;
542
+ while (commonIndex < maxPrefix && new Set(directories.map((segments) => segments[commonIndex + 1])).size === 1) {
543
+ commonIndex++;
544
+ }
545
+ if (commonIndex < 0) {
546
+ return undefined;
547
+ }
548
+ return directories[0][commonIndex];
549
+ function segmentPath(fileName) {
550
+ const result = new Array();
551
+ for (let parent = fileName; parent !== path.dirname(parent); parent = path.dirname(parent)) {
552
+ result.unshift(parent);
553
+ }
554
+ return result;
555
+ }
556
+ }
557
+ /** Mirror of strada `_fingerprint`: sort keys, hash, stamp `fingerprint`. */
558
+ function fingerprint(assembly) {
559
+ delete assembly.fingerprint;
560
+ const sorted = sortJson(assembly);
561
+ const hash = crypto.createHash('sha256').update(JSON.stringify(sorted)).digest('base64');
562
+ return { ...sorted, fingerprint: hash };
485
563
  }
486
564
  //# sourceMappingURL=compiler.js.map