jsii 6.0.22-dev.1 → 7.1.0-dev.2

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/assembler.js CHANGED
@@ -32,2589 +32,2367 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
36
  exports.Assembler = void 0;
40
- const crypto = __importStar(require("node:crypto"));
37
+ exports.isInterfaceName = isInterfaceName;
38
+ exports.isStdlibDeclPath = isStdlibDeclPath;
39
+ exports.splitSummary = splitSummary;
40
+ /*
41
+ * ===========================================================================
42
+ * The jsii Assembler: reads a TypeScript program through the TypeScript 7
43
+ * programmatic API (the out-of-process `sync` client, see compiler-host.ts)
44
+ * and produces the `spec.Assembly` (`.jsii`).
45
+ *
46
+ * The assembler reads the raw TypeScript 7 handles directly rather than
47
+ * wrapping them to look like the in-process `ts.Program` / `ts.TypeChecker`
48
+ * of TypeScript 6; the structure and method names of the previous
49
+ * implementation (`_visitClass`, `_visitInterface`, `_visitEnum`,
50
+ * `_visitMethod`, `_visitProperty`, `_visitDocumentation`) are kept so the
51
+ * two can be compared. The `.jsii` it produces was compared field by field
52
+ * with the previous implementation's on aws-cdk-lib and the fixtures.
53
+ *
54
+ * Not produced here (yet): the JSII_xxxx validation diagnostics of the
55
+ * previous validator. TypeScript compilation errors are surfaced and fail the
56
+ * build (see compiler.ts).
57
+ * ===========================================================================
58
+ */
59
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return */
41
60
  const fs = __importStar(require("node:fs"));
42
61
  const path = __importStar(require("node:path"));
62
+ const zlib = __importStar(require("node:zlib"));
43
63
  const spec = __importStar(require("@jsii/spec"));
44
- const spec_1 = require("@jsii/spec");
45
- const chalk_1 = __importDefault(require("chalk"));
46
- const es6_1 = __importDefault(require("fast-deep-equal/es6"));
47
- const log4js = __importStar(require("log4js"));
48
- const ts = __importStar(require("typescript"));
49
- const Case = __importStar(require("./case"));
64
+ const find_utils_1 = require("./common/find-utils");
50
65
  const symbol_id_1 = require("./common/symbol-id");
51
- const directives_1 = require("./directives");
52
- const docs_1 = require("./docs");
53
66
  const helpers_1 = require("./helpers");
54
67
  const jsii_diagnostic_1 = require("./jsii-diagnostic");
55
68
  const literate = __importStar(require("./literate"));
56
- const bindings = __importStar(require("./node-bindings"));
57
69
  const project_info_1 = require("./project-info");
58
- const reserved_words_1 = require("./reserved-words");
59
- const sets_1 = require("./sets");
60
- const deprecated_remover_1 = require("./transforms/deprecated-remover");
61
- const deprecation_warnings_1 = require("./transforms/deprecation-warnings");
62
- const runtime_info_1 = require("./transforms/runtime-info");
63
- const utils_1 = require("./transforms/utils");
70
+ const type_analysis_1 = require("./type-analysis");
64
71
  const type_reference_1 = require("./type-reference");
65
- const type_tracker_1 = require("./type-tracker");
66
- const type_visitor_1 = require("./type-visitor");
67
- const utils_2 = require("./utils");
68
- const validator_1 = require("./validator");
69
72
  const version_1 = require("./version");
70
- // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
71
- const sortJson = require('sort-json');
72
- const LOG = log4js.getLogger('jsii/assembler');
73
73
  /**
74
- * The JSII Assembler consumes a ``ts.Program`` instance and emits a JSII assembly.
74
+ * Load the `.jsiirc.json` targets of a submodule: `<dir>/.jsiirc.json` for a
75
+ * directory module (`index.ts`), `.<name>.jsiirc.json` next to a file module.
76
+ * Invalid target configuration throws a JsiiError, like the classic compiler.
77
+ */
78
+ function loadSubmoduleTargetConfig(submoduleMain) {
79
+ const dirname = path.dirname(submoduleMain);
80
+ const basenameWithoutExtension = path.basename(submoduleMain).replace(/(\.d)?\.ts$/, '');
81
+ const jsiirc = basenameWithoutExtension === 'index'
82
+ ? path.resolve(dirname, '.jsiirc.json')
83
+ : path.resolve(dirname, `.${basenameWithoutExtension}.jsiirc.json`);
84
+ if (!fs.existsSync(jsiirc)) {
85
+ return undefined;
86
+ }
87
+ const data = JSON.parse(fs.readFileSync(jsiirc, 'utf-8'));
88
+ return (0, project_info_1.validateTargets)(data.targets);
89
+ }
90
+ /**
91
+ * Load the README for a submodule: `README.md` in the directory of a directory
92
+ * module, `<name>.README.md` next to a file module. Literate examples are
93
+ * rendered relative to the project root, like the package README.
94
+ */
95
+ function loadSubmoduleReadMe(submoduleMain, projectRoot) {
96
+ const fileBase = path.basename(submoduleMain).replace(/(\.d)?\.ts$/, '');
97
+ const readMeName = fileBase === 'index' ? 'README.md' : `${fileBase}.README.md`;
98
+ const readmePath = path.join(path.dirname(submoduleMain), readMeName);
99
+ if (!fs.existsSync(readmePath)) {
100
+ return undefined;
101
+ }
102
+ return {
103
+ markdown: literate
104
+ .includeAndRenderExamples(literate.loadFromFile(readmePath), literate.fileSystemLoader(path.dirname(readmePath)), projectRoot)
105
+ .join('\n'),
106
+ };
107
+ }
108
+ /** Port of the classic services' `findLinkNameEnd` (where a `{@link}` name ends inside its text). */
109
+ function findLinkNameEnd(text) {
110
+ let pos = text.indexOf('://');
111
+ if (pos === 0) {
112
+ while (pos < text.length && text.charCodeAt(pos) !== 124) {
113
+ pos++;
114
+ }
115
+ return pos;
116
+ }
117
+ if (text.indexOf('()') === 0) {
118
+ return 2;
119
+ }
120
+ if (text.charAt(0) === '<') {
121
+ let brackets = 0;
122
+ let i = 0;
123
+ while (i < text.length) {
124
+ if (text[i] === '<') {
125
+ brackets++;
126
+ }
127
+ if (text[i] === '>') {
128
+ brackets--;
129
+ }
130
+ i++;
131
+ if (!brackets) {
132
+ return i;
133
+ }
134
+ }
135
+ }
136
+ return 0;
137
+ }
138
+ /** Port of the classic services' `skipSeparatorFromLinkText`. */
139
+ function skipSeparatorFromLinkText(text) {
140
+ let pos = 0;
141
+ if (text.charCodeAt(pos++) === 124) {
142
+ while (pos < text.length && text.charCodeAt(pos) === 32) {
143
+ pos++;
144
+ }
145
+ return text.slice(pos);
146
+ }
147
+ return text;
148
+ }
149
+ /**
150
+ * Orders the constituents of a union the way the classic compiler emitted them.
151
+ *
152
+ * The classic assembler kept the checker's own order, in which the constituents
153
+ * are sorted by type id, i.e. by the order the types were created in. That order
154
+ * is not observable through the TypeScript 7 API, so it is approximated: the
155
+ * intrinsic primitives first (any, string, number, boolean), then named types in
156
+ * declaration order (program file order, then position in the file; types of
157
+ * dependencies before own types), then collections in their declared order, and
158
+ * nested unions ranked by their first constituent.
159
+ */
160
+ function sortUnionLikeClassic(refs, rankOfFqn) {
161
+ const rank = (ref) => {
162
+ if (spec.isPrimitiveTypeReference(ref)) {
163
+ const order = [
164
+ spec.PrimitiveType.Any,
165
+ spec.PrimitiveType.String,
166
+ spec.PrimitiveType.Number,
167
+ spec.PrimitiveType.Boolean,
168
+ spec.PrimitiveType.Date,
169
+ spec.PrimitiveType.Json,
170
+ ].indexOf(ref.primitive);
171
+ return order < 0 ? 10 : order;
172
+ }
173
+ if (spec.isNamedTypeReference(ref)) {
174
+ return rankOfFqn(ref.fqn);
175
+ }
176
+ if (spec.isCollectionTypeReference(ref)) {
177
+ // Arrays of primitives are instantiated early (the standard library uses
178
+ // them, after the primitives themselves); maps and other collections when
179
+ // first referenced, i.e. after the named types of the union. The relative
180
+ // order of the late collections is kept.
181
+ const element = ref.collection.elementtype;
182
+ if (ref.collection.kind === spec.CollectionKind.Array && spec.isPrimitiveTypeReference(element)) {
183
+ return 50 + rank(element);
184
+ }
185
+ return Number.MAX_SAFE_INTEGER / 2;
186
+ }
187
+ if (spec.isUnionTypeReference(ref)) {
188
+ return Math.min(...ref.union.types.map(rank));
189
+ }
190
+ return Number.MAX_SAFE_INTEGER;
191
+ };
192
+ return refs
193
+ .map((ref, index) => ({ ref, index, rank: rank(ref) }))
194
+ .sort((l, r) => l.rank - r.rank || l.index - r.index)
195
+ .map(({ ref }) => ref);
196
+ }
197
+ /**
198
+ * Member ordering of the classic assembler (`_sortMembers`): static members
199
+ * first, then immutable, then required, then lexicographical by name.
75
200
  */
201
+ function compareMembers(l, r) {
202
+ const key = (m) => [m.static ? '0' : '1', m.immutable ? '0' : '1', !m.optional ? '0' : '1', m.name].join('|');
203
+ return key(l).localeCompare(key(r));
204
+ }
76
205
  class Assembler {
77
- projectInfo;
78
- system;
206
+ options;
207
+ ts;
208
+ checker;
79
209
  program;
80
- stdlib;
81
- runtimeTypeInfoInjector;
82
- deprecatedRemover;
83
- warningsInjector;
84
- mainFile;
85
- tscRootDir;
86
- tscOutDir;
87
- compressAssembly;
88
- usedFeatures = new Set();
89
- _typeChecker;
210
+ project;
211
+ root;
212
+ assemblyName;
213
+ entry;
214
+ defaultStability;
215
+ currentStability;
216
+ types = {};
217
+ submodules = {};
218
+ typeFqnBySymbolId = new Map();
219
+ exported = [];
220
+ // Perf caches: memoize per-symbol doc reads (each is an RPC), keyed by
221
+ // the symbol's declaration coordinate (path:index), which is stable.
222
+ _jsDocTagsCache = new Map();
223
+ _docCommentCache = new Map();
224
+ _sourceTextCache = new Map();
225
+ _docCacheHits = 0;
226
+ /** Number of doc-read cache hits (RPCs avoided). Exposed for perf reporting. */
227
+ get docCacheHits() {
228
+ return this._docCacheHits;
229
+ }
230
+ /** The jsii diagnostics (warnings and errors) collected while assembling. */
231
+ get diagnostics() {
232
+ return this._diagnostics;
233
+ }
90
234
  _diagnostics = new Array();
91
- _deferred = new Array();
92
- _types = new Map();
93
- _packageInfoCache = new Map();
94
- /** Map of Symbol to namespace export Symbol */
95
- _submoduleMap = new Map();
235
+ /** The jsii features the assembly makes use of (classic `usedFeatures`). */
236
+ usedFeatures = new Set();
237
+ /** FQNs of classes without their own constructor, whose initializer is the base type's. */
238
+ inheritsInitializer = new Set();
239
+ /** Declaration rank of each own type FQN, for ordering union constituents (see _declarationRank). */
240
+ declarationRanks = new Map();
241
+ programFileIndex;
242
+ // external dependency assemblies (peerDependencies): name -> Set(type names)
243
+ externalDeps = new Map();
244
+ // full type records of external dependency assemblies, keyed by fqn (for
245
+ // datatype propagation across assembly boundaries)
246
+ externalTypeByFqn = new Map();
247
+ // dependency name -> (symbolId within that dependency -> fqn), the primary way
248
+ // foreign symbols are mapped back to the types of the assembly declaring them
249
+ externalFqnBySymbolId = new Map();
250
+ // dependency name -> its loaded assembly (metadata drives the symbolId path mapping)
251
+ externalAssemblies = new Map();
252
+ // real directory of each loaded dependency -> dependency name. Declarations are
253
+ // attributed to a dependency by path prefix, which also works when the package
254
+ // is reached through a symlink (workspaces, linked fixtures) and the checker
255
+ // reports the resolved path, where no `node_modules` segment is present.
256
+ externalDepDirs = new Map();
257
+ stripDeprecated;
258
+ stripAllowList;
259
+ // Type symbols dropped by --strip-deprecated. Unlike genuinely unexported
260
+ // (erased) bases, a stripped base is a *named* type that strada's
261
+ // DeprecatedRemover deletes post-assembly WITHOUT folding its members into
262
+ // subclasses — so member re-listing must not treat it as an erased base.
263
+ strippedTypeSymIds = new Set();
264
+ constructor(ts, project, options) {
265
+ this.options = options;
266
+ this.ts = ts;
267
+ this.project = project;
268
+ this.program = project.program;
269
+ this.checker = project.checker;
270
+ this.root = options.projectRoot;
271
+ this.assemblyName = options.assemblyName;
272
+ this.entry = options.entry;
273
+ this.defaultStability = options.defaultStability;
274
+ this.currentStability = options.defaultStability;
275
+ this.stripDeprecated = !!options.stripDeprecated;
276
+ if (options.stripDeprecatedAllowListFile && fs.existsSync(options.stripDeprecatedAllowListFile)) {
277
+ this.stripAllowList = new Set(fs
278
+ .readFileSync(options.stripDeprecatedAllowListFile, 'utf8')
279
+ .split('\n')
280
+ .map((l) => l.trim())
281
+ .filter(Boolean));
282
+ }
283
+ }
96
284
  /**
97
- * Submodule information
98
- *
99
- * Contains submodule information for all namespaces that have been seen
100
- * across all assemblies (this and dependencies).
101
- *
102
- * Filtered to local submodules only at time of writing the assembly out to disk.
285
+ * Build the assembly. Mirrors strada `Assembler.emit()`'s high-level flow:
286
+ * load dependency assemblies, walk module exports, register types, visit each.
103
287
  */
104
- _submodules = new Map();
105
- _typeTracker = new type_tracker_1.TypeTracker();
288
+ assemble() {
289
+ this._loadDependencyAssemblies();
290
+ const entrySf = this.program.getSourceFile(this.entry);
291
+ if (!entrySf) {
292
+ throw new Error(`ts: entrypoint not found: ${this.entry}`);
293
+ }
294
+ const moduleSymbol = this.checker.getSymbolAtLocation(entrySf);
295
+ const moduleExports = this.checker.getExportsOfModule(moduleSymbol);
296
+ this._registerModuleExports(moduleExports);
297
+ for (const { name, sym, decl, fqn } of this.exported) {
298
+ this._visitNode(name, sym, decl, fqn);
299
+ }
300
+ this._propagateDatatype();
301
+ return this._buildAssembly();
302
+ }
303
+ // -------------------------------------------------------------------------
304
+ // symbol / alias helpers
305
+ // -------------------------------------------------------------------------
306
+ _resolveAlias(sym) {
307
+ const { SymbolFlags } = this.ts;
308
+ let s = sym;
309
+ while ((s.flags & SymbolFlags.Alias) !== 0) {
310
+ s = this.checker.getAliasedSymbol(s);
311
+ }
312
+ return s;
313
+ }
106
314
  /**
107
- * @param projectInfo information about the package being assembled
108
- * @param program the TypeScript program to be assembled from
109
- * @param stdlib the directory where the TypeScript stdlib is rooted
315
+ * Whether a symbol is hidden from the jsii type model: marked `@internal`,
316
+ * named with a leading underscore, or ignored with `@jsii ignore` on every one
317
+ * of its declarations (the classic `_isPrivateOrInternal`).
110
318
  */
111
- constructor(projectInfo, system, program, stdlib, options = {}) {
112
- this.projectInfo = projectInfo;
113
- this.system = system;
114
- this.program = program;
115
- this.stdlib = stdlib;
116
- this._typeChecker = this.program.getTypeChecker();
117
- if (options.stripDeprecated) {
118
- let allowlistedDeprecations;
119
- if (options.stripDeprecatedAllowListFile) {
120
- if (!fs.existsSync(options.stripDeprecatedAllowListFile)) {
121
- throw new utils_2.JsiiError(`--strip-deprecated file not found: ${options.stripDeprecatedAllowListFile}`);
122
- }
123
- allowlistedDeprecations = new Set(fs.readFileSync(options.stripDeprecatedAllowListFile, 'utf8').split('\n'));
124
- }
125
- this.deprecatedRemover = new deprecated_remover_1.DeprecatedRemover(this._typeChecker, allowlistedDeprecations);
126
- }
127
- if (options.addDeprecationWarnings) {
128
- this.warningsInjector = new deprecation_warnings_1.DeprecationWarningsInjector(this._typeChecker, this._typeTracker);
129
- }
130
- this.compressAssembly = options.compressAssembly;
131
- const dts = projectInfo.types ?? 'index.d.ts';
132
- let mainFile = dts.replace(/\.d\.ts(x?)$/, '.ts$1');
133
- // If out-of-source build was configured (tsc's outDir and rootDir), the
134
- // main file's path needs to be re-rooted from the outDir into the rootDir.
135
- // outDir might be also be absolute, so we need to normalize it.
136
- this.tscOutDir = (0, helpers_1.normalizeConfigPath)(projectInfo.projectRoot, program.getCompilerOptions().outDir);
137
- if (this.tscOutDir != null) {
138
- mainFile = path.relative(this.tscOutDir, mainFile);
139
- // rootDir may be set explicitly or not. If not, inferRootDir replicates
140
- // tsc's behavior of using the longest prefix of all built source files.
141
- // rootDir might also be absolute (just like outDir), so we normalize it
142
- // to be relative to the package root. Otherwise the absolute path leaks
143
- // into the assembly's `metadata.tscRootDir`, which breaks the
144
- // reproducibility/fingerprint check for downstream consumers.
145
- this.tscRootDir = (0, helpers_1.normalizeConfigPath)(projectInfo.projectRoot, program.getCompilerOptions().rootDir ?? inferRootDir(program));
146
- if (this.tscRootDir != null) {
147
- mainFile = path.join(this.tscRootDir, mainFile);
148
- }
149
- }
150
- this.mainFile = path.resolve(projectInfo.projectRoot, mainFile);
151
- this.runtimeTypeInfoInjector = new runtime_info_1.RuntimeTypeInfoInjector(projectInfo.version);
152
- }
153
- get customTransformers() {
154
- return (0, utils_1.combinedTransformers)(this.deprecatedRemover?.customTransformers ?? {}, this.runtimeTypeInfoInjector.makeTransformers(), this.warningsInjector?.customTransformers ?? {});
319
+ _isInternal(sym) {
320
+ return (this._jsDocTags(sym).some((t) => t.name === 'internal') || sym.name.startsWith('_') || this._isIgnored(sym));
155
321
  }
156
322
  /**
157
- * Attempt emitting the JSII assembly for the program.
158
- *
159
- * @return the result of the assembly emission.
323
+ * Whether every declaration of the symbol carries the `@jsii ignore` directive.
324
+ * All declarations must be ignored so that a partially-ignored merged
325
+ * declaration stays a visible part of the public API, as in the classic
326
+ * compiler. The tags of a symbol are aggregated over its declarations, so a
327
+ * merged declaration is checked per declaration on the raw JSDoc text.
160
328
  */
161
- emit() {
162
- if (!this.projectInfo.description) {
163
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0001_PKG_MISSING_DESCRIPTION.createDetached());
329
+ _isIgnored(sym) {
330
+ const decls = sym.declarations ?? [];
331
+ if (decls.length === 0 || !this._jsDocTags(sym).some((t) => isIgnoreDirective(t))) {
332
+ return false;
164
333
  }
165
- if (!this.projectInfo.homepage) {
166
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0002_PKG_MISSING_HOMEPAGE.createDetached());
334
+ if (decls.length === 1) {
335
+ return true;
336
+ }
337
+ return decls.every((handle) => {
338
+ const block = this._leadingJsDocBlock(handle.resolve(this.project));
339
+ return block != null && this._jsDocLines(block).some((line) => /^@jsii\s+ignore(\s|$)/.test(line));
340
+ });
341
+ /** `@jsii ignore` (a `@jsii` tag whose directive text, on any of its lines, is `ignore`). */
342
+ function isIgnoreDirective(tag) {
343
+ if (tag.name !== 'jsii') {
344
+ return false;
345
+ }
346
+ const text = typeof tag.text === 'string' ? tag.text : (tag.text ?? []).map((p) => p.text).join('');
347
+ return text.split(/[\n,]/).some((part) => part.trim().split(/\s+/)[0] === 'ignore');
167
348
  }
168
- const readme = _loadReadme.call(this);
169
- if (readme == null) {
170
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0003_MISSING_README.createDetached());
349
+ }
350
+ _isDeprecated(sym) {
351
+ return this._jsDocTags(sym).some((t) => t.name === 'deprecated');
352
+ }
353
+ /**
354
+ * Memoized `symbol.getJsDocTags(checker)`. The same symbol's tags are consulted
355
+ * multiple times per member (isInternal + isDeprecated + _visitDocumentation),
356
+ * and each call is an out-of-process round-trip. Keyed by the symbol's first
357
+ * declaration coordinate `path:index` (a NodeHandle field readable WITHOUT a
358
+ * resolve() RPC and stable across re-materialization — unlike `symbol.id`,
359
+ * which is undefined/unstable here and made the previous cache inert). Results
360
+ * are value-identical to the uncached call (pure read), so parity is unaffected.
361
+ */
362
+ _jsDocTags(sym) {
363
+ const key = this._symbolDocKey(sym);
364
+ if (key == null) {
365
+ return sym.getJsDocTags(this.checker) ?? [];
171
366
  }
172
- const docs = _loadDocs.call(this);
173
- const sourceFile = this.program.getSourceFile(this.mainFile);
174
- if (sourceFile == null) {
175
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0004_COULD_NOT_FIND_ENTRYPOINT.createDetached(this.mainFile));
367
+ let tags = this._jsDocTagsCache.get(key);
368
+ if (tags === undefined) {
369
+ tags = sym.getJsDocTags(this.checker) ?? [];
370
+ this._jsDocTagsCache.set(key, tags);
176
371
  }
177
372
  else {
178
- this._registerDependenciesNamespaces(sourceFile);
179
- if (LOG.isTraceEnabled()) {
180
- LOG.trace(`Processing source file: ${chalk_1.default.blue(path.relative(this.projectInfo.projectRoot, sourceFile.fileName))}`);
181
- }
182
- const symbol = this._typeChecker.getSymbolAtLocation(sourceFile);
183
- if (symbol) {
184
- const moduleExports = this._typeChecker.getExportsOfModule(symbol);
185
- moduleExports.map((item) => this._registerNamespaces(item, this.projectInfo.projectRoot));
186
- for (const node of moduleExports) {
187
- const decl = node.declarations?.[0];
188
- if (decl == null) {
189
- continue;
190
- }
191
- this._visitNode(decl, new EmitContext([], this.projectInfo.stability));
192
- }
193
- }
373
+ this._docCacheHits++;
194
374
  }
195
- this.callDeferredsInOrder();
196
- this.validateTypesAgainstPositions();
197
- this.validateSubmoduleConfigs();
198
- // Skip emitting if any diagnostic message is an error
199
- if (this._diagnostics.find((diag) => diag.category === ts.DiagnosticCategory.Error) != null) {
200
- LOG.debug('Skipping emit due to errors.');
201
- try {
202
- return { diagnostics: this._diagnostics, emitSkipped: true };
203
- }
204
- finally {
205
- // Clearing ``this._diagnostics`` to allow contents to be garbage-collected.
206
- this._afterEmit();
375
+ return tags;
376
+ }
377
+ /**
378
+ * The documentation comment of a symbol with `{@link ...}` references rendered
379
+ * the way the classic language service did (`buildLinkParts`): a link whose
380
+ * name resolves keeps its text verbatim, `{@link Name text}`; a link that does
381
+ * not resolve (or uses a `#member` name, which the classic checker never
382
+ * resolved) is rendered as `{@link Name` + ' ' + `text}`, which is where the
383
+ * trailing space in `{@link Foo }` comes from. The TypeScript 7 checker renders
384
+ * links as plain text, so the raw JSDoc block is consulted when it has links.
385
+ */
386
+ _docCommentWithClassicLinks(sym) {
387
+ const comment = this._docComment(sym);
388
+ if (typeof comment !== 'string' || comment === '') {
389
+ return comment;
390
+ }
391
+ const decl = sym.declarations?.[0]?.resolve(this.project);
392
+ const block = decl ? this._leadingJsDocBlock(decl) : undefined;
393
+ if (!block) {
394
+ return comment;
395
+ }
396
+ // Only the comment part (before the first tag) belongs to the documentation comment.
397
+ const commentLines = [];
398
+ for (const line of this._jsDocLines(block)) {
399
+ if (/^@/.test(line)) {
400
+ break;
207
401
  }
208
- }
209
- const jsiiVersion = this.projectInfo.jsiiVersionFormat === 'short' ? version_1.SHORT_VERSION : version_1.VERSION;
210
- const assembly = {
211
- schema: spec.SchemaVersion.LATEST,
212
- name: this.projectInfo.name,
213
- version: this.projectInfo.version,
214
- description: this.projectInfo.description ?? this.projectInfo.name,
215
- license: this.projectInfo.license,
216
- keywords: this.projectInfo.keywords && Array.from(this.projectInfo.keywords),
217
- homepage: this.projectInfo.homepage ?? this.projectInfo.repository.url,
218
- author: this.projectInfo.author,
219
- contributors: this.projectInfo.contributors && [...this.projectInfo.contributors],
220
- repository: this.projectInfo.repository,
221
- dependencies: noEmptyDict({
222
- ...this.projectInfo.dependencies,
223
- ...this.projectInfo.peerDependencies,
224
- }),
225
- dependencyClosure: noEmptyDict(toDependencyClosure(this.projectInfo.dependencyClosure)),
226
- bundled: this.projectInfo.bundleDependencies,
227
- types: Object.fromEntries(this._types),
228
- submodules: noEmptyDict(toSubmoduleDeclarations(this.mySubmodules())),
229
- // Force this into shape
230
- targets: this.projectInfo.targets,
231
- metadata: {
232
- ...this.projectInfo.metadata,
233
- // Downstream consumers need these to map a symbolId in the outDir to a
234
- // symbolId in the rootDir. They cannot always be recovered from the
235
- // consumed package's `package.json` (e.g. when the package was built
236
- // with a user-provided `tsconfig.json` via `jsii.tsconfig`), so they
237
- // must be recorded in the assembly itself.
238
- tscRootDir: this.tscRootDir,
239
- tscOutDir: this.tscOutDir,
240
- },
241
- docs,
242
- readme,
243
- jsiiVersion,
244
- bin: this.projectInfo.bin,
245
- fingerprint: '<TBD>',
246
- usedFeatures: _assemblyFeatures(this.usedFeatures), // might be appended later
247
- };
248
- if (this.deprecatedRemover) {
249
- this._diagnostics.push(...this.deprecatedRemover.removeFrom(assembly));
250
- }
251
- if (this.warningsInjector) {
252
- const jsiiMetadata = {
253
- ...(assembly.metadata?.jsii ?? {}),
254
- ...{ compiledWithDeprecationWarnings: true },
255
- };
256
- if (assembly.metadata) {
257
- assembly.metadata.jsii = jsiiMetadata;
402
+ commentLines.push(line);
403
+ }
404
+ const rawComment = commentLines.join('\n');
405
+ if (!/\{@link(code|plain)?\b/.test(rawComment)) {
406
+ return comment;
407
+ }
408
+ const linkRe = /\{@(link|linkcode|linkplain)([^}\n]*)\}/g;
409
+ let result = comment;
410
+ let cursor = 0;
411
+ let rawRendered = rawComment;
412
+ let allFound = true;
413
+ let rawCursor = 0;
414
+ for (const m of rawComment.matchAll(linkRe)) {
415
+ // Anchor the search on the (end of the) raw text preceding this link, so a
416
+ // link text that also occurs earlier in the comment is not matched there.
417
+ const preceding = rawComment.slice(rawCursor, m.index).trimEnd().slice(-24).trimStart();
418
+ rawCursor = (m.index ?? 0) + m[0].length;
419
+ if (preceding) {
420
+ const anchor = result.indexOf(preceding, cursor);
421
+ if (anchor >= 0) {
422
+ cursor = anchor + preceding.length;
423
+ }
424
+ }
425
+ const kind = m[1];
426
+ const after = m[2].replace(/^\s+/, '');
427
+ const nm = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:#[A-Za-z_$][\w$]*)*/.exec(after);
428
+ let classic;
429
+ let modern;
430
+ if (!nm) {
431
+ classic = `{@${kind} ${after}}`;
432
+ modern = after;
258
433
  }
259
434
  else {
260
- assembly.metadata = { jsii: jsiiMetadata };
435
+ const name0 = nm[0];
436
+ const text = after.slice(name0.length);
437
+ const suffix = findLinkNameEnd(text);
438
+ const name = name0 + text.slice(0, suffix);
439
+ const rest = skipSeparatorFromLinkText(text.slice(suffix));
440
+ const resolved = !name0.includes('#') && this._resolvesLinkName(name0, decl);
441
+ if (resolved) {
442
+ classic = `{@${kind} ${name}${rest}}`;
443
+ }
444
+ else {
445
+ const separator = suffix === 0 || (text.charCodeAt(suffix) === 124 && !name.endsWith(' ')) ? ' ' : '';
446
+ classic = `{@${kind} ${name}${separator}${rest}}`;
447
+ }
448
+ modern = `${name0.replace(/#/g, '.')}${text}`;
261
449
  }
262
- this.warningsInjector.process(assembly, this.projectInfo);
263
- }
264
- const validator = new validator_1.Validator(this.projectInfo, assembly);
265
- const validationResult = validator.emit();
266
- // Inject detected features
267
- if (validationResult.usedFeatures) {
268
- for (const item of validationResult.usedFeatures) {
269
- this.usedFeatures.add(item);
450
+ rawRendered = rawRendered.replace(m[0], classic);
451
+ // Re-insert the braces where the TypeScript 7 rendering of this link is.
452
+ const at = result.indexOf(modern, cursor);
453
+ if (at < 0) {
454
+ allFound = false;
455
+ continue;
270
456
  }
271
- assembly.usedFeatures = _assemblyFeatures(this.usedFeatures);
272
- }
273
- if (!validationResult.emitSkipped) {
274
- const zipped = (0, spec_1.writeAssembly)(this.projectInfo.projectRoot, _fingerprint(assembly), {
275
- compress: this.compressAssembly ?? false,
276
- });
277
- LOG.trace(`${zipped ? 'Zipping' : 'Emitting'} assembly: ${chalk_1.default.blue(path.join(this.projectInfo.projectRoot, spec_1.SPEC_FILE_NAME))}`);
457
+ result = result.slice(0, at) + classic + result.slice(at + modern.length);
458
+ cursor = at + classic.length;
278
459
  }
460
+ // A link the TypeScript 7 rendering could not be located for (e.g. `{@link url | text}`
461
+ // is rendered as "text (url)"): fall back to the raw comment with the links rendered.
462
+ return allFound ? result : rawRendered.trim();
463
+ }
464
+ /** Whether a `{@link A.b.c}` name resolves at `location` (classic `getSymbolAtLocation` on the link name). */
465
+ _resolvesLinkName(name, location) {
466
+ const { SymbolFlags, SyntaxKind } = this.ts;
467
+ const parts = name.split('.');
279
468
  try {
280
- return {
281
- diagnostics: [...this._diagnostics, ...validationResult.diagnostics],
282
- emitSkipped: validationResult.emitSkipped,
283
- };
469
+ let sym = this.checker.resolveName(parts[0], SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value, location);
470
+ if (!sym) {
471
+ // Classic fallback for a bare name: a member of the enclosing class/interface.
472
+ let container = location;
473
+ while (container &&
474
+ container.kind !== SyntaxKind.ClassDeclaration &&
475
+ container.kind !== SyntaxKind.InterfaceDeclaration) {
476
+ container = container.parent;
477
+ }
478
+ if (container) {
479
+ const containerType = this.checker.getTypeAtLocation(container);
480
+ const containerSym = containerType?.getSymbol?.();
481
+ sym =
482
+ (containerType && this.checker.getPropertyOfType(containerType, parts[0])) ??
483
+ (containerSym && this.checker.getPropertyOfType(this.checker.getTypeOfSymbol(containerSym), parts[0]));
484
+ }
485
+ }
486
+ for (const part of parts.slice(1)) {
487
+ if (!sym) {
488
+ return false;
489
+ }
490
+ if ((sym.flags & SymbolFlags.Alias) !== 0) {
491
+ sym = this.checker.getAliasedSymbol(sym);
492
+ }
493
+ const exported = sym.getExports?.()?.get?.(part);
494
+ if (exported) {
495
+ sym = exported;
496
+ continue;
497
+ }
498
+ const staticType = this.checker.getTypeOfSymbol(sym);
499
+ const declaredType = this.checker.getDeclaredTypeOfSymbol(sym);
500
+ sym =
501
+ (staticType && this.checker.getPropertyOfType(staticType, part)) ??
502
+ (declaredType && this.checker.getPropertyOfType(declaredType, part));
503
+ }
504
+ return sym != null && (sym.declarations?.length ?? 0) > 0;
284
505
  }
285
- finally {
286
- this._afterEmit();
506
+ catch {
507
+ return false;
287
508
  }
288
- function _assemblyFeatures(usedFeatures) {
289
- return usedFeatures.size > 0 ? Array.from(usedFeatures).sort() : undefined;
509
+ }
510
+ /** Memoized `symbol.getDocumentationComment(checker)` (keyed by declaration coordinate). */
511
+ _docComment(sym) {
512
+ const key = this._symbolDocKey(sym);
513
+ if (key == null) {
514
+ return sym.getDocumentationComment(this.checker);
290
515
  }
291
- function _loadReadme() {
292
- // Search for `README.md` in a case-insensitive way
293
- const fileName = fs
294
- .readdirSync(this.projectInfo.projectRoot)
295
- .find((file) => file.toLocaleLowerCase() === 'readme.md');
296
- if (fileName == null) {
297
- return undefined;
298
- }
299
- const readmePath = path.join(this.projectInfo.projectRoot, fileName);
300
- return loadAndRenderReadme(readmePath, this.projectInfo.projectRoot);
516
+ let doc = this._docCommentCache.get(key);
517
+ if (doc === undefined) {
518
+ doc = sym.getDocumentationComment(this.checker) ?? null;
519
+ this._docCommentCache.set(key, doc);
301
520
  }
302
- function _loadDocs() {
303
- if (!this.projectInfo.stability && !this.projectInfo.deprecated) {
304
- return undefined;
305
- }
306
- const deprecated = this.projectInfo.deprecated;
307
- const stability = this.projectInfo.stability;
308
- return { deprecated, stability };
521
+ else {
522
+ this._docCacheHits++;
309
523
  }
524
+ return doc;
310
525
  }
311
- _afterEmit() {
312
- this._diagnostics = [];
313
- this._deferred = [];
314
- this._types.clear();
315
- this._submoduleMap.clear();
316
- this._submodules.clear();
317
- this._packageInfoCache.clear();
526
+ /** Stable per-symbol key from its first declaration's (path, index); undefined if none. */
527
+ _symbolDocKey(sym) {
528
+ const d0 = sym?.declarations?.[0];
529
+ if (!d0 || d0.path == null || d0.index == null) {
530
+ return undefined;
531
+ }
532
+ return `${d0.path}:${d0.index}`;
318
533
  }
319
534
  /**
320
- * Defer a callback until a (set of) types are available
321
- *
322
- * This is a helper function around _defer() which encapsulates the _dereference
323
- * action (which is basically the majority use case for _defer anyway).
324
- *
325
- * Will not invoke the function with any 'undefined's; an error will already have been emitted in
326
- * that case anyway.
327
- *
328
- * @param fqn FQN of the current type (the type that has a dependency on baseTypes)
329
- * @param baseTypes Array of type references to be looked up
330
- * @param referencingNode Node to report a diagnostic on if we fail to look up a type
331
- * @param cb Callback to be invoked with the Types corresponding to the TypeReferences in baseTypes
535
+ * Documentation is read per symbol: on TypeScript 7.1 the request-batching
536
+ * combinator was measured slower than individual requests for this workload.
537
+ * Kept as a no-op hook so call sites document where a prefetch would go.
332
538
  */
333
- _deferUntilTypesAvailable(fqn, baseTypes, referencingNode, cb) {
334
- // We can do this one eagerly
335
- if (baseTypes.length === 0) {
336
- cb();
337
- return;
539
+ _prefetchDocs(_syms) {
540
+ /* intentionally empty */
541
+ }
542
+ _shouldStrip(sym, fqn) {
543
+ if (!this.stripDeprecated || !this._isDeprecated(sym)) {
544
+ return false;
338
545
  }
339
- const baseFqns = baseTypes.flatMap((bt) => {
340
- if (typeof bt === 'string') {
341
- return [bt];
342
- }
343
- if (spec.isNamedTypeReference(bt)) {
344
- return [bt.fqn];
546
+ if (!this.stripAllowList) {
547
+ return true;
548
+ }
549
+ return this.stripAllowList.has(fqn);
550
+ }
551
+ // -------------------------------------------------------------------------
552
+ // external (peer-dependency) assembly resolution
553
+ // -------------------------------------------------------------------------
554
+ _loadDependencyAssemblies() {
555
+ const pkg = this.options.packageJson;
556
+ for (const dep of Object.keys(pkg.peerDependencies ?? {})) {
557
+ try {
558
+ // Resolved like the classic compiler (and independently of the package's
559
+ // `exports` map, which may not expose package.json).
560
+ const depDir = fs.realpathSync((0, find_utils_1.findDependencyDirectory)(dep, this.root));
561
+ this.externalDepDirs.set(depDir, dep);
562
+ let depJsii = JSON.parse(fs.readFileSync(path.join(depDir, '.jsii'), 'utf8'));
563
+ if (depJsii.schema === 'jsii/file-redirect') {
564
+ depJsii = JSON.parse(zlib.gunzipSync(fs.readFileSync(path.join(depDir, depJsii.filename))).toString('utf8'));
565
+ }
566
+ this.externalDeps.set(dep, new Set(Object.keys(depJsii.types ?? {}).map((f) => f.slice(depJsii.name.length + 1))));
567
+ const bySymbolId = new Map();
568
+ for (const [fqn, type] of Object.entries(depJsii.types ?? {})) {
569
+ this.externalTypeByFqn.set(fqn, type);
570
+ if (typeof type.symbolId === 'string') {
571
+ bySymbolId.set(type.symbolId, fqn);
572
+ }
573
+ }
574
+ this.externalFqnBySymbolId.set(dep, bySymbolId);
575
+ this.externalAssemblies.set(dep, depJsii);
345
576
  }
346
- return [];
347
- });
348
- this._defer(fqn, baseFqns, () => {
349
- const resolved = baseFqns
350
- .map((x) => this._dereference(x, referencingNode, 'used-in-syntax'))
351
- .filter((x) => x !== undefined);
352
- if (resolved.length > 0) {
353
- cb(...resolved);
577
+ catch {
578
+ /* not a jsii dependency */
354
579
  }
355
- });
356
- }
357
- /**
358
- * Defer checks for after the program has been entirely processed; useful for verifying type references that may not
359
- * have been discovered yet, and verifying properties about them.
360
- *
361
- * The callback is guaranteed to be executed only after all deferreds for all types in 'dependedFqns' have
362
- * been executed.
363
- *
364
- * @param fqn FQN of the current type.
365
- * @param dependedFqns List of FQNs of types this callback depends on. All deferreds for all
366
- * @param cb the function to be called in a deferred way. It will be bound with ``this``, so it can depend on using
367
- * ``this``.
368
- */
369
- _defer(fqn, dependedFqns, cb) {
370
- this._deferred.push({ fqn, dependedFqns, cb: cb.bind(this) });
580
+ }
371
581
  }
372
582
  /**
373
- * Obtains the ``spec.Type`` for a given ``spec.NamedTypeReference``.
374
- *
375
- * @param ref the type reference to be de-referenced
376
- *
377
- * @returns the de-referenced type, if it was found, otherwise ``undefined``.
583
+ * The (alias-resolved) symbol of a heritage-clause entry (`extends X` /
584
+ * `implements X`). Newer API clients materialize some resolved child nodes
585
+ * (e.g. the `expression` of ExpressionWithTypeArguments) as local-only
586
+ * objects that `getSymbolAtLocation` rejects, so prefer resolving the base
587
+ * TYPE at the heritage node itself and taking its symbol.
378
588
  */
379
- _dereference(ref, referencingNode, usedInSyntax) {
380
- if (typeof ref !== 'string') {
381
- ref = ref.fqn;
382
- }
383
- const [assm] = ref.split('.');
384
- let type;
385
- if (assm === this.projectInfo.name) {
386
- type = this._types.get(ref);
589
+ _heritageBaseSymbol(t) {
590
+ const viaExpression = this._symbolAtNodeSafe(t.expression);
591
+ if (viaExpression) {
592
+ return this._resolveAlias(viaExpression);
593
+ }
594
+ const type = this.checker.getTypeAtLocation(t);
595
+ const s = type?.getSymbol?.() ?? type?.symbol;
596
+ return s ? this._resolveAlias(s) : undefined;
597
+ }
598
+ /** `checker.getSymbolAtLocation` that tolerates local-only / missing nodes. */
599
+ _symbolAtNodeSafe(node) {
600
+ if (node == null) {
601
+ return undefined;
387
602
  }
388
- else {
389
- const assembly = this.projectInfo.dependencyClosure.find((dep) => dep.name === assm);
390
- type = assembly?.types?.[ref];
391
- // since we are exposing a type of this assembly in this module's public API,
392
- // we expect it to appear as a peer dependency instead of a normal dependency.
393
- if (assembly) {
394
- if (!(assembly.name in this.projectInfo.peerDependencies)) {
395
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_0005_MISSING_PEER_DEPENDENCY.create(referencingNode, // Cheating here for now, until the referencingNode can be made required
396
- assembly.name, ref));
397
- }
398
- }
603
+ try {
604
+ return this.checker.getSymbolAtLocation(node);
399
605
  }
400
- if (!type && usedInSyntax === 'used-in-syntax') {
401
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9002_UNRESOLVEABLE_TYPE.create(referencingNode, // Cheating here for now, until the referencingNode can be made required
402
- ref));
606
+ catch {
607
+ return undefined; // not a remote node handle in this API generation
403
608
  }
404
- return type;
609
+ }
610
+ /** The alias symbol of the type at a node (e.g. a TypeReference to a type alias). */
611
+ _aliasSymbolAt(node) {
612
+ const type = this.checker.getTypeAtLocation(node);
613
+ return type?.getAliasSymbol?.() ?? type?.aliasSymbol;
405
614
  }
406
615
  /**
407
- * Compute the JSII fully qualified name corresponding to a ``ts.Type`` instance. If for any reason a name cannot be
408
- * computed for the type, a marker is returned instead, and an ``ts.DiagnosticCategory.Error`` diagnostic is
409
- * inserted in the assembler context.
410
- *
411
- * @param type the type for which a JSII fully qualified name is needed.
412
- * @param typeAnnotationNode the type annotation for which this FQN is generated. This is used for attaching the error
413
- * marker. When there is no explicit type annotation (e.g: inferred method return type), the
414
- * preferred substitute is the "type-inferred" element's name.
415
- * @param typeUse the reason why this type was resolved (e.g: "return type")
416
- * @param isThisType whether this type was specified or inferred as "this" or not
417
- *
418
- * @returns the FQN of the type, or some "unknown" marker.
616
+ * The loaded jsii dependency a declaration path belongs to, if any: the
617
+ * dependency whose (real) directory is a prefix of the path, falling back to
618
+ * the `node_modules/<name>/` segment for paths that were not resolved.
419
619
  */
420
- _getFQN(type, typeAnnotationNode, typeUse, isThisType) {
421
- const sym = symbolFromType(type, this._typeChecker);
422
- const typeDeclaration = sym.valueDeclaration ?? sym.declarations?.[0];
423
- // Set to true to prevent further adding of Error diagnostics for known-bad reference
424
- let hasError = false;
425
- if (this._isPrivateOrInternal(sym)) {
426
- // Check if this type is "this" (explicit or inferred method return type).
427
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3001_EXPOSED_INTERNAL_TYPE.create(typeAnnotationNode, sym, isThisType, typeUse).addRelatedInformationIf(typeDeclaration, 'The referenced type is declared here'));
428
- hasError = true;
429
- }
430
- const tsName = this._typeChecker.getFullyQualifiedName(sym);
431
- const groups = /^"([^"]+)"\.(.*)$/.exec(tsName);
432
- if (!groups) {
433
- if (!hasError) {
434
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3001_EXPOSED_INTERNAL_TYPE.create(typeAnnotationNode, sym, isThisType, typeUse).addRelatedInformationIf(typeDeclaration, 'The referenced type is declared here'));
435
- hasError = true;
436
- }
437
- return tsName;
438
- }
439
- const [, modulePath, typeName] = groups;
440
- const pkg = this.findPackageInfo(modulePath);
441
- if (!pkg) {
442
- if (!hasError) {
443
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9003_UNRESOLVEABLE_MODULE.create(typeAnnotationNode, modulePath).addRelatedInformationIf(typeDeclaration, 'The referenced type is declared here'));
444
- hasError = true;
445
- }
446
- return `unknown.${typeName}`;
447
- }
448
- // If the symbol comes from an assembly whose submodules we've already
449
- // spidered (or from the current assembly), look up there. This relies
450
- // on an entry-point import of the library having been done first
451
- // (`import * as x from 'module-root';`)
452
- const submodule = this._submoduleMap.get(sym);
453
- if (submodule != null) {
454
- const submoduleNs = this._submodules.get(submodule).fqnResolutionPrefix;
455
- return `${submoduleNs}.${typeName}`;
456
- }
457
- // This is the fallback: in case we can't find a symbolId for the given
458
- // type, we're return this value. This is for backwards compatibility with
459
- // modules that haven't been compiled to have symbolId support. Those also
460
- // most likely won't be using submodules so this legacy guess will be correct.
461
- const fallbackFqn = `${pkg.name}.${typeName}`;
462
- // If the type is coming from the current module, we won't find it in a dependency
463
- if (pkg.name === this.projectInfo.name) {
464
- return fallbackFqn;
465
- }
466
- // Otherwise look up the symbol identifier in the dependency assemblies
467
- // This is now the preferred mechanism but we can't do this as the only mechanism,
468
- // as we may still have compile against very old assemblies that don't have a
469
- // symbol identifier table at all.
470
- const dep = this.projectInfo.dependencyClosure.find((d) => d.name === pkg.name);
471
- if (!dep) {
472
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9000_UNKNOWN_MODULE.create(typeAnnotationNode, pkg.name));
473
- return fallbackFqn;
474
- }
475
- const symbolId = (0, symbol_id_1.symbolIdentifier)(this._typeChecker, sym, {
476
- assembly: dep,
477
- });
478
- const fqn = (dep && symbolId ? symbolIdIndex(dep)[symbolId] : undefined) ?? fallbackFqn;
479
- if (!fqn || !this._dereference({ fqn }, sym.valueDeclaration, 'used-in-syntax')) {
480
- if (!hasError) {
481
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3002_USE_OF_UNEXPORTED_FOREIGN_TYPE.create(typeAnnotationNode, fqn ?? tsName, typeUse, pkg).addRelatedInformationIf(typeDeclaration, 'The referenced type is declared here'));
482
- hasError = true;
620
+ _dependencyOfPath(declPath) {
621
+ if (!declPath) {
622
+ return undefined;
623
+ }
624
+ for (const [dir, dep] of this.externalDepDirs) {
625
+ if (declPath === dir || declPath.startsWith(`${dir}/`)) {
626
+ return dep;
483
627
  }
484
628
  }
485
- return fqn;
629
+ const m = /node_modules\/((?:@[^/]+\/)?[^/]+)\//.exec(declPath);
630
+ return m && this.externalDeps.has(m[1]) ? m[1] : undefined;
486
631
  }
487
- /**
488
- * For all modules in the dependency closure, crawl their exports to register
489
- * the submodules they contain.
490
- *
491
- * @param entryPoint the main source file for the currently compiled module.
492
- */
493
- _registerDependenciesNamespaces(entryPoint) {
494
- for (const assm of this.projectInfo.dependencyClosure) {
495
- const resolved = ts.resolveModuleName(assm.name, entryPoint.fileName, this.program.getCompilerOptions(), ts.sys);
496
- // If we can't resolve the module name, simply ignore it (TypeScript compilation likely failed)
497
- if (resolved.resolvedModule == null) {
498
- continue;
632
+ _externalFqnOf(sym) {
633
+ const decl0 = sym.declarations?.[0];
634
+ if (!decl0) {
635
+ return undefined;
636
+ }
637
+ const dep = this._dependencyOfPath(decl0.path ?? '');
638
+ if (dep == null) {
639
+ return undefined;
640
+ }
641
+ // Primary: match the symbol's identifier against the symbolIds recorded in
642
+ // the dependency's assembly (the classic compiler's symbolIdentifier lookup).
643
+ // The declaration lives in the dependency's compiled output, so its path is
644
+ // mapped from tscOutDir back to tscRootDir first.
645
+ const symbolId = this._symbolIdOf(sym, this.externalAssemblies.get(dep));
646
+ if (symbolId != null) {
647
+ const fqn = this.externalFqnBySymbolId.get(dep)?.get(symbolId);
648
+ if (fqn != null) {
649
+ return fqn;
499
650
  }
500
- const source = this.program.getSourceFile(resolved.resolvedModule.resolvedFileName);
501
- const depMod = source && this._typeChecker.getSymbolAtLocation(source);
502
- // It's unlikely, but if we can't get the SourceFile here, ignore it (TypeScript compilation probably failed)
503
- if (depMod == null) {
504
- continue;
651
+ }
652
+ // Fallback for assemblies without symbolIds: a top-level type of that name.
653
+ if (this.externalDeps.get(dep).has(sym.name)) {
654
+ return `${dep}.${sym.name}`;
655
+ }
656
+ return undefined;
657
+ }
658
+ // -------------------------------------------------------------------------
659
+ // module walk + type registration (strada: _registerNamespaces / _visitNode)
660
+ // -------------------------------------------------------------------------
661
+ _registerModuleExports(moduleExports) {
662
+ const { SyntaxKind, SymbolFlags } = this.ts;
663
+ const candidates = new Map();
664
+ const visitedModules = new Set();
665
+ const collect = (mExports, prefix, moduleDir) => {
666
+ for (const e of mExports) {
667
+ const sym = this._resolveAlias(e);
668
+ const declH = sym.declarations?.[0];
669
+ if (!declH) {
670
+ continue;
671
+ }
672
+ const kind = declH.kind;
673
+ if ([SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration, SyntaxKind.EnumDeclaration].includes(kind)) {
674
+ if (this._dependencyOfPath(declH.path ?? '') != null) {
675
+ continue; // peer-dependency type: referenced externally, not owned
676
+ }
677
+ if (!candidates.has(sym.id)) {
678
+ candidates.set(sym.id, []);
679
+ }
680
+ // When the export is an alias, keep its own first declaration handle:
681
+ // it discriminates `export { X } from '...'` (ExportSpecifier with a
682
+ // module specifier — strada visits it in the CURRENT namespace and
683
+ // emits a duplicate entry) from `import { X } ...; export { X };`
684
+ // (strada's ExportSpecifier resolution lands on an ImportSpecifier,
685
+ // which no _visitNode branch handles — silently dropped).
686
+ const aliasDeclH = (e.flags & SymbolFlags.Alias) !== 0 ? e.declarations?.[0] : undefined;
687
+ candidates.get(sym.id).push({ name: e.name, prefix, moduleDir, sym, aliasDeclH });
688
+ }
689
+ else if (kind === SyntaxKind.SourceFile ||
690
+ (sym.flags & SymbolFlags.ValueModule) !== 0 ||
691
+ (sym.flags & SymbolFlags.NamespaceModule) !== 0) {
692
+ if (kind !== SyntaxKind.SourceFile && this._isIgnored(sym)) {
693
+ continue; // `@jsii ignore` on a namespace hides all of its nested declarations
694
+ }
695
+ const subFqn = `${prefix}.${e.name}`;
696
+ const key = `${sym.id}:${subFqn}`;
697
+ if (visitedModules.has(key)) {
698
+ continue;
699
+ }
700
+ visitedModules.add(key);
701
+ this.submodules[subFqn] = this._submoduleSpec(e, sym, kind === SyntaxKind.SourceFile);
702
+ const subDir = path.dirname(sym.declarations?.[0]?.path ?? moduleDir);
703
+ collect(this.checker.getExportsOfModule(sym), subFqn, subDir);
704
+ }
505
705
  }
506
- const depRoot = packageRoot(resolved.resolvedModule.resolvedFileName);
507
- for (const symbol of this._typeChecker.getExportsOfModule(depMod)) {
508
- this._registerNamespaces(symbol, depRoot);
706
+ };
707
+ collect(moduleExports, this.assemblyName, path.dirname(this.entry));
708
+ this._validateSubmoduleConfigs();
709
+ // FQN attribution: the *canonical* home of a type is the shortest module
710
+ // path that contains its declaration (the shortest-module-path "best
711
+ // candidate" selection); typeFqnBySymbolId (reference resolution) uses it.
712
+ // A symbol additionally exported from OTHER submodules (cross-submodule
713
+ // re-export, e.g. aws_docdb re-exporting aws_rds.CaCertificate) gets a full
714
+ // duplicate type entry under each such fqn — strada emits one entry per
715
+ // namespace visit.
716
+ const registrations = [];
717
+ for (const [, cands] of candidates) {
718
+ let best = cands[0];
719
+ let bestLen = -1;
720
+ for (const c of cands) {
721
+ const declPath = c.sym.declarations?.[0]?.path ?? '';
722
+ const dir = c.moduleDir.endsWith('/') ? c.moduleDir : c.moduleDir + '/';
723
+ const len = declPath.startsWith(dir) ? dir.length : -1;
724
+ if (len > bestLen) {
725
+ bestLen = len;
726
+ best = c;
727
+ }
728
+ }
729
+ const bestFqn = `${best.prefix}.${best.name}`;
730
+ registrations.push({ sym: best.sym, name: best.name, fqn: bestFqn });
731
+ const extraFqns = new Set([bestFqn]);
732
+ for (const c of cands) {
733
+ const fqn = `${c.prefix}.${c.name}`;
734
+ if (extraFqns.has(fqn)) {
735
+ continue;
736
+ }
737
+ // Only FOREIGN re-exports (candidate module dir does NOT contain the
738
+ // declaration, e.g. aws_docdb re-exporting a type declared in aws-rds/)
739
+ // produce a duplicate entry. Candidates from ancestor dirs (the package
740
+ // root re-exporting a submodule's type) collapse into the canonical fqn.
741
+ const declPath = c.sym.declarations?.[0]?.path ?? '';
742
+ const dir = c.moduleDir.endsWith('/') ? c.moduleDir : c.moduleDir + '/';
743
+ if (declPath.startsWith(dir)) {
744
+ continue;
745
+ }
746
+ // strada only emits the duplicate for `export { X } from '...'` — the
747
+ // alias declaration must be an ExportSpecifier whose ExportDeclaration
748
+ // carries a module specifier. Aliases that go through a local import
749
+ // (`import { X } ...; export { X };`) are dropped by strada's visitor.
750
+ if (!c.aliasDeclH || c.aliasDeclH.kind !== SyntaxKind.ExportSpecifier) {
751
+ continue;
752
+ }
753
+ const aliasDecl = c.aliasDeclH.resolve(this.project);
754
+ const exportDeclNode = aliasDecl?.parent?.parent;
755
+ if (exportDeclNode?.moduleSpecifier == null) {
756
+ continue;
757
+ }
758
+ extraFqns.add(fqn);
759
+ registrations.push({ sym: c.sym, name: c.name, fqn });
509
760
  }
510
761
  }
511
- function packageRoot(file) {
512
- const parent = path.dirname(file);
513
- if (path.basename(parent) === 'node_modules' || parent === file) {
514
- return file;
515
- }
516
- return packageRoot(parent);
762
+ // Batch-prefetch docs for all candidate type symbols (used by the
763
+ // isInternal/shouldStrip checks inside _registerType).
764
+ this._prefetchDocs(registrations.map((r) => r.sym));
765
+ for (const r of registrations) {
766
+ this._registerType(r.sym, r.name, r.fqn);
517
767
  }
518
768
  }
519
- _registerNamespaces(symbol, packageRoot) {
520
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
521
- if (declaration == null) {
522
- // Nothing to do here...
523
- return;
769
+ _registerType(sym, name, fqn) {
770
+ const { SyntaxKind } = this.ts;
771
+ const isFirst = !this.typeFqnBySymbolId.has(sym.id);
772
+ if (!isFirst) {
773
+ // Already registered under its canonical fqn. A *different* fqn means a
774
+ // cross-submodule re-export: emit a duplicate entry under that fqn too
775
+ // (nested-export recursion runs only for the canonical registration).
776
+ if (this.typeFqnBySymbolId.get(sym.id) === fqn || this.exported.some((e) => e.fqn === fqn)) {
777
+ return;
778
+ }
524
779
  }
525
- if (ts.isModuleDeclaration(declaration)) {
526
- // Looks like:
527
- //
528
- // export some_namespace {
529
- // ...
530
- // }
531
- //
532
- // No way to configure targets
533
- const { fqn, fqnResolutionPrefix } = qualifiedNameOf.call(this, symbol, true);
534
- this._submodules.set(symbol, {
535
- fqn,
536
- fqnResolutionPrefix,
537
- symbolId: (0, symbol_id_1.symbolIdentifier)(this._typeChecker, symbol),
538
- locationInModule: this.declarationLocation(declaration),
539
- });
540
- this._addToSubmodule(symbol, symbol, packageRoot);
780
+ if (this._isInternal(sym)) {
541
781
  return;
542
782
  }
543
- if (!ts.isNamespaceExport(declaration)) {
544
- // Nothing to do here...
783
+ if (this._shouldStrip(sym, fqn)) {
784
+ this.strippedTypeSymIds.add(sym.id);
545
785
  return;
546
786
  }
547
- const moduleSpecifier = declaration.parent.moduleSpecifier;
548
- if (moduleSpecifier == null || !ts.isStringLiteral(moduleSpecifier)) {
549
- // There is a grammar error here, so we'll let tsc report this for us.
787
+ const decl = sym.declarations?.[0]?.resolve(this.project);
788
+ if (!decl) {
550
789
  return;
551
790
  }
552
- const resolution = ts.resolveModuleName(moduleSpecifier.text, declaration.getSourceFile().fileName, this.program.getCompilerOptions(), this.system);
553
- if (resolution.resolvedModule == null) {
554
- // Unresolvable module... We'll let tsc report this for us.
555
- return;
791
+ if (isFirst) {
792
+ this.typeFqnBySymbolId.set(sym.id, fqn);
556
793
  }
557
- if (
558
- // We're not looking into a dependency's namespace exports, and the resolution says it's external
559
- (packageRoot === this.projectInfo.projectRoot && resolution.resolvedModule.isExternalLibraryImport) ||
560
- // Or the module resolves outside of the current dependency's tree entirely
561
- !isUnder(resolution.resolvedModule.resolvedFileName, packageRoot) ||
562
- // Or the module is under one the current dependency's node_modules subtree
563
- resolution.resolvedModule.resolvedFileName
564
- .split('/') // Separator is always '/', even on Windows
565
- .filter((entry) => entry === 'node_modules').length !==
566
- packageRoot.split('/').filter((entry) => entry === 'node_modules').length) {
567
- // External re-exports are "pure-javascript" sugar; they need not be
568
- // represented in the jsii Assembly since the types in there will be
569
- // resolved through dependencies.
794
+ this.exported.push({ name, sym, decl, fqn });
795
+ this._registerDeclarationRank(fqn, sym);
796
+ if (!isFirst) {
570
797
  return;
571
798
  }
572
- const sourceFile = this.program.getSourceFile(resolution.resolvedModule.resolvedFileName);
573
- const sourceModule = this._typeChecker.getSymbolAtLocation(sourceFile);
574
- // If there's no module, it's a syntax error, and tsc will have reported it for us.
575
- if (sourceModule) {
576
- if (symbol.name !== Case.camel(symbol.name) && symbol.name !== Case.snake(symbol.name)) {
577
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8004_SUBMOULE_NAME_CASING.create(declaration.name, symbol.name));
578
- }
579
- const { fqn, fqnResolutionPrefix } = qualifiedNameOf.call(this, symbol);
580
- const targets = loadSubmoduleTargetConfig(sourceFile.fileName);
581
- // There is no need to process the README file for submodules that are
582
- // external (i.e: from a dependency), as these will not be emitted in the
583
- // assembly. That'd be wasted effort, and could fail if the README file
584
- // refers to literate examples that are not packaged in the dependency.
585
- const readme = packageRoot === this.projectInfo.projectRoot
586
- ? loadSubmoduleReadMe(sourceFile.fileName, this.projectInfo.projectRoot)
587
- : undefined;
588
- this._submodules.set(symbol, {
589
- fqn,
590
- fqnResolutionPrefix,
591
- targets,
592
- readme,
593
- symbolId: (0, symbol_id_1.symbolIdentifier)(this._typeChecker, symbol),
594
- locationInModule: this.declarationLocation(declaration),
595
- });
596
- this._addToSubmodule(symbol, sourceModule, packageRoot);
597
- }
598
- function qualifiedNameOf(sym, inlineNamespace = false) {
599
- if (this._submoduleMap.has(sym)) {
600
- const parent = this._submodules.get(this._submoduleMap.get(sym));
601
- const fqn = `${parent.fqn}.${sym.name}`;
602
- return {
603
- fqn,
604
- fqnResolutionPrefix: inlineNamespace ? parent.fqnResolutionPrefix : fqn,
605
- };
606
- }
607
- const symbolLocation = sym.getDeclarations()?.[0]?.getSourceFile()?.fileName;
608
- const pkgInfo = symbolLocation ? this.findPackageInfo(symbolLocation) : undefined;
609
- const assemblyName = pkgInfo?.name ?? this.projectInfo.name;
610
- const fqn = `${assemblyName}.${sym.name}`;
611
- return {
612
- fqn,
613
- fqnResolutionPrefix: inlineNamespace ? this.projectInfo.name : fqn,
614
- };
615
- }
616
- function loadSubmoduleTargetConfig(submoduleMain) {
617
- const dirname = path.dirname(submoduleMain);
618
- const basenameWithoutExtension = path.basename(submoduleMain).replace(/\.ts$/, '');
619
- let jsiirc;
620
- if (basenameWithoutExtension === 'index') {
621
- jsiirc = path.resolve(submoduleMain, '..', '.jsiirc.json');
622
- }
623
- else {
624
- jsiirc = path.resolve(dirname, `.${basenameWithoutExtension}.jsiirc.json`);
625
- }
626
- if (!jsiirc || !fs.existsSync(jsiirc)) {
627
- return undefined;
799
+ // nested exported types (namespaces on a class/interface)
800
+ const nested = sym.getExports?.();
801
+ if (nested && nested.size) {
802
+ for (const [, nsym0] of nested) {
803
+ const nsym = this._resolveAlias(nsym0);
804
+ const nDeclH = nsym.declarations?.[0];
805
+ if (!nDeclH) {
806
+ continue;
807
+ }
808
+ if ([SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration, SyntaxKind.EnumDeclaration].includes(nDeclH.kind)) {
809
+ this._registerType(nsym, nsym.name, `${fqn}.${nsym.name}`);
810
+ }
628
811
  }
629
- const data = JSON.parse(fs.readFileSync(jsiirc, 'utf-8'));
630
- return (0, project_info_1.validateTargets)(data.targets);
631
- }
632
- /**
633
- * Load the README for the given submodule
634
- *
635
- * If the submodule is loaded from a complete directory (determined by the 'main'
636
- * file ending in `index.[d.]ts`, then we load `README.md` in that same directory.
637
- *
638
- * If the submodule is loaded from a file, like `mymodule.[d.]ts`, we will load
639
- * `mymodule.README.md`.
640
- */
641
- function loadSubmoduleReadMe(submoduleMain, projectRoot) {
642
- const fileBase = path.basename(submoduleMain).replace(/(\.d)?\.ts$/, '');
643
- const readMeName = fileBase === 'index' ? 'README.md' : `${fileBase}.README.md`;
644
- const fullPath = path.join(path.dirname(submoduleMain), readMeName);
645
- return loadAndRenderReadme(fullPath, projectRoot);
646
812
  }
647
813
  }
648
814
  /**
649
- * Registers Symbols to a particular submodule. This is used to associate
650
- * declarations exported by an `export * as ns from 'moduleLike';` statement
651
- * so that they can subsequently be correctly namespaced.
815
+ * The assembly entry for a submodule (classic `_registerNamespaces`): the
816
+ * location of the `export * as ns from '...'` (or `export namespace ns`)
817
+ * declaration, its symbolId and, for module-file submodules, the targets
818
+ * configured in the module's `.jsiirc.json` and its README.
652
819
  *
653
- * @param ns the symbol that identifies the submodule.
654
- * @param moduleLike the module-like symbol bound to the submodule.
655
- * @param packageRoot the root of the package being traversed.
820
+ * @param exportSym the (alias) symbol the submodule is exported as
821
+ * @param moduleSym the resolved module-like symbol
822
+ * @param isModuleFile whether the submodule is a source file (vs an inline namespace)
656
823
  */
657
- _addToSubmodule(ns, moduleLike, packageRoot) {
658
- // For each symbol exported by the moduleLike, map it to the ns submodule.
659
- for (const symbol of this._typeChecker.getExportsOfModule(moduleLike)) {
660
- if (this._submoduleMap.has(symbol)) {
661
- const currNs = this._submoduleMap.get(symbol);
662
- // Checking if there's been two submodules exporting the same symbol,
663
- // which is illegal. We can tell if the currently registered symbol has
664
- // a different name than the one we're currently trying to register in.
665
- if (currNs.name !== ns.name) {
666
- const currNsDecl = currNs.valueDeclaration ?? currNs.declarations?.[0];
667
- const nsDecl = ns.valueDeclaration ?? ns.declarations?.[0];
668
- // Make sure the error message always lists causes in the same order
669
- const refs = [
670
- { decl: currNsDecl, name: currNs.name },
671
- { decl: nsDecl, name: ns.name },
672
- ].sort(({ name: l }, { name: r }) => l.localeCompare(r));
673
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3003_SYMBOL_IS_EXPORTED_TWICE.create(_nameOrDeclarationNode(symbol), refs[0].name, refs[1].name)
674
- .addRelatedInformationIf(refs[0].decl, `Symbol is exported under the "${refs[0].name}" submodule`)
675
- .addRelatedInformationIf(refs[1].decl, `Symbol is exported under the "${refs[1].name}" submodule`));
676
- }
677
- // Found two re-exports, which is odd, but they use the same submodule,
678
- // so it's probably okay? That's likely a tsc error, which will have
679
- // been reported for us already anyway.
680
- continue;
681
- }
682
- this._submoduleMap.set(symbol, ns);
683
- // If the exported symbol has any declaration, and that delcaration is of
684
- // an entity that can have nested declarations of interest to jsii
685
- // (classes, interfaces, enums, modules), we need to also associate those
686
- // nested symbols to the submodule (or they won't be named correctly!)
687
- const decl = symbol.declarations?.[0];
688
- if (decl != null) {
689
- if (ts.isClassDeclaration(decl) || ts.isInterfaceDeclaration(decl) || ts.isEnumDeclaration(decl)) {
690
- const type = this._typeChecker.getTypeAtLocation(decl);
691
- if (isSingleValuedEnum(type, this._typeChecker)) {
692
- // type.symbol !== symbol, because symbol is the enum itself, but
693
- // since it's single-valued, the TypeChecker will only show us the
694
- // value's symbol later on.
695
- this._submoduleMap.set(type.symbol, ns);
696
- }
697
- if (type.symbol.exports) {
698
- // eslint-disable-next-line no-await-in-loop
699
- this._addToSubmodule(ns, symbol, packageRoot);
700
- }
701
- }
702
- else if (ts.isModuleDeclaration(decl)) {
703
- // eslint-disable-next-line no-await-in-loop
704
- this._registerNamespaces(symbol, packageRoot);
705
- }
706
- else if (ts.isNamespaceExport(decl)) {
707
- // eslint-disable-next-line no-await-in-loop
708
- this._registerNamespaces(symbol, packageRoot);
709
- }
710
- }
824
+ _submoduleSpec(exportSym, moduleSym, isModuleFile) {
825
+ // Namespace exports (`export * as ns`) and inline namespaces carry their own
826
+ // declaration; a plain module file (SourceFile) has no meaningful position.
827
+ const declH = exportSym.declarations?.[0] ?? moduleSym.declarations?.[0];
828
+ const decl = declH && declH.kind !== this.ts.SyntaxKind.SourceFile ? declH.resolve(this.project) : undefined;
829
+ const result = {
830
+ ...(decl ? { locationInModule: this._locationOf(decl) } : {}),
831
+ ...(isModuleFile ? { symbolId: this._symbolIdOf(moduleSym) } : { symbolId: this._symbolIdOf(exportSym) }),
832
+ };
833
+ if (!isModuleFile) {
834
+ return result;
711
835
  }
836
+ const submoduleMain = moduleSym.declarations?.[0]?.path;
837
+ if (submoduleMain == null) {
838
+ return result;
839
+ }
840
+ const targets = loadSubmoduleTargetConfig(submoduleMain);
841
+ const readme = loadSubmoduleReadMe(submoduleMain, this.root);
842
+ return { ...result, ...(targets ? { targets } : {}), ...(readme ? { readme } : {}) };
712
843
  }
713
844
  /**
714
- * Register exported types in ``this.types``.
715
- *
716
- * @param node a node found in a module
717
- * @param namePrefix the prefix for the types' namespaces
845
+ * Make sure that no 2 submodules are emitting into the same target namespaces
846
+ * (classic `validateSubmoduleConfigs`).
718
847
  */
719
- // eslint-disable-next-line complexity
720
- _visitNode(node, context) {
721
- if (ts.isNamespaceExport(node)) {
722
- // export * as ns from 'module';
723
- // Note: the "ts.NamespaceExport" refers to the "export * as ns" part of
724
- // the statement only. We must refer to `node.parent` in order to be able
725
- // to access the module specifier ("from 'module'") part.
726
- const symbol = this._typeChecker.getSymbolAtLocation(node.parent.moduleSpecifier);
727
- if (LOG.isTraceEnabled()) {
728
- LOG.trace(`Entering submodule: ${chalk_1.default.cyan([...context.namespace, symbol.name].join('.'))}`);
729
- }
730
- const nsContext = context.appendNamespace(node.name.text);
731
- const allTypes = this._typeChecker.getExportsOfModule(symbol).flatMap((child) => {
732
- const decl = child.declarations?.[0];
733
- if (decl == null) {
734
- return [];
735
- }
736
- return this._visitNode(decl, nsContext);
737
- });
738
- if (LOG.isTraceEnabled()) {
739
- LOG.trace(`Leaving submodule: ${chalk_1.default.cyan([...context.namespace, symbol.name].join('.'))}`);
740
- }
741
- return allTypes;
742
- }
743
- if (ts.isExportSpecifier(node)) {
744
- // This is what happens when one does `export { Symbol } from "./location";`
745
- // ExportSpecifier: ~~~~~~
746
- const resolvedSymbol = this._typeChecker.getExportSpecifierLocalTargetSymbol(node);
747
- const decl = resolvedSymbol?.valueDeclaration ?? resolvedSymbol?.declarations?.[0];
748
- if (!decl) {
749
- // A grammar error, compilation will already have failed
750
- return [];
751
- }
752
- return this._visitNode(decl, context);
753
- }
754
- if ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) === 0) {
755
- return [];
756
- }
757
- // Early exit if the declaration is marked with `@jsii ignore`. We resolve the
758
- // symbol and require *every* declaration to be ignored (see `_isIgnored`) so
759
- // this stays consistent with how references are resolved; otherwise a
760
- // partially-ignored merged declaration would be dropped here but treated as
761
- // public elsewhere. Without this, deriving from a `Partial<T>` would also
762
- // raise spurious compiler errors on an ignored declaration.
763
- const nodeSymbol = this._typeChecker.getSymbolAtLocation(ts.getNameOfDeclaration(node) ?? node);
764
- const isIgnored = nodeSymbol != null
765
- ? this._isIgnored(nodeSymbol)
766
- : directives_1.Directives.of(node, (diag) => this._diagnostics.push(diag)).ignore != null;
767
- if (isIgnored) {
768
- return [];
769
- }
770
- let jsiiType;
771
- if (ts.isClassDeclaration(node) && _isExported(node)) {
772
- // export class Name { ... }
773
- this._validateHeritageClauses(node.heritageClauses);
774
- jsiiType = this._visitClass(this._typeChecker.getTypeAtLocation(node), context);
775
- if (jsiiType) {
776
- this.registerExportedClassFqn(node, jsiiType.fqn);
777
- }
778
- }
779
- else if (ts.isInterfaceDeclaration(node) && _isExported(node)) {
780
- // export interface Name { ... }
781
- this._validateHeritageClauses(node.heritageClauses);
782
- jsiiType = this._visitInterface(this._typeChecker.getTypeAtLocation(node), context);
783
- }
784
- else if (ts.isEnumDeclaration(node) && _isExported(node)) {
785
- // export enum Name { ... }
786
- jsiiType = this._visitEnum(this._typeChecker.getTypeAtLocation(node), context);
787
- }
788
- else if (ts.isModuleDeclaration(node)) {
789
- // export namespace name { ... }
790
- const name = node.name.getText();
791
- const symbol = this._typeChecker.getSymbolAtLocation(node.name);
792
- if (LOG.isTraceEnabled()) {
793
- LOG.trace(`Entering namespace: ${chalk_1.default.cyan([...context.namespace, name].join('.'))}`);
794
- }
795
- const nsContext = context.appendNamespace(node.name.getText());
796
- const allTypes = this._typeChecker.getExportsOfModule(symbol).flatMap((prop) => {
797
- const decl = prop.declarations?.[0];
798
- if (decl == null) {
799
- return [];
848
+ _validateSubmoduleConfigs() {
849
+ const byLanguage = { dotnet: {}, java: {}, python: {}, go: {} };
850
+ const pick = {
851
+ dotnet: (t) => t?.dotnet?.namespace,
852
+ java: (t) => t?.java?.package,
853
+ python: (t) => t?.python?.module,
854
+ go: (t) => t?.go?.packageName,
855
+ };
856
+ for (const [fqn, submodule] of Object.entries(this.submodules)) {
857
+ for (const language of Object.keys(byLanguage)) {
858
+ const key = pick[language](submodule.targets);
859
+ if (key) {
860
+ (byLanguage[language][key] ??= []).push(fqn);
800
861
  }
801
- return this._visitNode(decl, nsContext);
802
- });
803
- if (LOG.isTraceEnabled()) {
804
- LOG.trace(`Leaving namespace: ${chalk_1.default.cyan([...context.namespace, name].join('.'))}`);
805
862
  }
806
- return allTypes;
807
863
  }
808
- else {
809
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9998_UNSUPPORTED_NODE.create(ts.getNameOfDeclaration(node) ?? node, node.kind));
810
- }
811
- if (!jsiiType) {
812
- return [];
813
- }
814
- // If symbolId hasn't been set yet, set it here
815
- if (!jsiiType.symbolId) {
816
- jsiiType.symbolId = this.getSymbolId(node);
817
- }
818
- // Verify the declaration does not collide with a submodule at the same level in the hierarchy.
819
- // Submodules get case-adjusted per target language, so names cannot collide with case-variations.
820
- // We only check submodules and types with a shared parent namespace. Symbols at different nesting
821
- // levels should not conflict with each other. E.g. "pkg.MyType" and "pkg.sub.my_type" are okay.
822
- const typeFqnPrefix = (0, utils_2.parentFqn)(jsiiType.fqn);
823
- for (const [submodule, submoduleSpec] of this._submodules.entries()) {
824
- // Only check submodules that share the same parent namespace as the type
825
- if (typeFqnPrefix !== (0, utils_2.parentFqn)(submoduleSpec.fqn)) {
826
- continue;
827
- }
828
- // We build common variations of the submodule name to simulate what they would be called in various target languages.
829
- // This is not entirely accurate because submodules may actually be renamed via .jsiirc files.
830
- // It is however a good enough approximation for the compiler.
831
- const candidates = Array.from(new Set([submodule.name, Case.camel(submodule.name), Case.pascal(submodule.name), Case.snake(submodule.name)]));
832
- if (candidates.some((name) => name === jsiiType.name)) {
833
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5011_SUBMODULE_NAME_CONFLICT.create(ts.getNameOfDeclaration(node) ?? node, submodule.name, jsiiType.name, candidates).addRelatedInformationIf(_nameOrDeclarationNode(submodule), 'This is the conflicting submodule declaration'));
834
- }
835
- }
836
- if (LOG.isInfoEnabled()) {
837
- LOG.info(`Registering JSII ${chalk_1.default.magenta(jsiiType.kind)}: ${chalk_1.default.green(jsiiType.fqn)}`);
838
- }
839
- this._types.set(jsiiType.fqn, jsiiType);
840
- jsiiType.locationInModule = this.declarationLocation(node);
841
- const type = this._typeChecker.getTypeAtLocation(node);
842
- if (type.symbol.exports) {
843
- const nestedContext = context.appendNamespace(type.symbol.name);
844
- const visitedNodes = this._typeChecker
845
- .getExportsOfModule(type.symbol)
846
- .filter((s) => s.declarations)
847
- .flatMap((exportedNode) => {
848
- const decl = exportedNode.valueDeclaration ?? exportedNode.declarations?.[0];
849
- if (decl == null) {
850
- return [];
851
- }
852
- return [this._visitNode(decl, nestedContext)];
853
- });
854
- for (const nestedTypes of visitedNodes) {
855
- for (const nestedType of nestedTypes) {
856
- if (nestedType.namespace !== nestedContext.namespace.join('.')) {
857
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5012_NAMESPACE_IN_TYPE.create(ts.getNameOfDeclaration(node) ?? node, jsiiType.fqn, nestedType.namespace));
858
- }
864
+ for (const [language, namespaces] of Object.entries(byLanguage)) {
865
+ for (const [namespace, modules] of Object.entries(namespaces)) {
866
+ if (modules.length > 1) {
867
+ this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_4010_SUBMODULE_NAMESPACE_CONFLICT.create(undefined, language, namespace, modules));
859
868
  }
860
869
  }
861
870
  }
862
- return [jsiiType];
863
- }
864
- getSymbolId(node) {
865
- return (0, symbol_id_1.symbolIdentifier)(this._typeChecker, this._typeChecker.getTypeAtLocation(node).symbol);
866
871
  }
867
- _validateHeritageClauses(clauses) {
868
- if (clauses == null || clauses.length === 0) {
869
- // Nothing to do.
870
- return;
871
- }
872
- for (const clause of clauses) {
873
- for (const node of clause.types) {
874
- const parentType = this._typeChecker.getTypeAtLocation(node);
875
- if (parentType.symbol == null) {
876
- // The parent type won't have a symbol if it's an "error type" inserted by the type checker when the original
877
- // code contains a compilation error. In such cases, the TypeScript compiler will already have reported about
878
- // the incoherent declarations, so we'll just not re-validate it there (we'd fail anyway).
872
+ /**
873
+ * Records the inheritance relationships of members and the jsii features the
874
+ * assembly uses, then returns the sorted feature list (or `undefined` when
875
+ * there is none; classic `_assemblyFeatures`).
876
+ *
877
+ * This is the data-producing half of the classic validator's
878
+ * `_inheritanceDoesNotChangeContracts` pass: every member of a class that
879
+ * redeclares a member of a base class gets `overrides` set to that base, and
880
+ * members (own or inherited) that implement an interface member get
881
+ * `overrides` set to that interface, with class overrides taking precedence.
882
+ * `class-covariant-overrides` is recorded when an override changes the type
883
+ * of a non-static member in an allowed covariant way (immutable properties and
884
+ * method return types only). The diagnostics half of that pass (contract
885
+ * violations) is not performed here.
886
+ */
887
+ _finalizeInheritance() {
888
+ const assembly = { name: this.assemblyName, types: this.types };
889
+ const dereference = (0, type_reference_1.createTypeResolver)(assembly, [
890
+ ...this.options.projectInfo.dependencyClosure,
891
+ ...this.externalAssemblies.values(),
892
+ ]);
893
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
894
+ const overrideFromBase = (member, type, pick, isCovariant) => {
895
+ const baseType = type.base != null ? dereference(type.base) : undefined;
896
+ if (baseType == null) {
897
+ return false;
898
+ }
899
+ const overridden = pick(baseType)?.find((m) => m.name === member.name);
900
+ if (overridden == null) {
901
+ return overrideFromBase(member, baseType, pick, isCovariant);
902
+ }
903
+ if (isCovariant(member, overridden)) {
904
+ this.usedFeatures.add('class-covariant-overrides');
905
+ }
906
+ member.overrides = baseType.fqn;
907
+ return true;
908
+ };
909
+ const implementationOf = (member, type, pick) => {
910
+ if (!type.interfaces?.length) {
911
+ // Abstract classes may not directly implement all members, need to check their supertypes...
912
+ if (spec.isClassType(type) && type.base && type.abstract) {
913
+ const base = dereference(type.base);
914
+ return base != null && implementationOf(member, base, pick);
915
+ }
916
+ return false;
917
+ }
918
+ for (const iface of type.interfaces) {
919
+ const ifaceType = dereference(iface);
920
+ if (ifaceType == null) {
879
921
  continue;
880
922
  }
881
- // For some reason, we cannot trust parentType.isClassOrInterface()
882
- const badDecl = parentType.symbol.declarations?.find((decl) => !ts.isClassDeclaration(decl) && // <-- local classes
883
- !ts.isInterfaceDeclaration(decl) && // <-- local interfaces
884
- !ts.isModuleDeclaration(decl));
885
- if (badDecl != null) {
886
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3004_INVALID_SUPERTYPE.create(node, clause, badDecl).addRelatedInformation(badDecl, 'The invalid super type is declared here.'));
923
+ if (pick(ifaceType)?.some((m) => m.name === member.name)) {
924
+ // A class override has higher precedence than an initial implementation.
925
+ member.overrides = member.overrides ?? ifaceType.fqn;
926
+ return true;
927
+ }
928
+ if (implementationOf(member, ifaceType, pick)) {
929
+ return true;
887
930
  }
888
931
  }
889
- }
890
- }
891
- declarationLocation(node) {
892
- const file = node.getSourceFile();
893
- const line = ts.getLineAndCharacterOfPosition(file, node.getStart()).line;
894
- const filename = path.normalize(path.relative(this.projectInfo.projectRoot, file.fileName)).replace(/\\/g, '/');
895
- return {
896
- filename,
897
- line: line + 1,
932
+ return false;
898
933
  };
899
- }
900
- _processBaseInterfaces(fqn, baseTypes) {
901
- const erasedBases = new Array();
902
- if (!baseTypes) {
903
- return { erasedBases };
904
- }
905
- const result = new Array();
906
- const baseInterfaces = new Set();
907
- const processBaseTypes = (types) => {
908
- for (const iface of types) {
909
- // base is private/internal, so we continue recursively with it's own bases
910
- if (this._isPrivateOrInternal(iface.symbol) || isInternalSymbol(iface.symbol)) {
911
- erasedBases.push(iface);
912
- if (!isInternalSymbol(iface.symbol)) {
913
- const bases = iface.getBaseTypes();
914
- if (bases) {
915
- processBaseTypes(bases);
916
- }
934
+ // Own members plus the members inherited from base classes (copied, so the
935
+ // inherited entries are not mutated), like the classic `_allImplementations`.
936
+ const allImplementations = (type, pick) => {
937
+ const result = [...(pick(type) ?? [])];
938
+ const known = new Set(result.map((m) => m.name));
939
+ if (spec.isClassType(type) && type.base) {
940
+ const base = dereference(type.base);
941
+ for (const member of base ? allImplementations(base, pick) : []) {
942
+ if (!known.has(member.name)) {
943
+ result.push({ ...member });
944
+ known.add(member.name);
917
945
  }
918
- continue;
919
946
  }
920
- baseInterfaces.add(iface);
921
947
  }
948
+ return result;
922
949
  };
923
- processBaseTypes(baseTypes);
924
- const typeRefs = Array.from(baseInterfaces).map((iface) => {
925
- const decl = iface.symbol.valueDeclaration;
926
- const typeRef = this._typeReference(iface, decl, 'base interface');
927
- return { decl, typeRef };
928
- });
929
- for (const { decl, typeRef } of typeRefs) {
930
- if (!spec.isNamedTypeReference(typeRef)) {
931
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3005_TYPE_USED_AS_INTERFACE.create(decl, typeRef));
932
- continue;
950
+ // Initializers of classes without their own constructor: copy the base type's
951
+ // (base types first, so chains of such classes resolve).
952
+ const resolveInitializer = (fqn, seen = new Set()) => {
953
+ const type = this.types[fqn];
954
+ if (type == null || !this.inheritsInitializer.has(fqn) || seen.has(fqn)) {
955
+ return;
956
+ }
957
+ seen.add(fqn);
958
+ this.inheritsInitializer.delete(fqn);
959
+ if (type.base != null && this.inheritsInitializer.has(type.base)) {
960
+ resolveInitializer(type.base, seen);
961
+ }
962
+ const baseType = type.base != null ? dereference(type.base) : undefined;
963
+ if (baseType?.initializer != null) {
964
+ type.initializer = JSON.parse(JSON.stringify(baseType.initializer));
965
+ }
966
+ else {
967
+ delete type.initializer;
968
+ }
969
+ };
970
+ for (const fqn of [...this.inheritsInitializer]) {
971
+ resolveInitializer(fqn);
972
+ }
973
+ const methodCovariant = (actual, expected) => !same(actual.returns, expected.returns) &&
974
+ !actual.static &&
975
+ (0, type_analysis_1.isAllowedCovariantSubtype)(actual.returns?.type, expected.returns?.type, dereference);
976
+ const propertyCovariant = (actual, expected) => !same(actual.type, expected.type) &&
977
+ !actual.static &&
978
+ !!actual.immutable &&
979
+ (0, type_analysis_1.isAllowedCovariantSubtype)(actual.type, expected.type, dereference);
980
+ for (const type of Object.values(this.types)) {
981
+ if (spec.isClassType(type)) {
982
+ for (const method of type.methods ?? []) {
983
+ overrideFromBase(method, type, (t) => t.methods, methodCovariant);
984
+ }
985
+ for (const property of type.properties ?? []) {
986
+ overrideFromBase(property, type, (t) => t.properties, propertyCovariant);
987
+ }
933
988
  }
934
- this._deferUntilTypesAvailable(fqn, [typeRef], decl, (deref) => {
935
- if (!spec.isInterfaceType(deref)) {
936
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3005_TYPE_USED_AS_INTERFACE.create(decl, typeRef));
989
+ if (spec.isClassOrInterfaceType(type) && (type.interfaces?.length ?? 0) > 0) {
990
+ for (const method of allImplementations(type, (t) => t.methods)) {
991
+ implementationOf(method, type, (t) => t.methods);
937
992
  }
938
- });
939
- result.push(typeRef);
993
+ for (const property of allImplementations(type, (t) => t.properties)) {
994
+ implementationOf(property, type, (t) => t.properties);
995
+ }
996
+ }
940
997
  }
941
- return {
942
- interfaces: result.length === 0 ? undefined : result,
943
- erasedBases,
944
- };
998
+ return this.usedFeatures.size > 0 ? Array.from(this.usedFeatures).sort() : undefined;
945
999
  }
946
- // eslint-disable-next-line complexity
947
- _visitClass(type, ctx) {
948
- if (LOG.isTraceEnabled()) {
949
- LOG.trace(`Processing class: ${chalk_1.default.gray(ctx.namespace.join('.'))}.${chalk_1.default.cyan(type.symbol.name)}`);
950
- }
951
- if (_hasInternalJsDocTag(type.symbol)) {
952
- return undefined;
1000
+ /**
1001
+ * Declaration rank of a type FQN for union ordering: own types by (program file
1002
+ * order, position in file); types of dependencies before them, by name.
1003
+ */
1004
+ _declarationRank(fqn) {
1005
+ const own = this.declarationRanks.get(fqn);
1006
+ if (own != null) {
1007
+ return own;
953
1008
  }
954
- this._warnAboutReservedWords(type.symbol);
955
- const fqn = `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${type.symbol.name}`;
956
- if (Case.pascal(type.symbol.name) !== type.symbol.name) {
957
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8000_PASCAL_CASED_TYPE_NAMES.create(type.symbol.valueDeclaration.name ??
958
- type.symbol.valueDeclaration ??
959
- type.symbol.declarations?.[0], type.symbol.name));
1009
+ if (this.externalTypeByFqn.has(fqn)) {
1010
+ const foreign = [...this.externalTypeByFqn.keys()].sort();
1011
+ return 1000 + foreign.indexOf(fqn);
960
1012
  }
961
- const classDeclaration = type.symbol.valueDeclaration;
962
- for (const typeParam of classDeclaration.typeParameters ?? []) {
963
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1006_GENERIC_TYPE.create(typeParam));
1013
+ return Number.MAX_SAFE_INTEGER;
1014
+ }
1015
+ _registerDeclarationRank(fqn, sym) {
1016
+ if (this.programFileIndex == null) {
1017
+ const files = this.project.program.getSourceFileNames();
1018
+ this.programFileIndex = new Map(files.map((f, i) => [f, i]));
964
1019
  }
965
- const jsiiType = bindings.setClassRelatedNode({
966
- assembly: this.projectInfo.name,
1020
+ const d0 = sym.declarations?.[0];
1021
+ const file = (d0?.path != null ? this.programFileIndex.get(d0.path) : undefined) ?? this.programFileIndex.size;
1022
+ this.declarationRanks.set(fqn, 1_000_000 + file * 1_000_000 + (d0?.index ?? 0));
1023
+ }
1024
+ /**
1025
+ * The symbolId of a symbol, computed by the same `symbolIdentifier` the
1026
+ * classic compiler (and jsii-rosetta) use: the path is made relative to the
1027
+ * package the declaration lives in, with the package's `jsii.outdir` and, when
1028
+ * an assembly is given, its tscOutDir -> tscRootDir mapping applied.
1029
+ */
1030
+ _symbolIdOf(sym, assembly) {
1031
+ return (0, symbol_id_1.symbolIdentifier)(this.checker, sym, { assembly });
1032
+ }
1033
+ // -------------------------------------------------------------------------
1034
+ // per-type dispatch (strada: _visitNode)
1035
+ // -------------------------------------------------------------------------
1036
+ _visitNode(name, sym, decl, fqn) {
1037
+ const { SyntaxKind } = this.ts;
1038
+ const jsiiType = {
1039
+ assembly: this.assemblyName,
967
1040
  fqn,
968
- kind: spec.TypeKind.Class,
969
- name: type.symbol.name,
970
- namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
971
- docs: this._visitDocumentation(type.symbol, ctx).docs,
972
- }, classDeclaration);
973
- if (_isAbstract(type.symbol, jsiiType)) {
974
- jsiiType.abstract = true;
1041
+ kind: '',
1042
+ locationInModule: this._locationOf(decl),
1043
+ name,
1044
+ };
1045
+ // Classic: the namespace is the FQN between the assembly name and the type
1046
+ // name (submodules and enclosing types), absent for top-level types.
1047
+ const namespace = fqn
1048
+ .slice(this.assemblyName.length + 1)
1049
+ .split('.')
1050
+ .slice(0, -1)
1051
+ .join('.');
1052
+ if (namespace) {
1053
+ jsiiType.namespace = namespace;
1054
+ }
1055
+ const docs = this._visitDocumentation(sym);
1056
+ if (docs) {
1057
+ jsiiType.docs = docs;
1058
+ }
1059
+ this.currentStability = docs?.stability ?? this.defaultStability;
1060
+ this._withDefaultDocs(jsiiType);
1061
+ const symbolId = this._symbolIdOf(sym);
1062
+ if (symbolId) {
1063
+ jsiiType.symbolId = symbolId;
1064
+ }
1065
+ if (decl.kind === SyntaxKind.EnumDeclaration) {
1066
+ this._visitEnum(sym, decl, fqn, jsiiType);
1067
+ }
1068
+ else if (decl.kind === SyntaxKind.InterfaceDeclaration) {
1069
+ this._visitInterface(sym, decl, name, jsiiType);
975
1070
  }
976
- const erasedBases = new Array();
977
- for (let base of type.getBaseTypes() ?? []) {
978
- if (jsiiType.base) {
979
- // Ignoring this - there has already been a compilation error generated by tsc here.
1071
+ else {
1072
+ this._visitClass(sym, decl, jsiiType);
1073
+ }
1074
+ this.types[fqn] = jsiiType;
1075
+ }
1076
+ _visitEnum(sym, decl, fqn, jsiiType) {
1077
+ const { SyntaxKind } = this.ts;
1078
+ jsiiType.kind = 'enum';
1079
+ const members = [];
1080
+ // strada derives enum members from the enum TYPE's union constituents
1081
+ // (`type.isUnion() ? type.types : [type]`), not from the declaration. For
1082
+ // aliased members (`COLD_HDD = SC1`) the alias shares the canonical member's
1083
+ // literal type, so the alias never surfaces as its own constituent — this is
1084
+ // why strada emits only canonical members (e.g. EbsDeviceVolumeType).
1085
+ const enumMembers = [];
1086
+ const type = this.checker.getTypeAtLocation(decl);
1087
+ const constituents = typeof type?.isUnionType === 'function' && type.isUnionType() ? type.getTypes() : [type];
1088
+ const seen = new Set();
1089
+ for (const c of constituents) {
1090
+ const ms = c?.getSymbol?.() ?? c?.symbol;
1091
+ if (!ms || ms.declarations?.[0]?.kind !== SyntaxKind.EnumMember || seen.has(ms.id)) {
980
1092
  continue;
981
1093
  }
982
- //
983
- // base classes ("extends foo")
984
- // Crawl up the inheritance tree if the current base type is not exported, so we identify the type(s) to be
985
- // erased, and identify the closest exported base class, should there be one.
986
- while (base && this._isPrivateOrInternal(base.symbol)) {
987
- LOG.debug(`Base class of ${chalk_1.default.green(jsiiType.fqn)} named ${chalk_1.default.green(base.symbol.name)} is not exported, erasing it...`);
988
- erasedBases.push(base);
989
- base = (base.getBaseTypes() ?? [])[0];
990
- }
991
- if (!base || isInternalSymbol(base.symbol)) {
992
- // There is no exported base class to be found, pretend this class has no base class.
1094
+ seen.add(ms.id);
1095
+ enumMembers.push(ms);
1096
+ }
1097
+ if (enumMembers.length === 0) {
1098
+ // Fallback (single-valued or fully-computed enums where the declared type
1099
+ // is not a union of member literals): walk the declaration's exports.
1100
+ for (const [, m] of sym.getExports()) {
1101
+ enumMembers.push(m);
1102
+ }
1103
+ }
1104
+ this._prefetchDocs(enumMembers);
1105
+ for (const msym of enumMembers) {
1106
+ if (msym.declarations?.[0]?.kind !== SyntaxKind.EnumMember) {
993
1107
  continue;
994
1108
  }
995
- // eslint-disable-next-line no-await-in-loop
996
- const ref = this._typeReference(base, type.symbol.valueDeclaration ?? type.symbol.declarations?.[0], 'base class');
997
- if (!spec.isNamedTypeReference(ref)) {
998
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3006_TYPE_USED_AS_CLASS.create(base.symbol.valueDeclaration ?? base.symbol.declarations?.[0], ref));
1109
+ if (this._isInternal(msym) || this._shouldStrip(msym, `${fqn}#${msym.name}`)) {
999
1110
  continue;
1000
1111
  }
1001
- this._deferUntilTypesAvailable(fqn, [ref], base.symbol.valueDeclaration, (deref) => {
1002
- if (!spec.isClassType(deref)) {
1003
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3006_TYPE_USED_AS_CLASS.create(base.symbol.valueDeclaration ?? base.symbol.declarations?.[0], ref));
1004
- }
1005
- });
1006
- jsiiType.base = ref.fqn;
1007
- }
1008
- //
1009
- // base interfaces ("implements foo")
1010
- // collect all "implements" declarations from the current type and all
1011
- // erased base types (because otherwise we lose them, see jsii#487)
1012
- const implementsClauses = new Array();
1013
- for (const heritage of [type, ...erasedBases].map((t) => t.symbol.valueDeclaration.heritageClauses ?? [])) {
1014
- for (const clause of heritage) {
1015
- if (clause.token === ts.SyntaxKind.ExtendsKeyword) {
1016
- // Handled by `getBaseTypes`
1112
+ const member = { name: msym.name };
1113
+ const md = this._visitDocumentation(msym);
1114
+ if (md) {
1115
+ member.docs = md;
1116
+ }
1117
+ members.push(this._withDefaultDocs(member));
1118
+ }
1119
+ jsiiType.members = members;
1120
+ }
1121
+ _visitInterface(sym, decl, name, jsiiType) {
1122
+ jsiiType.kind = 'interface';
1123
+ const type = this.checker.getTypeAtLocation(decl);
1124
+ const { interfaces, erasedBases } = this._processBaseInterfaces(type.getBaseTypes());
1125
+ if (interfaces.length) {
1126
+ const rewrittenByStrip = erasedBases.some((b) => this.strippedTypeSymIds.has((b.getSymbol?.() ?? b.symbol)?.id));
1127
+ jsiiType.interfaces = rewrittenByStrip ? [...interfaces].sort() : interfaces;
1128
+ }
1129
+ this._visitMembers(sym, decl, jsiiType, true, erasedBases);
1130
+ // datatype (struct) — same sequence as the classic Assembler:
1131
+ // 1. an interface with no methods starts as a datatype;
1132
+ // 2. behavioral names (`isInterfaceName`: starts with I and has another
1133
+ // capital, so IPSetProperty/IAMUser qualify) drop it again, UNLESS the
1134
+ // `@struct` doc-tag hint forces struct-ness (cfn-generated `I*`
1135
+ // property bags rely on this);
1136
+ // 3. extending a non-datatype interface clears it (applied as a fixpoint
1137
+ // post-pass in assemble(), mirroring _deferUntilTypesAvailable).
1138
+ // The classic path also validates all-readonly with a JSII_3008 diagnostic;
1139
+ // this backend produces no jsii diagnostics, and the flag itself does not
1140
+ // depend on that validation.
1141
+ if ((jsiiType.methods ?? []).length === 0) {
1142
+ const hintsStruct = this._jsDocTags(sym).some((t) => t.name === 'struct');
1143
+ if (!isInterfaceName(name) || hintsStruct) {
1144
+ jsiiType.datatype = true;
1145
+ }
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Fixpoint post-pass for datatype propagation: an interface loses `datatype`
1150
+ * when any of its base interfaces is not a datatype (classic Assembler's
1151
+ * "Calculate datatype based on the datatypeness of this interface and all of
1152
+ * its parents", run via _deferUntilTypesAvailable). External bases are looked
1153
+ * up in the loaded dependency assemblies.
1154
+ */
1155
+ _propagateDatatype() {
1156
+ const isDatatypeBase = (fqn) => {
1157
+ const own = this.types[fqn];
1158
+ if (own) {
1159
+ return own.kind !== 'interface' || own.datatype === true;
1160
+ }
1161
+ const ext = this.externalTypeByFqn.get(fqn);
1162
+ if (ext) {
1163
+ return ext.kind !== 'interface' || ext.datatype === true;
1164
+ }
1165
+ return true; // unknown base: leave the flag alone
1166
+ };
1167
+ let changed = true;
1168
+ while (changed) {
1169
+ changed = false;
1170
+ for (const type of Object.values(this.types)) {
1171
+ if (type.kind !== 'interface' || type.datatype !== true) {
1017
1172
  continue;
1018
1173
  }
1019
- else if (clause.token !== ts.SyntaxKind.ImplementsKeyword) {
1020
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9998_UNSUPPORTED_NODE.create(clause, `Ignoring ${ts.SyntaxKind[clause.token]} heritage clause`));
1021
- continue;
1174
+ if ((type.interfaces ?? []).some((base) => !isDatatypeBase(base))) {
1175
+ delete type.datatype;
1176
+ changed = true;
1022
1177
  }
1023
- implementsClauses.push(clause);
1024
1178
  }
1025
1179
  }
1026
- // process all "implements" clauses
1027
- const allInterfaces = new Set();
1028
- const baseInterfaces = implementsClauses.map((clause) => this._processBaseInterfaces(fqn, clause.types.map((t) => this._getTypeFromTypeNode(t))));
1029
- for (const { interfaces } of baseInterfaces) {
1030
- for (const ifc of interfaces ?? []) {
1031
- allInterfaces.add(ifc.fqn);
1032
- }
1033
- if (interfaces) {
1034
- this._deferUntilTypesAvailable(jsiiType.fqn, interfaces, type.symbol.valueDeclaration, (...ifaces) => {
1035
- for (const iface of ifaces) {
1036
- if (spec.isInterfaceType(iface) && iface.datatype) {
1037
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3007_ILLEGAL_STRUCT_EXTENSION.create(type.symbol.valueDeclaration ?? type.symbol.declarations?.[0], jsiiType, iface));
1038
- }
1039
- }
1040
- });
1041
- }
1042
- }
1043
- if (allInterfaces.size > 0) {
1044
- jsiiType.interfaces = Array.from(allInterfaces);
1045
- }
1046
- if (!type.isClass()) {
1047
- throw new Error('Oh no');
1048
- }
1049
- const allDeclarations = (type.symbol.declarations ?? []).map((decl) => ({ decl, type }));
1050
- // Considering erased bases' declarations, too, so they are "blended in"
1051
- for (const base of erasedBases) {
1052
- allDeclarations.push(...(base.symbol.declarations ?? []).map((decl) => ({
1053
- decl,
1054
- type: base,
1055
- })));
1180
+ }
1181
+ /**
1182
+ * Flatten a type's base interfaces the way strada's `_processBaseInterfaces`
1183
+ * does: keep public/exported base interfaces as `interfaces` entries, but for
1184
+ * private/internal bases, erase them and recurse into *their* bases (so their
1185
+ * public ancestors surface, and their members get re-listed on this type).
1186
+ *
1187
+ * `getBaseTypes()` alone under-reports for interfaces whose heritage goes
1188
+ * through erased/aliased/multi-`extends` chains — recursion fixes that.
1189
+ */
1190
+ _processBaseInterfaces(baseTypes) {
1191
+ const erasedBases = [];
1192
+ const interfaces = [];
1193
+ const seen = new Set();
1194
+ const visitedErased = new Set();
1195
+ if (!baseTypes) {
1196
+ return { interfaces, erasedBases };
1056
1197
  }
1057
- for (const { decl, type: declaringType } of allDeclarations) {
1058
- const classDecl = decl;
1059
- if (!classDecl.members) {
1060
- continue;
1061
- }
1062
- for (const memberDecl of classDecl.members) {
1063
- if (ts.isSemicolonClassElement(memberDecl)) {
1064
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9996_UNNECESSARY_TOKEN.create(memberDecl));
1065
- continue;
1066
- }
1067
- const member = ts.isConstructorDeclaration(memberDecl)
1068
- ? getConstructor(this._typeChecker.getTypeAtLocation(memberDecl.parent))
1069
- : ts.isIndexSignatureDeclaration(memberDecl)
1070
- ? type.symbol.members?.get(ts.InternalSymbolName.Index) ??
1071
- type.symbol.exports?.get(ts.InternalSymbolName.Index)
1072
- : this._typeChecker.getSymbolAtLocation(ts.getNameOfDeclaration(memberDecl) ?? memberDecl);
1073
- if (member && this._isPrivateOrInternal(member, memberDecl)) {
1074
- continue;
1075
- }
1076
- if (ts.isIndexSignatureDeclaration(memberDecl)) {
1077
- // Index signatures (static or not) are not supported in the jsii type model.
1078
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1999_UNSUPPORTED.create(memberDecl, {
1079
- what: 'Index signatures',
1080
- suggestInternal: true,
1081
- }));
1082
- continue;
1083
- }
1084
- if (!(declaringType.symbol.getDeclarations() ?? []).find((d) => d === memberDecl.parent)) {
1085
- continue;
1086
- }
1087
- // constructors are handled later
1088
- if (ts.isConstructorDeclaration(memberDecl)) {
1198
+ const process = (types) => {
1199
+ for (const iface of types) {
1200
+ const s = iface.getSymbol?.() ?? iface.symbol;
1201
+ const fqn = s && (this.typeFqnBySymbolId.get(s.id) ?? this._externalFqnOf(s));
1202
+ if (fqn) {
1203
+ if (!seen.has(fqn)) {
1204
+ seen.add(fqn);
1205
+ interfaces.push(fqn);
1206
+ }
1089
1207
  continue;
1090
1208
  }
1091
- // eslint-disable-next-line no-await-in-loop
1092
- if (ts.isMethodDeclaration(memberDecl) || ts.isMethodSignature(memberDecl)) {
1093
- // eslint-disable-next-line no-await-in-loop
1094
- this._visitMethod(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability), classDecl);
1209
+ // Not an exported/foreign type: erase it and descend into its own bases,
1210
+ // so its public ancestors surface and its members get re-listed here.
1211
+ // Guard against heritage cycles / repeated visits (RPC-cost + safety).
1212
+ if (s && s.id != null) {
1213
+ if (visitedErased.has(s.id)) {
1214
+ continue;
1215
+ }
1216
+ visitedErased.add(s.id);
1095
1217
  }
1096
- else if (ts.isPropertyDeclaration(memberDecl) ||
1097
- ts.isPropertySignature(memberDecl) ||
1098
- ts.isAccessor(memberDecl)) {
1099
- // eslint-disable-next-line no-await-in-loop
1100
- this._visitProperty(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability), classDecl);
1218
+ erasedBases.push(iface);
1219
+ const bases = iface.getBaseTypes?.();
1220
+ if (bases && bases.length) {
1221
+ process(bases);
1101
1222
  }
1102
- else {
1103
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9998_UNSUPPORTED_NODE.create(ts.getNameOfDeclaration(memberDecl) ?? memberDecl, memberDecl.kind));
1104
- }
1105
- /* eslint-enable no-await-in-loop */
1106
- }
1107
- }
1108
- const memberEmitContext = ctx.replaceStability(jsiiType.docs && jsiiType.docs.stability);
1109
- // Find the first defined constructor in this class, or it's erased bases
1110
- const constructor = [type, ...erasedBases].map(getConstructor).find((ctor) => ctor != null);
1111
- const ctorDeclaration = constructor && constructor.declarations?.[0];
1112
- if (constructor && ctorDeclaration) {
1113
- const signature = this._typeChecker.getSignatureFromDeclaration(ctorDeclaration);
1114
- if ((ts.getCombinedModifierFlags(ctorDeclaration) & ts.ModifierFlags.Private) === 0) {
1115
- jsiiType.initializer = {
1116
- locationInModule: this.declarationLocation(ctorDeclaration),
1117
- };
1118
- if (signature) {
1119
- for (const param of signature.getParameters()) {
1120
- jsiiType.initializer.parameters = jsiiType.initializer.parameters ?? [];
1121
- const jsiiParam = // eslint-disable-next-line no-await-in-loop
1122
- this._toParameter(param, ctx.replaceStability(jsiiType.docs?.stability));
1123
- if (containsIntersection(jsiiParam.type)) {
1124
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1010_INTERSECTION_NOT_IN_CTOR.create(param.declarations?.[0]));
1223
+ }
1224
+ };
1225
+ process(baseTypes);
1226
+ return { interfaces, erasedBases };
1227
+ }
1228
+ _visitClass(sym, decl, jsiiType) {
1229
+ const { SyntaxKind } = this.ts;
1230
+ jsiiType.kind = 'class';
1231
+ const mods = decl.modifiers ?? [];
1232
+ if (mods.some((x) => x.kind === SyntaxKind.AbstractKeyword)) {
1233
+ jsiiType.abstract = true;
1234
+ }
1235
+ // heritage (base class + implemented interfaces), flattening erased/local bases
1236
+ const base = {};
1237
+ const interfaces = new Set();
1238
+ const erasedClassBases = [];
1239
+ // Classic order: a type's own `implements` first, then the interfaces of its
1240
+ // erased (non-exported) base classes, in erasure order. Erased interfaces in
1241
+ // an `implements` clause contribute their own super interfaces in place.
1242
+ const erasedDecls = [];
1243
+ // The classic deprecated-remover rebuilt (and sorted) the interface list when a
1244
+ // stripped interface was replaced by its super interfaces, or a stripped base
1245
+ // class contributed its interfaces.
1246
+ let interfacesRewrittenByStrip = false;
1247
+ const collectHeritage = (classDecl) => {
1248
+ const deferredBases = [];
1249
+ for (const h of classDecl.heritageClauses ?? []) {
1250
+ const isExt = h.token === SyntaxKind.ExtendsKeyword && classDecl.kind !== SyntaxKind.InterfaceDeclaration;
1251
+ for (const t of h.types) {
1252
+ const s = this._heritageBaseSymbol(t);
1253
+ if (!s) {
1254
+ continue;
1255
+ }
1256
+ const fqnRef = this.typeFqnBySymbolId.get(s.id) ?? this._externalFqnOf(s);
1257
+ if (isExt) {
1258
+ if (fqnRef) {
1259
+ base.value ??= fqnRef;
1260
+ }
1261
+ else {
1262
+ const d0 = s.declarations?.[0]?.resolve(this.project);
1263
+ if (d0 && (d0.kind === SyntaxKind.ClassDeclaration || d0.kind === SyntaxKind.InterfaceDeclaration)) {
1264
+ if (this.strippedTypeSymIds.has(s.id) &&
1265
+ (d0.heritageClauses ?? []).some((hc) => hc.token === SyntaxKind.ImplementsKeyword)) {
1266
+ interfacesRewrittenByStrip = true;
1267
+ }
1268
+ erasedClassBases.push({ getSymbol: () => s, symbol: s });
1269
+ erasedDecls.push(d0);
1270
+ deferredBases.push(d0);
1271
+ }
1125
1272
  }
1126
- jsiiType.initializer.parameters.push(jsiiParam);
1127
- jsiiType.initializer.variadic = jsiiType.initializer?.parameters?.some((p) => !!p.variadic) || undefined;
1128
- jsiiType.initializer.protected =
1129
- (ts.getCombinedModifierFlags(ctorDeclaration) & ts.ModifierFlags.Protected) !== 0 || undefined;
1130
1273
  }
1131
- }
1132
- this._verifyConsecutiveOptionals(ctorDeclaration, jsiiType.initializer.parameters);
1133
- jsiiType.initializer.docs = this._visitDocumentation(constructor, memberEmitContext).docs;
1134
- }
1135
- // Process constructor-based property declarations even if constructor is private
1136
- if (signature) {
1137
- for (const param of signature.getParameters()) {
1138
- const decl = param.valueDeclaration ?? param.declarations?.[0];
1139
- if (decl && ts.isParameterPropertyDeclaration(decl, decl.parent) && !this._isPrivateOrInternal(param)) {
1140
- // eslint-disable-next-line no-await-in-loop
1141
- this._visitProperty(param, jsiiType, memberEmitContext, ctorDeclaration.parent);
1274
+ else if (fqnRef) {
1275
+ interfaces.add(fqnRef);
1276
+ }
1277
+ else {
1278
+ const d0 = s.declarations?.[0]?.resolve(this.project);
1279
+ if (d0 && d0.kind === SyntaxKind.InterfaceDeclaration) {
1280
+ if (this.strippedTypeSymIds.has(s.id)) {
1281
+ interfacesRewrittenByStrip = true;
1282
+ }
1283
+ erasedClassBases.push({ getSymbol: () => s, symbol: s });
1284
+ collectHeritage(d0);
1285
+ }
1142
1286
  }
1143
1287
  }
1144
1288
  }
1145
- }
1146
- else if (jsiiType.base) {
1147
- this._deferUntilTypesAvailable(fqn, [jsiiType.base], type.symbol.valueDeclaration, (baseType) => {
1148
- if (spec.isClassType(baseType)) {
1149
- jsiiType.initializer = baseType.initializer;
1150
- }
1151
- else {
1152
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3999_INCOHERENT_TYPE_MODEL.create(type.symbol.valueDeclaration ?? type.symbol.declarations?.[0], `Base type of ${jsiiType.fqn} (${jsiiType.base}) is not a class`));
1153
- }
1154
- });
1155
- }
1156
- else {
1157
- jsiiType.initializer = {
1158
- docs: ctx.stability && { stability: ctx.stability },
1159
- };
1160
- }
1161
- this._verifyNoStaticMixing(jsiiType, type.symbol.valueDeclaration ?? type.symbol.declarations?.[0]);
1162
- return _sortMembers(jsiiType);
1163
- }
1164
- /**
1165
- * Use the TypeChecker's getTypeFromTypeNode, but throw a descriptive error if it fails
1166
- */
1167
- _getTypeFromTypeNode(t) {
1168
- const type = this._typeChecker.getTypeFromTypeNode(t);
1169
- if (isErrorType(type)) {
1170
- throw new utils_2.JsiiError(`Unable to resolve type: ${t.getFullText()}. This typically happens if something is wrong with your dependency closure.`);
1171
- }
1172
- return type;
1173
- }
1174
- /**
1175
- * Check that this class doesn't declare any members that are of different staticness in itself or any of its bases
1176
- */
1177
- _verifyNoStaticMixing(klass, decl) {
1178
- // Check class itself--may have two methods/props with the same name, so check the arrays
1179
- const statics = new Set((klass.methods ?? [])
1180
- .concat(klass.properties ?? [])
1181
- .filter((x) => x.static)
1182
- .map((x) => x.name));
1183
- const nonStatics = new Set((klass.methods ?? [])
1184
- .concat(klass.properties ?? [])
1185
- .filter((x) => !x.static)
1186
- .map((x) => x.name));
1187
- // Intersect
1188
- for (const member of sets_1.Sets.intersect(statics, nonStatics)) {
1189
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5013_STATIC_INSTANCE_CONFLICT.create(decl, member, klass));
1190
- }
1191
- // Check against base classes. They will not contain duplicate member names so we can load
1192
- // the members into a map.
1193
- const classMembers = typeMembers(klass);
1194
- this._withBaseClass(klass, decl, (base, recurse) => {
1195
- for (const [name, baseMember] of Object.entries(typeMembers(base))) {
1196
- const member = classMembers[name];
1197
- if (!member) {
1198
- continue;
1199
- }
1200
- if (!!baseMember.static !== !!member.static) {
1201
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5014_INHERITED_STATIC_CONFLICT.create(decl, member, klass, baseMember, base));
1202
- }
1289
+ for (const d0 of deferredBases) {
1290
+ collectHeritage(d0);
1203
1291
  }
1204
- recurse();
1205
- });
1206
- }
1207
- /**
1208
- * Wrapper around _deferUntilTypesAvailable, invoke the callback with the given classes' base type
1209
- *
1210
- * Does nothing if the given class doesn't have a base class.
1211
- *
1212
- * The second argument will be a `recurse` function for easy recursion up the inheritance tree
1213
- * (no messing around with binding 'self' and 'this' and doing multiple calls to _withBaseClass.)
1214
- */
1215
- _withBaseClass(klass, decl, cb) {
1216
- if (klass.base) {
1217
- this._deferUntilTypesAvailable(klass.fqn, [klass.base], decl, (base) => {
1218
- if (!spec.isClassType(base)) {
1219
- throw new Error('Oh no');
1292
+ };
1293
+ collectHeritage(decl);
1294
+ if (base.value) {
1295
+ jsiiType.base = base.value;
1296
+ }
1297
+ if (interfaces.size) {
1298
+ jsiiType.interfaces = interfacesRewrittenByStrip ? [...interfaces].sort() : [...interfaces];
1299
+ }
1300
+ // initializer (constructor)
1301
+ // Classic: the first constructor declared by the class or by one of its
1302
+ // erased base classes (in erasure order).
1303
+ const findCtor = (d) => d.members?.find((m) => m.kind === SyntaxKind.Constructor);
1304
+ const ctorOwners = [
1305
+ { decl, sym },
1306
+ ...erasedClassBases.map((b, i) => ({ decl: erasedDecls[i], sym: b.symbol })),
1307
+ ].filter((o) => o.decl?.kind === SyntaxKind.ClassDeclaration);
1308
+ const ctorOwner = ctorOwners.find((o) => findCtor(o.decl) != null);
1309
+ const effectiveCtor = ctorOwner && findCtor(ctorOwner.decl);
1310
+ // The constructor's own symbol carries its documentation (classic read it the same way).
1311
+ const ctorSym = ctorOwner?.sym?.getMembers?.()?.get?.('__constructor');
1312
+ const ctorPrivate = effectiveCtor && (effectiveCtor.modifiers ?? []).some((x) => x.kind === SyntaxKind.PrivateKeyword);
1313
+ if (ctorPrivate) {
1314
+ // private constructor: jsii omits the initializer
1315
+ }
1316
+ else if (effectiveCtor) {
1317
+ const sig = this.checker.getSignatureFromDeclaration(effectiveCtor);
1318
+ const initializer = { locationInModule: this._locationOf(effectiveCtor) };
1319
+ if (sig) {
1320
+ const params = sig.getParameters().map((p) => this._visitParameter(p));
1321
+ if (params.length) {
1322
+ initializer.parameters = params;
1323
+ if (params.some((p) => p.variadic)) {
1324
+ initializer.variadic = true;
1325
+ }
1326
+ // strada quirk: `initializer.protected` is assigned inside its
1327
+ // parameter loop, so a protected ZERO-parameter constructor does not
1328
+ // get the flag. Reproduced bug-for-bug for parity.
1329
+ if ((effectiveCtor.modifiers ?? []).some((x) => x.kind === SyntaxKind.ProtectedKeyword)) {
1330
+ initializer.protected = true;
1331
+ }
1220
1332
  }
1221
- cb(base, () => this._withBaseClass(base, decl, cb));
1222
- });
1223
- }
1224
- }
1225
- /**
1226
- * Whether a symbol is marked with the `@jsii ignore` directive on *all* of its
1227
- * declarations. We require every declaration to be ignored so that emission
1228
- * (`_visitNode`) and reference resolution (`_isPrivateOrInternal`) agree: a
1229
- * partially-ignored merged declaration stays a visible part of the public API.
1230
- */
1231
- _isIgnored(symbol) {
1232
- return ((symbol.declarations?.length ?? 0) > 0 &&
1233
- symbol.declarations.every((decl) => directives_1.Directives.of(decl, (diag) => this._diagnostics.push(diag)).ignore != null));
1234
- }
1235
- /**
1236
- * @returns true if this member is internal and should be omitted from the type manifest
1237
- */
1238
- _isPrivateOrInternal(symbol, validateDeclaration) {
1239
- const hasInternalJsDocTag = _hasInternalJsDocTag(symbol);
1240
- const hasInternalSymbolName = isInternalSymbol(symbol);
1241
- const hasUnderscorePrefix = !hasInternalSymbolName && symbol.name.startsWith('_');
1242
- if (_isPrivate(symbol)) {
1243
- LOG.trace(`${chalk_1.default.cyan(symbol.name)} is marked "private", or is an unexported type declaration`);
1244
- return true;
1245
- }
1246
- // If all the declarations are marked with `@jsii ignore`, then this is effetcively private as far as jsii is concerned.
1247
- if (this._isIgnored(symbol)) {
1248
- return true;
1249
- }
1250
- if (!hasInternalJsDocTag && !hasUnderscorePrefix) {
1251
- return false;
1252
- }
1253
- // We only validate if we have a declaration and the symbol doesn't have an internal name.
1254
- if (validateDeclaration && !hasInternalSymbolName) {
1255
- if (!hasUnderscorePrefix) {
1256
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8005_INTERNAL_UNDERSCORE.create(ts.getNameOfDeclaration(validateDeclaration) ?? validateDeclaration, symbol.name));
1257
1333
  }
1258
- if (!hasInternalJsDocTag) {
1259
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8006_UNDERSCORE_INTERNAL.create(ts.getNameOfDeclaration(validateDeclaration) ?? validateDeclaration, symbol.name));
1334
+ // strada: initializer docs come from the constructor symbol's JSDoc
1335
+ // (summary/remarks + tags like @default), same as any member.
1336
+ const ctorDocs = ctorSym ? this._visitDocumentation(ctorSym) : this._docsFromDeclJsDoc(effectiveCtor);
1337
+ if (ctorDocs) {
1338
+ initializer.docs = ctorDocs;
1260
1339
  }
1340
+ jsiiType.initializer = this._withDefaultDocs(initializer);
1261
1341
  }
1262
- return true;
1263
- }
1264
- _visitEnum(type, ctx) {
1265
- if (LOG.isTraceEnabled()) {
1266
- LOG.trace(`Processing enum: ${chalk_1.default.gray(ctx.namespace.join('.'))}.${chalk_1.default.cyan(type.symbol.name)}`);
1267
- }
1268
- // Forcefully resolving to the EnumDeclaration symbol for single-valued enums
1269
- let decl = type.symbol.declarations?.[0];
1270
- let symbol;
1271
- if (decl && ts.isEnumMember(decl)) {
1272
- decl = decl?.parent;
1273
- }
1274
- if (decl && ts.isEnumDeclaration(decl)) {
1275
- symbol = getSymbolFromDeclaration(decl, this._typeChecker);
1276
- }
1277
- if (!decl || !symbol || !ts.isEnumDeclaration(decl)) {
1278
- throw new utils_2.JsiiError(`Unable to resolve enum declaration for ${type.symbol.name}!`);
1279
- }
1280
- if (_hasInternalJsDocTag(symbol)) {
1281
- return undefined;
1342
+ else if (jsiiType.base) {
1343
+ // Classic: a class without its own constructor takes the initializer
1344
+ // recorded for its base type (own or foreign), verbatim. Resolved once all
1345
+ // types are assembled, see _finalizeInheritance.
1346
+ this.inheritsInitializer.add(jsiiType.fqn);
1282
1347
  }
1283
- // check the enum to see if there are duplicate enum values
1284
- this.assertNoDuplicateEnumValues(decl);
1285
- this._warnAboutReservedWords(symbol);
1286
- const flags = ts.getCombinedModifierFlags(decl);
1287
- if (flags & ts.ModifierFlags.Const) {
1288
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1000_NO_CONST_ENUM.create(decl.modifiers?.find((mod) => mod.kind === ts.SyntaxKind.ConstKeyword) ?? decl));
1289
- }
1290
- for (const memberDecl of decl.members) {
1291
- if (this._typeChecker.getConstantValue(memberDecl) === undefined) {
1292
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1012_ONLY_CONST_ENUM_MEMBERS.create(memberDecl));
1293
- }
1294
- }
1295
- const { docs } = this._visitDocumentation(symbol, ctx);
1296
- const typeContext = ctx.replaceStability(docs?.stability);
1297
- const members = type.isUnion() ? type.types : [type];
1298
- if (Case.pascal(symbol.name) !== symbol.name) {
1299
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8000_PASCAL_CASED_TYPE_NAMES.create(symbol.valueDeclaration.name, symbol.name));
1300
- }
1301
- const jsiiType = bindings.setEnumRelatedNode({
1302
- assembly: this.projectInfo.name,
1303
- fqn: `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${symbol.name}`,
1304
- kind: spec.TypeKind.Enum,
1305
- members: members.map((m) => {
1306
- // eslint-disable-next-line @typescript-eslint/no-shadow
1307
- const { docs } = this._visitDocumentation(m.symbol, typeContext);
1308
- return { name: m.symbol.name, docs };
1309
- }),
1310
- name: symbol.name,
1311
- namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
1312
- docs,
1313
- // Set SymbolId here instead of later, as by default TS will pick single-enum members
1314
- // as the target symbol if possible.
1315
- symbolId: (0, symbol_id_1.symbolIdentifier)(this._typeChecker, symbol),
1316
- }, decl);
1317
- this._typeTracker.registerEnum(jsiiType.fqn, decl);
1318
- return jsiiType;
1319
- }
1320
- assertNoDuplicateEnumValues(decl) {
1321
- const enumValues = decl.members
1322
- .filter((m) => m.initializer)
1323
- .map((member) => {
1324
- return {
1325
- value: member.initializer.getText(),
1326
- name: member.name.getText(),
1327
- decl: ts.getNameOfDeclaration(member),
1328
- };
1329
- });
1330
- const hasDuplicateEnumValues = enumValues.some((val, _, arr) => arr.filter((e) => val.value === e.value).length > 1);
1331
- if (hasDuplicateEnumValues) {
1332
- const enumValueMap = enumValues.reduce((acc, val) => {
1333
- if (!acc[val.value]) {
1334
- acc[val.value] = [];
1335
- }
1336
- acc[val.value].push(val);
1337
- return acc;
1338
- }, {});
1339
- for (const duplicateValue of Object.keys(enumValueMap)) {
1340
- if (enumValueMap[duplicateValue].length > 1) {
1341
- const err = jsii_diagnostic_1.JsiiDiagnostic.JSII_1004_DUPLICATE_ENUM_VALUE.create(enumValueMap[duplicateValue][0].decl, duplicateValue, enumValueMap[duplicateValue].map((v) => v.name));
1342
- for (let i = 1; i < enumValueMap[duplicateValue].length; i++) {
1343
- err.addRelatedInformation(enumValueMap[duplicateValue][i].decl, 'The conflicting declaration is here');
1348
+ else {
1349
+ // Classic: `{ docs: ctx.stability && { stability } }` with the package-level context.
1350
+ const init = {};
1351
+ if (this.defaultStability) {
1352
+ init.docs = { stability: this.defaultStability };
1353
+ }
1354
+ jsiiType.initializer = init;
1355
+ }
1356
+ this._visitMembers(sym, decl, jsiiType, false, erasedClassBases);
1357
+ }
1358
+ // -------------------------------------------------------------------------
1359
+ // members (strada: _visitProperty / _visitMethod live under this)
1360
+ // -------------------------------------------------------------------------
1361
+ _visitMembers(sym, decl, jsiiType, isInterface, erasedBases = []) {
1362
+ const { SyntaxKind, SymbolFlags } = this.ts;
1363
+ const type = this.checker.getTypeAtLocation(decl);
1364
+ const props = [];
1365
+ const methods = [];
1366
+ // The classic deprecated-remover left an empty list behind when it stripped
1367
+ // every member of a kind (`typeInfo.properties ? properties : undefined`).
1368
+ let strippedProps = false;
1369
+ let strippedMethods = false;
1370
+ // Symbol ids of the erased (private/internal/unexported) bases whose members
1371
+ // jsii folds into this type: members from those bases must be re-listed here.
1372
+ const erasedBaseSymIds = new Set();
1373
+ for (const eb of erasedBases) {
1374
+ const s = eb.getSymbol?.() ?? eb.symbol;
1375
+ if (s?.id != null && !this.strippedTypeSymIds.has(s.id)) {
1376
+ erasedBaseSymIds.add(s.id);
1377
+ }
1378
+ }
1379
+ const instanceProps = this.checker.getPropertiesOfType(type);
1380
+ const staticTypeForPrefetch = !isInterface ? this.checker.getTypeOfSymbol(sym) : undefined;
1381
+ const staticPropsForPrefetch = staticTypeForPrefetch ? this.checker.getPropertiesOfType(staticTypeForPrefetch) : [];
1382
+ // One RPC for all member docs of this type (instance + static).
1383
+ this._prefetchDocs([...instanceProps, ...staticPropsForPrefetch]);
1384
+ // Constructor parameter properties are only listed for the EFFECTIVE
1385
+ // constructor — the first constructor found on the type itself or along its
1386
+ // erased-base chain (strada visits param-props exclusively from that
1387
+ // signature). Param-props of a non-effective erased-base constructor (e.g.
1388
+ // when the subclass declares its own constructor) are NOT re-listed.
1389
+ let effectiveCtorOwnerId;
1390
+ if (!isInterface) {
1391
+ if ((decl.members ?? []).some((m) => m.kind === SyntaxKind.Constructor)) {
1392
+ effectiveCtorOwnerId = sym?.id;
1393
+ }
1394
+ else {
1395
+ for (const eb of erasedBases) {
1396
+ const s = eb.getSymbol?.() ?? eb.symbol;
1397
+ const ebDecl = s?.declarations?.[0]?.resolve(this.project);
1398
+ if (ebDecl && (ebDecl.members ?? []).some((m) => m.kind === SyntaxKind.Constructor)) {
1399
+ effectiveCtorOwnerId = s.id;
1400
+ break;
1344
1401
  }
1345
- this._diagnostics.push(err);
1346
1402
  }
1347
1403
  }
1348
1404
  }
1349
- }
1350
- /**
1351
- * Return docs for a symbol
1352
- */
1353
- _visitDocumentation(sym, context) {
1354
- const result = (0, docs_1.parseSymbolDocumentation)(sym, this._typeChecker);
1355
- for (const diag of result.diagnostics ?? []) {
1356
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_7999_DOCUMENTATION_ERROR.create(sym.valueDeclaration ?? sym.declarations?.[0], diag));
1357
- }
1358
- const decl = sym.valueDeclaration ?? sym.declarations?.[0];
1359
- // The @struct hint is only valid for interface declarations
1360
- if (decl && !ts.isInterfaceDeclaration(decl) && result.hints.struct) {
1361
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_7001_ILLEGAL_HINT.create(_findHint(decl, 'struct'), 'struct', 'interfaces with only readonly properties').addRelatedInformationIf(ts.getNameOfDeclaration(decl) ?? decl, 'The annotated declaration is here'));
1362
- // Clean up the bad hint...
1363
- delete result.hints.struct;
1364
- }
1365
- // Apply the current context's stability if none was specified locally.
1366
- if (result.docs.stability == null) {
1367
- result.docs.stability = context.stability;
1368
- }
1369
- const allUndefined = Object.values(result.docs).every((v) => v === undefined);
1370
- return {
1371
- docs: !allUndefined ? result.docs : undefined,
1372
- hints: result.hints,
1373
- };
1374
- }
1375
- /**
1376
- * Check that all parameters the doc block refers to with a @param declaration actually exist
1377
- */
1378
- _validateReferencedDocParams(method, methodSym) {
1379
- const params = (0, docs_1.getReferencedDocParams)(methodSym);
1380
- const actualNames = new Set((method.parameters ?? []).map((p) => p.name));
1381
- for (const param of params) {
1382
- if (!actualNames.has(param)) {
1383
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_7000_NON_EXISTENT_PARAMETER.create(methodSym.valueDeclaration ?? methodSym.declarations?.[0], method, param));
1405
+ for (const p of instanceProps) {
1406
+ if (this._isInternal(p)) {
1407
+ continue;
1384
1408
  }
1385
- }
1386
- }
1387
- _visitInterface(type, ctx) {
1388
- if (LOG.isTraceEnabled()) {
1389
- LOG.trace(`Processing interface: ${chalk_1.default.gray(ctx.namespace.join('.'))}.${chalk_1.default.cyan(type.symbol.name)}`);
1390
- }
1391
- if (_hasInternalJsDocTag(type.symbol)) {
1392
- return undefined;
1393
- }
1394
- this._warnAboutReservedWords(type.symbol);
1395
- const fqn = `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${type.symbol.name}`;
1396
- const { docs, hints } = this._visitDocumentation(type.symbol, ctx);
1397
- const jsiiType = bindings.setInterfaceRelatedNode({
1398
- assembly: this.projectInfo.name,
1399
- fqn,
1400
- kind: spec.TypeKind.Interface,
1401
- name: type.symbol.name,
1402
- namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
1403
- docs,
1404
- }, type.symbol.declarations?.[0]);
1405
- const { interfaces, erasedBases } = this._processBaseInterfaces(fqn, type.getBaseTypes());
1406
- jsiiType.interfaces = apply(interfaces, (arr) => arr.map((i) => i.fqn));
1407
- const typeDecl = (type.symbol.valueDeclaration ?? type.symbol.declarations?.[0]);
1408
- for (const typeParam of typeDecl?.typeParameters ?? []) {
1409
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1006_GENERIC_TYPE.create(typeParam));
1410
- }
1411
- for (const decl of typeDecl?.members?.filter((mem) => ts.isIndexSignatureDeclaration(mem)) ?? []) {
1412
- const sym = type.symbol.members?.get(ts.InternalSymbolName.Index) ?? type.symbol.exports?.get(ts.InternalSymbolName.Index);
1413
- if (sym != null && this._isPrivateOrInternal(sym, decl)) {
1409
+ const pDecl = p.declarations?.[0]?.resolve(this.project);
1410
+ if (!pDecl) {
1414
1411
  continue;
1415
1412
  }
1416
- // Index signatures (static or not) are not supported in the jsii type model.
1417
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1999_UNSUPPORTED.create(decl, { what: 'Index signatures', suggestInternal: true }));
1418
- }
1419
- for (const declaringType of [type, ...erasedBases]) {
1420
- for (const member of declaringType.getProperties()) {
1421
- const decl = member.valueDeclaration ?? member.declarations?.[0];
1422
- if (!(declaringType.symbol.getDeclarations() ?? []).find((d) => d === decl?.parent)) {
1413
+ if ((pDecl.modifiers ?? []).some((x) => x.kind === SyntaxKind.PrivateKeyword)) {
1414
+ continue;
1415
+ }
1416
+ const isParamProp = pDecl.kind === SyntaxKind.Parameter;
1417
+ const owner = isParamProp ? pDecl.parent?.parent : pDecl.parent;
1418
+ if (isParamProp) {
1419
+ const ownerId = owner === decl ? sym?.id : this.checker.getTypeAtLocation(owner)?.getSymbol?.()?.id;
1420
+ if (ownerId == null || ownerId !== effectiveCtorOwnerId) {
1423
1421
  continue;
1424
1422
  }
1425
- if (this._isPrivateOrInternal(member, decl)) {
1423
+ }
1424
+ else if (owner !== decl) {
1425
+ // Resolve the *declaring* type of this member via the owner declaration
1426
+ // node's type symbol. NOTE: do NOT use `p.getParent()` here — for a member
1427
+ // obtained from getPropertiesOfType(type) that returns the *queried* type
1428
+ // (membership), not the declaring type, which mis-classifies inherited
1429
+ // members as own. getTypeAtLocation(owner) gives the declaring type.
1430
+ const ownerTypeSym = owner ? this.checker.getTypeAtLocation(owner)?.getSymbol?.() : undefined;
1431
+ const ownerId = ownerTypeSym?.id;
1432
+ const isOwn = ownerId != null && ownerId === sym?.id;
1433
+ const isErasedBase = ownerId != null && erasedBaseSymIds.has(ownerId);
1434
+ if (!isOwn && !isErasedBase) {
1435
+ // strada re-lists a member only when its declaring declaration belongs
1436
+ // to this type or one of its *erased* bases. A member declared on an
1437
+ // unexported ancestor reachable only through a NAMED base (e.g.
1438
+ // FileOptions behind FingerprintOptions) is NOT re-listed — the named
1439
+ // base already re-lists it.
1426
1440
  continue;
1427
1441
  }
1428
- if (decl && (ts.isMethodDeclaration(decl) || ts.isMethodSignature(decl))) {
1429
- // eslint-disable-next-line no-await-in-loop
1430
- this._visitMethod(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability), typeDecl);
1431
- }
1432
- else if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl) || ts.isAccessor(decl))) {
1433
- // eslint-disable-next-line no-await-in-loop
1434
- this._visitProperty(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability), typeDecl);
1442
+ }
1443
+ // Stripping applies to the members the classic assembler listed on this type
1444
+ // (own and erased-base members), hence after the ownership check above.
1445
+ if (this._shouldStrip(p, `${jsiiType.fqn}#${p.name}`)) {
1446
+ if ((p.flags & SymbolFlags.Method) !== 0) {
1447
+ strippedMethods = true;
1435
1448
  }
1436
1449
  else {
1437
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9998_UNSUPPORTED_NODE.create(_nameOrDeclarationNode(member), (member.valueDeclaration ?? member.declarations?.[0])?.kind ?? ts.SyntaxKind.Unknown));
1438
- }
1439
- }
1440
- }
1441
- // Calculate datatype based on the datatypeness of this interface and all of its parents
1442
- // To keep the spec minimal the actual values of the attribute are "true" or "undefined" (to represent "false").
1443
- const declaration = type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];
1444
- this._deferUntilTypesAvailable(fqn, jsiiType.interfaces ?? [], declaration, (...bases) => {
1445
- if ((jsiiType.methods ?? []).length === 0) {
1446
- jsiiType.datatype = true;
1447
- }
1448
- else if (hints.struct) {
1449
- this._diagnostics.push(jsiiType.methods.reduce((diag, mthod) => {
1450
- const node = bindings.getMethodRelatedNode(mthod);
1451
- return node
1452
- ? diag.addRelatedInformation(ts.getNameOfDeclaration(node) ?? node, 'A method is declared here')
1453
- : diag;
1454
- }, jsii_diagnostic_1.JsiiDiagnostic.JSII_7001_ILLEGAL_HINT.create(declaration && _findHint(declaration, 'struct'), 'struct', 'interfaces with only readonly properties').addRelatedInformationIf(ts.getNameOfDeclaration(declaration) ?? declaration, 'The annotated declartion is here')));
1455
- }
1456
- for (const base of bases) {
1457
- if (spec.isInterfaceType(base) && !base.datatype) {
1458
- jsiiType.datatype = undefined;
1450
+ strippedProps = true;
1459
1451
  }
1452
+ continue;
1460
1453
  }
1461
- const interfaceName = isInterfaceName(jsiiType.name);
1462
- // If it's not a datatype the name must start with an "I".
1463
- if (!jsiiType.datatype && !interfaceName) {
1464
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8007_BEHAVIORAL_INTERFACE_NAME.create(ts.getNameOfDeclaration(declaration) ?? declaration, jsiiType.name));
1465
- }
1466
- // NOTE: We need to be careful with the `I` prefix for behavioral interfaces, as this can mess with PascalCase
1467
- // transformations, especially with short names such as `IA`, ...
1468
- const expectedName = interfaceName ? `I${Case.pascal(type.symbol.name.slice(1))}` : Case.pascal(type.symbol.name);
1469
- if (expectedName !== type.symbol.name) {
1470
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_8000_PASCAL_CASED_TYPE_NAMES.create(type.symbol.declarations?.[0]?.name, type.symbol.name, expectedName));
1471
- }
1472
- // If the name starts with an "I" it is not intended as a datatype, so switch that off,
1473
- // unless a TSDoc hint was set to force this to be considered a behavioral interface.
1474
- if (jsiiType.datatype && interfaceName && !hints.struct) {
1475
- delete jsiiType.datatype;
1476
- }
1477
- // Okay, this is a data type, check that all properties are readonly
1478
- if (jsiiType.datatype) {
1479
- for (const prop of jsiiType.properties ?? []) {
1480
- if (!prop.immutable) {
1481
- const p = type.getProperty(prop.name);
1482
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3008_STRUCT_PROPS_MUST_BE_READONLY.create(_nameOrDeclarationNode(p), p.name, jsiiType));
1483
- // force property to be "readonly" since jsii languages will pass this by-value
1484
- prop.immutable = true;
1485
- }
1454
+ if ((p.flags & SymbolFlags.Method) !== 0) {
1455
+ const m = this._visitMethod(p, pDecl, false);
1456
+ if (isInterface) {
1457
+ m.abstract = true;
1486
1458
  }
1459
+ methods.push(m);
1487
1460
  }
1488
1461
  else {
1489
- // This is *NOT* a data type, so it may not extend something that is one.
1490
- for (const base of bases) {
1491
- if (!spec.isInterfaceType(base)) {
1492
- // Invalid type we already warned about earlier, just ignoring it here..
1493
- continue;
1494
- }
1495
- if (base.datatype) {
1496
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3007_ILLEGAL_STRUCT_EXTENSION.create(type.symbol.valueDeclaration ?? type.symbol.declarations?.[0], jsiiType, base));
1497
- }
1462
+ const pr = this._visitProperty(p, pDecl, false);
1463
+ if (isInterface) {
1464
+ pr.abstract = true;
1498
1465
  }
1466
+ props.push(pr);
1499
1467
  }
1500
- });
1501
- // Check that no interface declares a member that's already declared
1502
- // in a base type (not allowed in C#).
1503
- const names = memberNames(jsiiType);
1504
- const checkNoIntersection = (...bases) => {
1505
- for (const base of bases) {
1506
- if (!spec.isInterfaceType(base)) {
1468
+ }
1469
+ if (!isInterface) {
1470
+ for (const sp of staticPropsForPrefetch) {
1471
+ if (sp.name === 'prototype' || this._isInternal(sp)) {
1507
1472
  continue;
1508
1473
  }
1509
- const baseMembers = memberNames(base);
1510
- for (const memberName of names) {
1511
- if (baseMembers.includes(memberName)) {
1512
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5015_REDECLARED_INTERFACE_MEMBER.create(type.symbol.valueDeclaration ?? type.symbol.declarations?.[0], memberName, jsiiType));
1474
+ if (this._shouldStrip(sp, `${jsiiType.fqn}#${sp.name}`)) {
1475
+ if ((sp.flags & SymbolFlags.Method) !== 0) {
1476
+ strippedMethods = true;
1513
1477
  }
1478
+ else {
1479
+ strippedProps = true;
1480
+ }
1481
+ continue;
1514
1482
  }
1515
- // Recurse upwards
1516
- this._deferUntilTypesAvailable(fqn, base.interfaces ?? [], type.symbol.valueDeclaration, checkNoIntersection);
1517
- }
1518
- };
1519
- this._deferUntilTypesAvailable(fqn, jsiiType.interfaces ?? [], type.symbol.valueDeclaration, checkNoIntersection);
1520
- return _sortMembers(jsiiType);
1521
- }
1522
- _visitMethod(symbol, type, ctx, declaringTypeDecl) {
1523
- if (LOG.isTraceEnabled()) {
1524
- LOG.trace(`Processing method: ${chalk_1.default.green(type.fqn)}#${chalk_1.default.cyan(symbol.name)}`);
1525
- }
1526
- const declaration = symbol.valueDeclaration;
1527
- const signature = this._typeChecker.getSignatureFromDeclaration(declaration);
1528
- if (!signature) {
1529
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9004_UNABLE_TO_COMPUTE_SIGNATURE.create(declaration, symbol.name, type));
1530
- return;
1531
- }
1532
- if (type.name === Case.pascal(symbol.name)) {
1533
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5019_MEMBER_TYPE_NAME_CONFLICT.create(declaration.name, 'method', symbol, type).addRelatedInformationIf(declaringTypeDecl?.name ?? declaringTypeDecl, `The declaring ${type.kind} is introduced here`));
1534
- }
1535
- if (isProhibitedMemberName(symbol.name)) {
1536
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5016_PROHIBITED_MEMBER_NAME.create(declaration.name, symbol.name));
1537
- return;
1538
- }
1539
- this._warnAboutReservedWords(symbol);
1540
- const parameters = signature.getParameters().map((p) => this._toParameter(p, ctx));
1541
- const returnType = signature.getReturnType();
1542
- const method = bindings.setMethodRelatedNode({
1543
- abstract: _isAbstract(symbol, type) || undefined,
1544
- name: symbol.name,
1545
- parameters: parameters.length > 0 ? parameters : undefined,
1546
- protected: _isProtected(symbol) || undefined,
1547
- returns: _isVoid(returnType)
1548
- ? undefined
1549
- : this._optionalValue(returnType, declaration.type ?? declaration.name, 'return type'),
1550
- async: _isPromise(returnType) || undefined,
1551
- static: _isStatic(symbol) || undefined,
1552
- locationInModule: this.declarationLocation(declaration),
1553
- }, declaration);
1554
- method.variadic = method.parameters?.some((p) => !!p.variadic) === true ? true : undefined;
1555
- this._verifyConsecutiveOptionals(declaration, method.parameters);
1556
- method.docs = this._visitDocumentation(symbol, ctx).docs;
1557
- // If the last parameter is a datatype, verify that it does not share any field names with
1558
- // other function arguments, so that it can be turned into keyword arguments by jsii frontends
1559
- // that support such.
1560
- const lastParamTypeRef = apply(last(parameters), (x) => x.type);
1561
- const lastParamSymbol = last(signature.getParameters());
1562
- if (lastParamTypeRef && spec.isNamedTypeReference(lastParamTypeRef)) {
1563
- this._deferUntilTypesAvailable(symbol.name, [lastParamTypeRef], lastParamSymbol.declarations?.[0], (lastParamType) => {
1564
- if (!spec.isInterfaceType(lastParamType) || !lastParamType.datatype) {
1565
- return;
1483
+ const spDecl = sp.declarations?.[0]?.resolve(this.project);
1484
+ if (!spDecl) {
1485
+ continue;
1566
1486
  }
1567
- // Liftable datatype, make sure no parameter names match any of the properties in the datatype
1568
- const propNames = this.allProperties(lastParamType);
1569
- const paramNames = new Set(parameters.slice(0, parameters.length - 1).map((x) => x.name));
1570
- const sharedNames = sets_1.Sets.intersection(propNames, paramNames);
1571
- for (const badName of sharedNames) {
1572
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5017_POSITIONAL_KEYWORD_CONFLICT.create(declaration, badName));
1487
+ if (spDecl.parent !== decl) {
1488
+ // Same declaring-type logic as the instance loop: statics declared on
1489
+ // an *erased* (private/internal/unexported) base are re-listed on this
1490
+ // type (strada blends erased-base declarations into the member walk);
1491
+ // statics declared on an exported/foreign named base are not.
1492
+ const ownerTypeSym = spDecl.parent ? this.checker.getTypeAtLocation(spDecl.parent)?.getSymbol?.() : undefined;
1493
+ const ownerId = ownerTypeSym?.id;
1494
+ const isOwn = ownerId != null && ownerId === sym?.id;
1495
+ if (!isOwn && !(ownerId != null && erasedBaseSymIds.has(ownerId))) {
1496
+ continue;
1497
+ }
1573
1498
  }
1574
- });
1575
- }
1576
- this._validateReferencedDocParams(method, symbol);
1577
- type.methods = type.methods ?? [];
1578
- if (type.methods.find((m) => m.name === method.name && m.static === method.static) != null) {
1579
- LOG.trace(`Dropping re-declaration of ${chalk_1.default.green(type.fqn)}#${chalk_1.default.cyan(method.name)}`);
1580
- return;
1581
- }
1582
- type.methods.push(method);
1583
- }
1584
- _warnAboutReservedWords(symbol) {
1585
- const reservingLanguages = (0, reserved_words_1.isReservedName)(symbol.name);
1586
- if (reservingLanguages) {
1587
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5018_RESERVED_WORD.create(_nameOrDeclarationNode(symbol), symbol.name, reservingLanguages));
1588
- }
1589
- }
1590
- _visitProperty(symbol, type, ctx, declaringTypeDecl) {
1591
- if (type.properties?.find((p) => p.name === symbol.name)) {
1592
- /*
1593
- * Second declaration of the same property. For example, if code specifies a getter & setter signature,
1594
- * there will be one pass for each of the signatures, but we can process only the first encountered. The
1595
- * typescript compiler will take care of making sure we don't have conflicting declarations, anyway.
1596
- */
1597
- return;
1598
- }
1599
- if (LOG.isTraceEnabled()) {
1600
- LOG.trace(`Processing property: ${chalk_1.default.green(type.fqn)}#${chalk_1.default.cyan(symbol.name)}`);
1601
- }
1602
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
1603
- const signature = declaration;
1604
- if (type.name === Case.pascal(symbol.name)) {
1605
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5019_MEMBER_TYPE_NAME_CONFLICT.create(signature.name, 'property', symbol, type).addRelatedInformationIf(declaringTypeDecl?.name ?? declaringTypeDecl, `The declaring ${type.kind} is introduced here`));
1606
- }
1607
- if (isProhibitedMemberName(symbol.name)) {
1608
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_5016_PROHIBITED_MEMBER_NAME.create(symbol.valueDeclaration ?? symbol.declarations?.[0], symbol.name));
1609
- return;
1610
- }
1611
- this._warnAboutReservedWords(symbol);
1612
- const property = bindings.setPropertyRelatedNode({
1613
- ...this._optionalValue(this._typeChecker.getTypeOfSymbolAtLocation(symbol, signature), signature.type ?? signature.name, 'property type'),
1614
- abstract: _isAbstract(symbol, type) || undefined,
1615
- name: symbol.name,
1616
- protected: _isProtected(symbol) || undefined,
1617
- static: _isStatic(symbol) || undefined,
1618
- locationInModule: this.declarationLocation(signature),
1619
- }, signature);
1620
- if (ts.isGetAccessor(signature)) {
1621
- property.immutable = true;
1622
- for (const decl of symbol.getDeclarations() ?? []) {
1623
- if (!ts.isSetAccessor(decl)) {
1499
+ if ((spDecl.modifiers ?? []).some((x) => x.kind === SyntaxKind.PrivateKeyword)) {
1624
1500
  continue;
1625
1501
  }
1626
- delete property.immutable;
1627
- // Verify the setter doesn't have a Separate Write Type (SWT)
1628
- const valueParam = decl.parameters[0];
1629
- if (valueParam?.type == null) {
1630
- // If there is no type node, there can't be a SWT
1631
- continue;
1502
+ if ((sp.flags & SymbolFlags.Method) !== 0) {
1503
+ methods.push(this._visitMethod(sp, spDecl, true));
1632
1504
  }
1633
- const paramType = this._typeChecker.getTypeFromTypeNode(valueParam.type);
1634
- const paramOptionalValue = this._optionalValue(paramType, valueParam.type, 'parameter type');
1635
- if (property.optional !== paramOptionalValue.optional ||
1636
- (0, spec_1.describeTypeReference)(property.type) !== (0, spec_1.describeTypeReference)(paramOptionalValue.type)) {
1637
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1005_SEPARATE_WRITE_TYPE.create(valueParam.type).addRelatedInformation(signature.type ?? signature.name, 'The getter signature is declared here'));
1505
+ else {
1506
+ props.push(this._visitProperty(sp, spDecl, true));
1638
1507
  }
1639
1508
  }
1640
1509
  }
1641
- else {
1642
- property.immutable = (ts.getCombinedModifierFlags(signature) & ts.ModifierFlags.Readonly) !== 0 || undefined;
1643
- }
1644
- if (signature.questionToken) {
1645
- property.optional = true;
1646
- }
1647
- if (property.static && property.immutable && ts.isPropertyDeclaration(signature) && signature.initializer) {
1648
- property.const = true;
1510
+ if (props.length || strippedProps) {
1511
+ jsiiType.properties = props.sort(compareMembers);
1649
1512
  }
1650
- property.docs = this._visitDocumentation(symbol, ctx).docs;
1651
- type.properties = type.properties ?? [];
1652
- if (type.properties.find((prop) => prop.name === property.name && prop.static === property.static) != null) {
1653
- LOG.trace(`Dropping re-declaration of ${chalk_1.default.green(type.fqn)}#${chalk_1.default.cyan(property.name)}`);
1654
- return;
1513
+ if (methods.length || strippedMethods) {
1514
+ jsiiType.methods = methods.sort(compareMembers);
1655
1515
  }
1656
- type.properties.push(property);
1657
1516
  }
1658
- _toParameter(paramSymbol, ctx) {
1659
- if (LOG.isTraceEnabled()) {
1660
- LOG.trace(`Processing parameter: ${chalk_1.default.cyan(paramSymbol.name)}`);
1661
- }
1662
- const paramDeclaration = paramSymbol.valueDeclaration;
1663
- this._warnAboutReservedWords(paramSymbol);
1664
- const parameter = bindings.setParameterRelatedNode({
1665
- ...this._optionalValue(this._typeChecker.getTypeAtLocation(paramDeclaration), paramDeclaration.type ?? paramDeclaration.name, 'parameter type'),
1666
- name: paramSymbol.name,
1667
- variadic: paramDeclaration.dotDotDotToken && true,
1668
- }, paramDeclaration);
1669
- if (parameter.variadic && spec.isCollectionTypeReference(parameter.type)) {
1670
- // TypeScript types variadic parameters as an array, but JSII uses the item-type instead.
1671
- parameter.type = parameter.type.collection.elementtype;
1672
- }
1673
- else if (paramDeclaration.initializer || paramDeclaration.questionToken) {
1674
- // Optional parameters have an inherently null-able type.
1675
- parameter.optional = true;
1676
- }
1677
- parameter.docs = this._visitDocumentation(paramSymbol, ctx.removeStability()).docs;
1678
- // Don't rewrite doc comment here on purpose -- instead, we add them as '@param'
1679
- // into the parent's doc comment.
1680
- return parameter;
1681
- }
1682
- _typeReference(type, declaration, purpose) {
1683
- const optionalValue = this._optionalValue(type, declaration, purpose);
1684
- if (optionalValue.optional) {
1685
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3999_INCOHERENT_TYPE_MODEL.create(declaration, 'Encountered optional value in location where a plain type reference is expected'));
1686
- }
1687
- return optionalValue.type;
1517
+ /**
1518
+ * Documentation of a class/interface member, inherited like the classic
1519
+ * services did it (`findBaseOfDeclaration`): a member without JSDoc of its own
1520
+ * takes the documentation of the same-named member of the first super type
1521
+ * (`extends` then `implements`, recursively) that documents it. The TypeScript 7
1522
+ * checker already follows base classes, but not implemented interfaces, so the
1523
+ * walk is done here when the checker returns nothing.
1524
+ */
1525
+ _visitMemberDocumentation(msym, decl) {
1526
+ const own = this._visitDocumentation(msym) ?? {};
1527
+ if (own.summary != null || own.remarks != null) {
1528
+ return own;
1529
+ }
1530
+ const { SyntaxKind } = this.ts;
1531
+ const seen = new Set();
1532
+ const inherited = (typeDecl) => {
1533
+ if (typeDecl == null || seen.has(typeDecl)) {
1534
+ return undefined;
1535
+ }
1536
+ seen.add(typeDecl);
1537
+ const clauses = typeDecl.heritageClauses ?? [];
1538
+ const ordered = [
1539
+ ...clauses.filter((h) => h.token === SyntaxKind.ExtendsKeyword),
1540
+ ...clauses.filter((h) => h.token !== SyntaxKind.ExtendsKeyword),
1541
+ ];
1542
+ for (const h of ordered) {
1543
+ for (const t of h.types) {
1544
+ const baseType = this.checker.getTypeAtLocation(t);
1545
+ const prop = baseType && this.checker.getPropertyOfType(baseType, msym.name);
1546
+ if (!prop) {
1547
+ continue;
1548
+ }
1549
+ const docs = this._visitDocumentation(prop);
1550
+ if (docs?.summary != null || docs?.remarks != null) {
1551
+ return docs;
1552
+ }
1553
+ const propDecl = prop.declarations?.[0]?.resolve(this.project);
1554
+ const found = inherited(propDecl?.parent);
1555
+ if (found != null) {
1556
+ return found;
1557
+ }
1558
+ }
1559
+ }
1560
+ return undefined;
1561
+ };
1562
+ // The classic compiler read the comment with inheritance (getDocumentationComment)
1563
+ // but the tags without (getJsDocTags()), so only summary/remarks are taken over.
1564
+ // A parameter property is declared in the constructor; its type is the class.
1565
+ const base = inherited(decl?.kind === SyntaxKind.Parameter ? decl.parent?.parent : decl?.parent);
1566
+ const result = {
1567
+ ...(base?.summary != null ? { summary: base.summary } : {}),
1568
+ ...(base?.remarks != null ? { remarks: base.remarks } : {}),
1569
+ ...own,
1570
+ };
1571
+ return Object.keys(result).length ? result : undefined;
1572
+ }
1573
+ _visitMethod(msym, decl, isStatic) {
1574
+ const { SyntaxKind } = this.ts;
1575
+ const sig = this.checker.getSignatureFromDeclaration(decl);
1576
+ const m = { locationInModule: this._locationOf(decl), name: msym.name };
1577
+ if (isStatic) {
1578
+ m.static = true;
1579
+ }
1580
+ const mods = decl.modifiers ?? [];
1581
+ if (mods.some((x) => x.kind === SyntaxKind.AbstractKeyword)) {
1582
+ m.abstract = true;
1583
+ }
1584
+ if (mods.some((x) => x.kind === SyntaxKind.ProtectedKeyword)) {
1585
+ m.protected = true;
1586
+ }
1587
+ if (sig) {
1588
+ const params = sig.getParameters().map((p) => this._visitParameter(p));
1589
+ if (params.length) {
1590
+ m.parameters = params;
1591
+ }
1592
+ if (params.some((p) => p.variadic)) {
1593
+ m.variadic = true;
1594
+ }
1595
+ const opt = {};
1596
+ let retType = this.checker.getReturnTypeOfSignature(sig);
1597
+ let retNode = decl.type;
1598
+ // Promise-returning methods: jsii marks them `async` and models the
1599
+ // resolved type (Promise<string> -> string), like strada.
1600
+ if (retType && typeof retType.isTypeReference === 'function' && retType.isTypeReference()) {
1601
+ const tsym = retType.getTarget?.()?.getSymbol?.();
1602
+ if (tsym?.name === 'Promise' && this._isStdlibDecl(tsym)) {
1603
+ m.async = true;
1604
+ retType = this.checker.getTypeArguments(retType)?.[0];
1605
+ retNode = retNode?.typeArguments?.[0];
1606
+ }
1607
+ }
1608
+ const ret = this._typeReference(retType, opt, retNode);
1609
+ if (ret) {
1610
+ m.returns = opt.optional ? { optional: true, type: ret } : { type: ret };
1611
+ }
1612
+ }
1613
+ const d = this._visitMemberDocumentation(msym, decl);
1614
+ if (d) {
1615
+ m.docs = d;
1616
+ }
1617
+ return this._withDefaultDocs(m);
1618
+ }
1619
+ _visitProperty(psym, decl, isStatic) {
1620
+ const { SyntaxKind } = this.ts;
1621
+ const t = this.checker.getTypeOfSymbolAtLocation(psym, decl);
1622
+ const opt = {};
1623
+ const p = {
1624
+ locationInModule: this._locationOf(decl),
1625
+ name: psym.name,
1626
+ type: this._typeReference(t, opt, decl.type),
1627
+ };
1628
+ const mods = decl.modifiers ?? [];
1629
+ const hasSetter = psym.declarations?.some((h) => h.kind === SyntaxKind.SetAccessor);
1630
+ if (mods.some((x) => x.kind === SyntaxKind.ReadonlyKeyword) ||
1631
+ (decl.kind === SyntaxKind.GetAccessor && !hasSetter)) {
1632
+ p.immutable = true;
1633
+ }
1634
+ if (mods.some((x) => x.kind === SyntaxKind.ProtectedKeyword)) {
1635
+ p.protected = true;
1636
+ }
1637
+ if (mods.some((x) => x.kind === SyntaxKind.AbstractKeyword)) {
1638
+ p.abstract = true;
1639
+ }
1640
+ if (isStatic) {
1641
+ p.static = true;
1642
+ if (mods.some((x) => x.kind === SyntaxKind.ReadonlyKeyword)) {
1643
+ p.const = true;
1644
+ }
1645
+ }
1646
+ const q = decl.questionToken ?? (decl.postfixToken?.kind === SyntaxKind.QuestionToken ? decl.postfixToken : undefined);
1647
+ if (q != null || opt.optional) {
1648
+ p.optional = true;
1649
+ }
1650
+ const d = this._visitMemberDocumentation(psym, decl) ?? {};
1651
+ if (decl.kind === SyntaxKind.Parameter) {
1652
+ // Classic: the documentation comment of a parameter property is its own
1653
+ // JSDoc followed by the constructor's `@param <name>` text (when present).
1654
+ const paramText = this._paramDocComment(psym, decl);
1655
+ const own = this._docCommentWithClassicLinks(psym);
1656
+ const ownText = typeof own === 'string' ? own.trim() : '';
1657
+ // The TypeScript 7 checker already uses the `@param` text when the
1658
+ // parameter has no JSDoc of its own; the combination with an own comment,
1659
+ // and the fallback when the own JSDoc block only holds tags, are missing.
1660
+ if (paramText && !ownText.includes(paramText.trim())) {
1661
+ const combined = [ownText, paramText.trim()].filter(Boolean).join('\n');
1662
+ const { summary, remarks } = this._splitSummary(combined);
1663
+ delete d.remarks;
1664
+ if (remarks) {
1665
+ d.remarks = remarks;
1666
+ }
1667
+ d.summary = summary;
1668
+ }
1669
+ }
1670
+ if (Object.keys(d).length) {
1671
+ p.docs = d;
1672
+ }
1673
+ return this._withDefaultDocs(p);
1674
+ }
1675
+ _visitParameter(prm) {
1676
+ const decl = prm.declarations?.[0]?.resolve(this.project);
1677
+ const t = decl ? this.checker.getTypeOfSymbolAtLocation(prm, decl) : undefined;
1678
+ const opt = {};
1679
+ const p = { name: prm.name, type: this._typeReference(t, opt, decl?.type) };
1680
+ if (decl?.dotDotDotToken) {
1681
+ p.variadic = true;
1682
+ p.type = p.type?.collection?.elementtype ?? p.type;
1683
+ }
1684
+ else if (decl?.questionToken != null || decl?.initializer != null || opt.optional) {
1685
+ p.optional = true;
1686
+ }
1687
+ // Parameter docs mirror TS5's services semantics that strada relies on:
1688
+ // 1. the `@param` tag from the JSDoc of the function declaration that OWNS
1689
+ // the parameter (never the base/overridden signature's @param — method
1690
+ // params do NOT inherit docs);
1691
+ // 2. when a CONSTRUCTOR parameter has no own @param, TS5's
1692
+ // findBaseOfDeclaration falls back to the documentation of a PROPERTY
1693
+ // with the parameter's name on the first super type that has one (this
1694
+ // is how e.g. RemoveTag's ctor param `key` gets TagBase.key's doc).
1695
+ // The tsgo checker's doc APIs implement different inheritance (methods
1696
+ // over-inherit, some @param tags are missed), so the @param text is read
1697
+ // straight from the owning declaration's JSDoc source text.
1698
+ // TS collects parameter docs from BOTH an inline JSDoc block directly on
1699
+ // the parameter declaration (common for documented parameter properties)
1700
+ // and the `@param` tag of the owning function's JSDoc; when both exist
1701
+ // they are concatenated (inline first), as strada's output shows.
1702
+ const inline = this._inlineJsDocText(decl);
1703
+ const tagText = this._paramDocComment(prm, decl);
1704
+ let comments = inline != null && tagText != null ? `${inline}\n${tagText}` : inline ?? tagText;
1705
+ if (comments === undefined && decl?.parent?.kind === this.ts.SyntaxKind.Constructor) {
1706
+ comments = this._inheritedCtorParamDoc(prm, decl);
1707
+ }
1708
+ if (comments) {
1709
+ const { summary, remarks } = this._splitSummary(comments);
1710
+ const docs = {};
1711
+ if (remarks) {
1712
+ docs.remarks = remarks;
1713
+ }
1714
+ if (summary) {
1715
+ docs.summary = summary;
1716
+ }
1717
+ if (Object.keys(docs).length) {
1718
+ p.docs = docs;
1719
+ }
1720
+ }
1721
+ return p;
1688
1722
  }
1689
- _optionalValue(type, declaration, purpose) {
1690
- const isThisType = _isThisType(type, this._typeChecker, declaration?.parent);
1691
- if (type.isLiteral() && _isEnumLike(type)) {
1692
- type = this._typeChecker.getBaseTypeOfLiteralType(type);
1693
- }
1694
- else {
1695
- type = this._typeChecker.getApparentType(type);
1723
+ /**
1724
+ * Extract the `@param <name>` description for a parameter from the JSDoc
1725
+ * block that immediately precedes its owning function declaration. Returns
1726
+ * undefined when the declaration has no JSDoc or no matching @param tag.
1727
+ */
1728
+ _paramDocComment(prm, paramDecl) {
1729
+ const funcDecl = paramDecl?.parent;
1730
+ const block = funcDecl ? this._leadingJsDocBlock(funcDecl) : undefined;
1731
+ if (!block) {
1732
+ return undefined;
1696
1733
  }
1697
- const primitiveType = _tryMakePrimitiveType.call(this);
1698
- if (primitiveType) {
1699
- return { type: primitiveType };
1734
+ const out = [];
1735
+ let capturing = false;
1736
+ let done = false;
1737
+ // A new `@tag` starts even MID-LINE in the TS JSDoc parser (e.g.
1738
+ // "...Lambda function. @see Permission for details." ends the @param text
1739
+ // before "@see"), except inside an inline `{@link ...}`.
1740
+ const cutInlineTag = (s) => {
1741
+ const m = /(?:^|[^{\S])@[A-Za-z]/.exec(s);
1742
+ if (!m) {
1743
+ return { text: s, cut: false };
1744
+ }
1745
+ const at = s.indexOf('@', m.index);
1746
+ return { text: s.slice(0, at).replace(/\s+$/, ''), cut: true };
1747
+ };
1748
+ for (const line of this._jsDocLines(block)) {
1749
+ if (done) {
1750
+ break;
1751
+ }
1752
+ if (capturing) {
1753
+ if (/^@/.test(line)) {
1754
+ break;
1755
+ }
1756
+ const { text, cut } = cutInlineTag(line);
1757
+ out.push(text);
1758
+ done = cut;
1759
+ continue;
1760
+ }
1761
+ // Keep the text verbatim after the parameter name (including a leading
1762
+ // `- ` separator — strada keeps it in the summary).
1763
+ // Accept `@param name`, `@param [name]` and `@param [name=default]`
1764
+ // (JSDoc optional-parameter syntax), with an optional `{type}` prefix.
1765
+ const m = /^@param\s+(?:\{[^}]*\}\s+)?(?:\[([\w$]+)(?:=[^\]]*)?\]|([\w$]+))\s*(.*)$/.exec(line);
1766
+ if (m && (m[1] ?? m[2]) === prm.name) {
1767
+ capturing = true;
1768
+ const { text, cut } = cutInlineTag(m[3]);
1769
+ out.push(text);
1770
+ done = cut;
1771
+ }
1700
1772
  }
1701
- if (type.isUnion() && !_isEnumLike(type)) {
1702
- return _setType.call(this, 'union');
1773
+ if (!capturing) {
1774
+ return undefined;
1703
1775
  }
1704
- if (type.isIntersection()) {
1705
- this.usedFeatures.add('intersection-types');
1706
- const ret = _setType.call(this, 'intersection');
1707
- const intersectionType = ret.type;
1708
- this.validateIntersectionType(intersectionType, declaration);
1709
- return ret;
1776
+ const result = out.join('\n').trim();
1777
+ return result === '' ? undefined : result;
1778
+ }
1779
+ /** Source text of a declaration's file (client-side cache; no RPC). */
1780
+ _sourceTextOf(sf) {
1781
+ if (typeof sf?.text === 'string') {
1782
+ return sf.text;
1710
1783
  }
1711
- if ((type.getFlags() & ts.TypeFlags.Never) !== 0) {
1712
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1007_NEVER_TYPE.create(declaration));
1713
- return { type: spec.CANONICAL_ANY };
1784
+ let text = this._sourceTextCache.get(sf?.fileName);
1785
+ if (text === undefined) {
1786
+ try {
1787
+ text = fs.readFileSync(sf.fileName, 'utf8');
1788
+ }
1789
+ catch {
1790
+ text = '';
1791
+ }
1792
+ this._sourceTextCache.set(sf.fileName, text);
1714
1793
  }
1715
- if (!type.symbol) {
1716
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1001_TYPE_HAS_NO_SYMBOL.create(declaration));
1717
- return { type: spec.CANONICAL_ANY };
1794
+ return text;
1795
+ }
1796
+ /** The last JSDoc block in a node's leading trivia, or undefined. */
1797
+ _leadingJsDocBlock(node) {
1798
+ const sf = node?.getSourceFile?.();
1799
+ if (!sf) {
1800
+ return undefined;
1718
1801
  }
1719
- if (type.symbol.name === 'Array') {
1720
- return { type: _arrayType.call(this) };
1802
+ const text = this._sourceTextOf(sf);
1803
+ if (!text) {
1804
+ return undefined;
1721
1805
  }
1722
- if (type.symbol.name === '__type' && type.symbol.members) {
1723
- return { type: _mapType.call(this) };
1806
+ const leading = text.slice(node.pos, node.getStart(sf));
1807
+ const blocks = leading.match(/\/\*\*[\s\S]*?\*\//g);
1808
+ return blocks && blocks.length ? blocks[blocks.length - 1] : undefined;
1809
+ }
1810
+ /** Margin-stripped lines of a JSDoc block. */
1811
+ _jsDocLines(block) {
1812
+ return block
1813
+ .replace(/^\/\*\*/, '')
1814
+ .replace(/\*\/$/, '')
1815
+ .split('\n')
1816
+ .map((l) => l.replace(/^\s*\*?\s*/, '').replace(/\s+$/, ''));
1817
+ }
1818
+ /** Full text of an inline JSDoc block attached to a declaration, or undefined. */
1819
+ _inlineJsDocText(decl) {
1820
+ const block = decl ? this._leadingJsDocBlock(decl) : undefined;
1821
+ if (!block) {
1822
+ return undefined;
1724
1823
  }
1725
- if (type.symbol.escapedName === 'Promise') {
1726
- const typeRef = type;
1727
- if (!typeRef.typeArguments || typeRef.typeArguments.length !== 1) {
1728
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1002_UNSPECIFIED_PROMISE.create(declaration));
1729
- return { type: spec.CANONICAL_ANY };
1824
+ const textLines = [];
1825
+ for (const line of this._jsDocLines(block)) {
1826
+ if (/^@/.test(line)) {
1827
+ break;
1730
1828
  }
1731
- return {
1732
- type: this._typeReference(typeRef.typeArguments[0], declaration, purpose),
1733
- };
1829
+ textLines.push(line);
1734
1830
  }
1735
- const fqn = this._getFQN(type, declaration, purpose, isThisType);
1736
- if (fqn == null) {
1737
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_9997_UNKNOWN_ERROR.create(declaration, new Error('Could not determine FQN')));
1738
- return { type: { fqn: '' } };
1831
+ const result = textLines.join('\n').trim();
1832
+ return result === '' ? undefined : result;
1833
+ }
1834
+ /**
1835
+ * Build a jsii docs object from a declaration's leading JSDoc, mirroring what
1836
+ * `_visitDocumentation` produces from the symbol doc APIs (summary/remarks +
1837
+ * the doc tags jsii consumes). Used for constructor (initializer) docs, where
1838
+ * no symbol-level doc read exists on the ts path.
1839
+ */
1840
+ _docsFromDeclJsDoc(decl) {
1841
+ const block = this._leadingJsDocBlock(decl);
1842
+ if (!block) {
1843
+ return undefined;
1739
1844
  }
1740
- return {
1741
- type: { fqn },
1742
- };
1743
- function _arrayType() {
1744
- const typeRef = type;
1745
- let elementtype;
1746
- if (typeRef.typeArguments?.length === 1) {
1747
- elementtype = this._typeReference(typeRef.typeArguments[0], declaration, 'list element type');
1845
+ const lines = this._jsDocLines(block);
1846
+ const commentLines = [];
1847
+ const tags = [];
1848
+ let current;
1849
+ for (const line of lines) {
1850
+ const tm = /^@([A-Za-z][\w-]*)\s*(.*)$/.exec(line);
1851
+ if (tm) {
1852
+ if (current) {
1853
+ tags.push({ name: current.name, text: current.text.join('\n') });
1854
+ }
1855
+ current = { name: tm[1], text: [tm[2]] };
1748
1856
  }
1749
- else {
1750
- const count = typeRef.typeArguments ? typeRef.typeArguments.length : 'none';
1751
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1003_UNSUPPORTED_TYPE.create(declaration, `Array references must have exactly one type argument (found ${count})`));
1752
- elementtype = spec.CANONICAL_ANY;
1753
- }
1754
- return {
1755
- collection: {
1756
- elementtype,
1757
- kind: spec.CollectionKind.Array,
1758
- },
1759
- };
1760
- }
1761
- function _mapType() {
1762
- let elementtype;
1763
- const objectType = type.getStringIndexType();
1764
- if (objectType) {
1765
- elementtype = this._typeReference(objectType, declaration, 'map element type');
1857
+ else if (current) {
1858
+ current.text.push(line);
1766
1859
  }
1767
1860
  else {
1768
- const typeDecl = type.symbol.declarations?.[0];
1769
- if (typeDecl != null &&
1770
- ts.isTypeLiteralNode(typeDecl) &&
1771
- typeDecl.members.length == 1 &&
1772
- ts.isIndexSignatureDeclaration(typeDecl.members[0]) &&
1773
- typeDecl.members[0].parameters[0].type != null &&
1774
- ts.isTemplateLiteralTypeNode(typeDecl.members[0].parameters[0].type)) {
1775
- const indexTypeNode = typeDecl.members[0].type;
1776
- const indexType = this._typeChecker.getTypeFromTypeNode(indexTypeNode);
1777
- elementtype = this._typeReference(indexType, indexTypeNode, 'map element type');
1778
- }
1779
- else {
1780
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1003_UNSUPPORTED_TYPE.create(declaration, 'Only string-indexed map types are supported'));
1781
- elementtype = spec.CANONICAL_ANY;
1782
- }
1861
+ commentLines.push(line);
1783
1862
  }
1784
- return {
1785
- collection: {
1786
- elementtype,
1787
- kind: spec.CollectionKind.Map,
1788
- },
1789
- };
1790
1863
  }
1791
- function _tryMakePrimitiveType() {
1792
- if (!type.symbol) {
1793
- if (type.flags & ts.TypeFlags.Object) {
1794
- if (isTupleType(type)) {
1795
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1999_UNSUPPORTED.create(declaration, { what: 'Tuple types', alternative: 'arrays' }));
1796
- }
1797
- return { primitive: spec.PrimitiveType.Json };
1798
- }
1799
- if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
1800
- return spec.CANONICAL_ANY;
1801
- }
1802
- }
1803
- else if (type.symbol.valueDeclaration &&
1804
- isUnder(type.symbol.valueDeclaration.getSourceFile().fileName, this.stdlib)) {
1805
- switch (type.symbol.name) {
1806
- case 'Boolean':
1807
- return { primitive: spec.PrimitiveType.Boolean };
1808
- case 'Date':
1809
- return { primitive: spec.PrimitiveType.Date };
1810
- case 'Number':
1811
- return { primitive: spec.PrimitiveType.Number };
1812
- case 'String':
1813
- return { primitive: spec.PrimitiveType.String };
1814
- }
1864
+ if (current) {
1865
+ tags.push({ name: current.name, text: current.text.join('\n') });
1866
+ }
1867
+ const docs = {};
1868
+ const comment = commentLines.join('\n').trim();
1869
+ if (comment) {
1870
+ const { summary, remarks } = this._splitSummary(comment);
1871
+ if (remarks) {
1872
+ docs.remarks = remarks;
1815
1873
  }
1816
- // Not a primitive type!
1817
- return undefined;
1874
+ docs.summary = summary;
1818
1875
  }
1819
- function _setType(field) {
1820
- const types = new Array();
1821
- let optional;
1822
- for (const subType of type.types) {
1823
- if (subType.flags & ts.TypeFlags.Undefined) {
1824
- optional = true;
1825
- continue;
1826
- }
1827
- // eslint-disable-next-line no-await-in-loop
1828
- const resolvedType = this._typeReference(subType, declaration, purpose);
1829
- if (types.some((ref) => (0, es6_1.default)(ref, resolvedType))) {
1830
- continue;
1831
- }
1832
- types.push(resolvedType);
1876
+ for (const tag of tags) {
1877
+ const tagText = tag.text.replace(/\{@link\s+([^}]*?)\s*\}/g, '{@link $1 }');
1878
+ switch (tag.name) {
1879
+ case 'default':
1880
+ docs.default = tagText.trim();
1881
+ break;
1882
+ case 'deprecated':
1883
+ docs.deprecated = tagText.trim();
1884
+ docs.stability = 'deprecated';
1885
+ break;
1886
+ case 'stability':
1887
+ docs.stability = tagText.trim();
1888
+ break;
1889
+ case 'example':
1890
+ docs.example = tagText.replace(/^\n/, '');
1891
+ break;
1892
+ case 'returns':
1893
+ docs.returns = tagText.trim();
1894
+ break;
1895
+ case 'see':
1896
+ docs.see = tagText.trim();
1897
+ break;
1898
+ default:
1899
+ break;
1833
1900
  }
1834
- const returnedType = {
1835
- [field]: { types },
1836
- };
1837
- return types.length === 1 ? { optional, type: types[0] } : { optional, type: returnedType };
1838
1901
  }
1902
+ return Object.keys(docs).length ? docs : undefined;
1839
1903
  }
1840
1904
  /**
1841
- * Validate the restrictions on an intersection type reference
1842
- *
1843
- * - Type only consists of (behavioral) interface types
1844
- * - For all types referenced in the intersection, the definitions of all shared
1845
- * members must match exactly.
1905
+ * TS5 `findBaseOfDeclaration` fallback for constructor parameters: the first
1906
+ * super type (extends/implements, in source order) that has a PROPERTY named
1907
+ * like the parameter contributes that property's documentation; the search
1908
+ * stops at the first super type owning such a property even when its docs
1909
+ * are empty. Method parameters have no such fallback.
1846
1910
  */
1847
- validateIntersectionType(intersectionType, declaration) {
1848
- // Validate that this intersection type only consists of interface types
1849
- this._deferUntilTypesAvailable('', intersectionType.intersection.types, declaration, (...elementTypes) => {
1850
- const requestedFqns = new Set(intersectionType.intersection.types.map(type_reference_1.typeReferenceToString));
1851
- const resolvedFqns = new Set(elementTypes.map((t) => t.fqn));
1852
- const unresolved = sets_1.Sets.diff(requestedFqns, resolvedFqns);
1853
- if (unresolved.size > 0) {
1854
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1008_ONLY_INTERFACE_INTERSECTION.create(declaration, Array.from(unresolved).join(', ')));
1855
- }
1856
- const nonBehavioral = elementTypes.filter((t) => !(0, type_visitor_1.isBehavioralInterfaceType)(t));
1857
- if (nonBehavioral.length > 0) {
1858
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1008_ONLY_INTERFACE_INTERSECTION.create(declaration, nonBehavioral.map((t) => t.fqn).join(', ')));
1859
- }
1860
- // Check that shared members are the same
1861
- const interfaces = elementTypes.filter(type_visitor_1.isBehavioralInterfaceType);
1862
- const allProps = sets_1.Sets.union(...interfaces.map((int) => this.allProperties(int)));
1863
- const allMethods = sets_1.Sets.union(...interfaces.map((int) => this.allMethods(int)));
1864
- for (let i = 1; i < interfaces.length; i++) {
1865
- let int0 = interfaces[0];
1866
- let int1 = interfaces[i];
1867
- for (const prop of allProps) {
1868
- const p1 = int0.properties?.find((p) => p.name === prop);
1869
- const p2 = int1.properties?.find((p) => p.name === prop);
1870
- const diff = this.comparePropForIntersection(p1, p2);
1871
- if (diff) {
1872
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1011_INTERSECTION_MEMBER_DIFFERENT.create(declaration, prop, int0.name, diff[0], int1.name, diff[1]));
1873
- }
1874
- }
1875
- for (const meth of allMethods) {
1876
- const m1 = int0.methods?.find((p) => p.name === meth);
1877
- const m2 = int1.methods?.find((p) => p.name === meth);
1878
- const diff = this.compareMethodForIntersection(m1, m2);
1879
- if (diff) {
1880
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1011_INTERSECTION_MEMBER_DIFFERENT.create(declaration, meth, int0.name, diff[0], int1.name, diff[1]));
1881
- }
1911
+ _inheritedCtorParamDoc(prm, paramDecl) {
1912
+ return this._inheritedPropDocFromBases(paramDecl.parent?.parent, prm.name, new Set());
1913
+ }
1914
+ /**
1915
+ * TS5 `findBaseOfDeclaration` search: the first super type (extends /
1916
+ * implements, in source order) of a class/interface declaration that has a
1917
+ * property with the given name contributes that property's documentation —
1918
+ * even when empty (the search stops there). Doc resolution for the found
1919
+ * property is itself recursive: a class element with no own JSDoc inherits
1920
+ * from ITS super types (e.g. a getter overriding an interface property).
1921
+ */
1922
+ _inheritedPropDocFromBases(classOrIfaceDecl, name, seen) {
1923
+ for (const h of classOrIfaceDecl?.heritageClauses ?? []) {
1924
+ for (const t of h.types ?? []) {
1925
+ const s = this._heritageBaseSymbol(t);
1926
+ const baseDecl = s?.declarations?.[0]?.resolve(this.project);
1927
+ const baseType = baseDecl ? this.checker.getTypeAtLocation(baseDecl) : undefined;
1928
+ const psym = baseType ? this.checker.getPropertyOfType(baseType, name) : undefined;
1929
+ if (psym) {
1930
+ return this._symbolDocTextFromSource(psym, seen);
1882
1931
  }
1883
1932
  }
1884
- });
1933
+ }
1934
+ return undefined;
1885
1935
  }
1886
- comparePropForIntersection(a, b) {
1887
- if (!a || !b) {
1936
+ /**
1937
+ * Documentation text of a member symbol, read from source (the tsgo doc APIs
1938
+ * return an empty comment for several of these members — one of the JSDoc
1939
+ * behaviour gaps this backend works around). A constructor parameter
1940
+ * property's docs come from an inline JSDoc on the parameter or the
1941
+ * constructor's `@param` tag; other members use their leading JSDoc. Empty
1942
+ * own docs recurse into the owner's super types.
1943
+ */
1944
+ _symbolDocTextFromSource(psym, seen) {
1945
+ const { SyntaxKind } = this.ts;
1946
+ const d0 = psym.declarations?.[0];
1947
+ const key = `${d0?.path}:${d0?.index}`;
1948
+ if (!d0 || seen.has(key)) {
1888
1949
  return undefined;
1889
1950
  }
1890
- if (!(0, type_reference_1.typeReferenceEqual)(a.type, b.type)) {
1891
- return [(0, type_reference_1.typeReferenceToString)(a.type), (0, type_reference_1.typeReferenceToString)(b.type)];
1951
+ seen.add(key);
1952
+ const pd = d0.resolve(this.project);
1953
+ if (!pd) {
1954
+ return undefined;
1892
1955
  }
1893
- return (cmpDesc(a.static, b.static, (s) => (s ? 'static' : 'instance member')) ??
1894
- cmpDesc(a.optional, b.optional, (o) => (o ? 'optional' : 'required')) ??
1895
- cmpDesc(a.abstract, b.abstract, (s) => (s ? 'abstract' : 'concrete')));
1896
- }
1897
- compareMethodForIntersection(a, b) {
1898
- if (!a || !b) {
1956
+ const own = pd.kind === SyntaxKind.Parameter
1957
+ ? this._inlineJsDocText(pd) ?? this._paramDocComment(psym, pd)
1958
+ : this._inlineJsDocText(pd);
1959
+ if (own !== undefined) {
1960
+ return own;
1961
+ }
1962
+ const owner = pd.parent?.kind === SyntaxKind.Constructor ? pd.parent.parent : pd.parent;
1963
+ return this._inheritedPropDocFromBases(owner, psym.name, seen);
1964
+ }
1965
+ // -------------------------------------------------------------------------
1966
+ // type references (strada: _typeReference / _optionalValue)
1967
+ // -------------------------------------------------------------------------
1968
+ _unionNodeOf(typeNode) {
1969
+ const { SyntaxKind } = this.ts;
1970
+ if (!typeNode) {
1899
1971
  return undefined;
1900
1972
  }
1901
- if (a.returns && b.returns) {
1902
- if (!(0, type_reference_1.typeReferenceEqual)(a.returns.type, b.returns.type)) {
1903
- return [(0, type_reference_1.typeReferenceToString)(a.returns.type), (0, type_reference_1.typeReferenceToString)(b.returns.type)];
1904
- }
1905
- const x = cmpDesc(a.returns.optional, b.returns.optional, (o) => o ? 'return type optional' : 'return type required');
1906
- if (x) {
1907
- return x;
1908
- }
1909
- }
1910
- const paramsA = a.parameters ?? [];
1911
- const paramsB = b.parameters ?? [];
1912
- if (paramsA.length !== paramsB.length) {
1913
- return [`${paramsA.length} parameters`, `${paramsB.length} parameters`];
1914
- }
1915
- for (let i = 0; i < paramsA.length; i++) {
1916
- const p1 = paramsA[i];
1917
- const p2 = paramsB[i];
1918
- if (!(0, type_reference_1.typeReferenceEqual)(p1.type, p2.type)) {
1919
- return [(0, type_reference_1.typeReferenceToString)(p1.type), (0, type_reference_1.typeReferenceToString)(p2.type)];
1920
- }
1921
- const x = cmpDesc(p1.optional, p2.optional, (o) => (o ? `parameter ${i + 1} optional` : `parameter ${i + 1} required`)) ??
1922
- cmpDesc(p1.variadic, p2.variadic, (v) => v ? `parameter ${i + 1} variadic` : `parameter ${i + 1} not variadic`);
1923
- if (x) {
1924
- return x;
1925
- }
1926
- }
1927
- return (cmpDesc(a.abstract, b.abstract, (s) => (s ? 'abstract' : 'concrete')) ??
1928
- cmpDesc(a.async, b.async, (s) => (s ? 'async' : 'async')) ??
1929
- cmpDesc(a.protected, b.protected, (p) => (p ? 'protected' : 'public')) ??
1930
- cmpDesc(a.variadic, b.variadic, (v) => (v ? 'variadic' : 'non-variadic')) ??
1931
- cmpDesc(a.static, b.static, (s) => (s ? 'static' : 'instance member')));
1932
- }
1933
- callDeferredsInOrder() {
1934
- // Do a topological call order of all deferreds.
1935
- while (this._deferred.length > 0) {
1936
- // All fqns in dependency lists that don't have any pending
1937
- // deferreds themselves can be executed now, so are removed from
1938
- // dependency lists.
1939
- const pendingFqns = new Set(this._deferred.map((x) => x.fqn).filter((x) => x));
1940
- for (const deferred of this._deferred) {
1941
- restrictDependenciesTo(deferred, pendingFqns);
1942
- }
1943
- // Invoke all deferreds with no more dependencies and remove them from the list.
1944
- let invoked = false;
1945
- for (let i = 0; i < this._deferred.length; i++) {
1946
- if (this._deferred[i].dependedFqns.length === 0) {
1947
- const deferred = this._deferred.splice(i, 1)[0];
1948
- deferred.cb();
1949
- invoked = true;
1950
- }
1951
- }
1952
- if (!invoked) {
1953
- // Apparently we're stuck. Complain loudly.
1954
- throw new Error(`Could not invoke any more deferreds, cyclic dependency? Remaining: ${JSON.stringify(this._deferred, undefined, 2)}`);
1955
- }
1973
+ if (typeNode.kind === SyntaxKind.UnionType) {
1974
+ return typeNode;
1956
1975
  }
1957
- /**
1958
- * Retain only elements in the dependencyfqn that are also in the set
1959
- */
1960
- function restrictDependenciesTo(def, fqns) {
1961
- def.dependedFqns = def.dependedFqns.filter(fqns.has.bind(fqns));
1976
+ if (typeNode.kind === SyntaxKind.TypeReference) {
1977
+ const s0 = this._symbolAtNodeSafe(typeNode.typeName) ?? this._aliasSymbolAt(typeNode);
1978
+ const s = s0 ? this._resolveAlias(s0) : undefined;
1979
+ const d = s?.declarations?.[0]?.resolve(this.project);
1980
+ if (d?.kind === SyntaxKind.TypeAliasDeclaration && d.type?.kind === SyntaxKind.UnionType) {
1981
+ return d.type;
1982
+ }
1962
1983
  }
1984
+ return undefined;
1963
1985
  }
1964
1986
  /**
1965
- * Return the set of all (inherited) properties of an interface
1987
+ * Client-side array-type check to avoid an out-of-process `checker.isArrayType`
1988
+ * RPC on every type reference (~85k on aws-cdk-lib). `type.isTypeReference()`
1989
+ * is a local objectFlags bit; the target's symbol name (`Array`/`ReadonlyArray`
1990
+ * from a `lib.*.d.ts`) is resolved client-side after the global Array type is
1991
+ * fetched once. Verified to produce identical `.jsii` vs `checker.isArrayType`.
1966
1992
  */
1967
- allProperties(root) {
1968
- return this.allInterfacesRecursively(root, (int) => {
1969
- return (int.properties ?? []).map((p) => p.name);
1970
- });
1993
+ _isArrayType(type) {
1994
+ if (typeof type.isTypeReference !== 'function' || !type.isTypeReference()) {
1995
+ return false;
1996
+ }
1997
+ const target = type.getTarget?.() ?? type;
1998
+ const tsym = target?.getSymbol?.();
1999
+ const name = tsym?.name;
2000
+ if (name !== 'Array' && name !== 'ReadonlyArray') {
2001
+ return false;
2002
+ }
2003
+ // must be the built-in Array from the standard library (not a user type)
2004
+ return this._isStdlibDecl(tsym);
1971
2005
  }
1972
- /**
1973
- * Return the set of all (inherited) methods of an interface
1974
- */
1975
- allMethods(root) {
1976
- return this.allInterfacesRecursively(root, (int) => {
1977
- return (int.methods ?? []).map((p) => p.name);
1978
- });
2006
+ /** Whether the symbol's first declaration lives in a standard-library lib.*.d.ts. */
2007
+ _isStdlibDecl(sym) {
2008
+ return isStdlibDeclPath(sym?.declarations?.[0]?.path ?? '');
1979
2009
  }
1980
- allInterfacesRecursively(root, cb) {
1981
- const ret = new Set();
1982
- recurse.call(this, root);
1983
- return ret;
1984
- function recurse(int) {
1985
- for (const x of cb(int)) {
1986
- ret.add(x);
1987
- }
1988
- for (const baseRef of int.interfaces ?? []) {
1989
- const base = this._dereference(baseRef, undefined, 'used-in-syntax');
1990
- if (!base) {
1991
- throw new Error('Impossible to have unresolvable base in allInterfacesRecursively()');
1992
- }
1993
- if (!spec.isInterfaceType(base)) {
1994
- throw new Error('Impossible to have non-interface base in allInterfacesRecursively()');
1995
- }
1996
- recurse.call(this, base);
2010
+ _typeReference(type, optionalOut, typeNode) {
2011
+ const { TypeFlags } = this.ts;
2012
+ if (!type) {
2013
+ return { primitive: 'any' };
2014
+ }
2015
+ const f = type.flags;
2016
+ if (f & TypeFlags.EnumLike) {
2017
+ const s = type.getSymbol();
2018
+ const parent = s?.getParent();
2019
+ const fqn = s &&
2020
+ (this.typeFqnBySymbolId.get(s.id) ??
2021
+ this._externalFqnOf(s) ??
2022
+ (parent && (this.typeFqnBySymbolId.get(parent.id) ?? this._externalFqnOf(parent))));
2023
+ if (fqn) {
2024
+ return { fqn };
1997
2025
  }
1998
2026
  }
1999
- }
2000
- _verifyConsecutiveOptionals(node, parameters) {
2001
- if (!parameters) {
2002
- return;
2027
+ if (f & TypeFlags.NonPrimitive) {
2028
+ return { primitive: 'json' };
2003
2029
  }
2004
- const remaining = [...parameters].reverse();
2005
- while (remaining.length > 0) {
2006
- const current = remaining.pop();
2007
- if (current.optional) {
2008
- const offender = remaining.find((p) => !p.optional && !p.variadic);
2009
- if (offender == null) {
2010
- continue;
2011
- }
2012
- this._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_3009_OPTIONAL_PARAMETER_BEFORE_REQUIRED.create(node, current, offender));
2013
- delete current.optional;
2030
+ if (f & TypeFlags.StringLike) {
2031
+ return { primitive: 'string' };
2032
+ }
2033
+ if (f & TypeFlags.NumberLike) {
2034
+ return { primitive: 'number' };
2035
+ }
2036
+ if (f & TypeFlags.BooleanLike) {
2037
+ return { primitive: 'boolean' };
2038
+ }
2039
+ if (f & (TypeFlags.Any | TypeFlags.Unknown)) {
2040
+ return { primitive: 'any' };
2041
+ }
2042
+ if (f & TypeFlags.Void) {
2043
+ return undefined;
2044
+ }
2045
+ if (type.isUnionType()) {
2046
+ return this._unionTypeReference(type, optionalOut, typeNode);
2047
+ }
2048
+ if (typeof type.isIntersectionType === 'function' && type.isIntersectionType()) {
2049
+ return this._intersectionTypeReference(type);
2050
+ }
2051
+ if (this._isArrayType(type)) {
2052
+ const args = type.isTypeReference() ? this.checker.getTypeArguments(type) : [];
2053
+ return { collection: { elementtype: this._typeReference(args[0]), kind: 'array' } };
2054
+ }
2055
+ const sym = type.getSymbol();
2056
+ // Boxed standard-library wrapper types map to primitives (strada's
2057
+ // _tryMakePrimitiveType): e.g. `limit?: Number` or `Array<String>`.
2058
+ if (sym && this._isStdlibDecl(sym)) {
2059
+ switch (sym.name) {
2060
+ case 'Boolean':
2061
+ return { primitive: 'boolean' };
2062
+ case 'Date':
2063
+ return { primitive: 'date' };
2064
+ case 'Number':
2065
+ return { primitive: 'number' };
2066
+ case 'String':
2067
+ return { primitive: 'string' };
2068
+ default:
2069
+ break;
2014
2070
  }
2015
2071
  }
2016
- }
2017
- /**
2018
- * Updates the runtime type info with the fully-qualified name for the current class definition.
2019
- * Used by the runtime type info injector to add this information to the compiled file.
2020
- */
2021
- registerExportedClassFqn(clazz, fqn) {
2022
- this.runtimeTypeInfoInjector.registerClassFqn(clazz, fqn);
2023
- }
2024
- /**
2025
- * Return only those submodules from the submodules list that are submodules inside this
2026
- * assembly.
2027
- */
2028
- mySubmodules() {
2029
- return Array.from(this._submodules.values()).filter((m) => m.fqn.startsWith(`${this.projectInfo.name}.`));
2030
- }
2031
- findPackageInfo(fromDir) {
2032
- if (this._packageInfoCache.has(fromDir)) {
2033
- return this._packageInfoCache.get(fromDir);
2034
- }
2035
- const packageInfo = _findPackageInfo.call(this, fromDir);
2036
- this._packageInfoCache.set(fromDir, packageInfo);
2037
- return packageInfo;
2038
- function _findPackageInfo(dir) {
2039
- const filePath = path.join(dir, 'package.json');
2040
- if (fs.existsSync(filePath)) {
2041
- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
2042
- }
2043
- const parent = path.dirname(dir);
2044
- if (parent === dir) {
2045
- return undefined;
2072
+ if (sym) {
2073
+ const target = type.isTypeReference() ? type.getTarget() : type;
2074
+ const tsym = target.getSymbol() ?? sym;
2075
+ const fqn = this.typeFqnBySymbolId.get(tsym.id) ?? this._externalFqnOf(tsym);
2076
+ if (fqn) {
2077
+ return { fqn };
2046
2078
  }
2047
- return this.findPackageInfo(parent);
2048
2079
  }
2080
+ const indexInfos = this.checker.getIndexInfosOfType(type);
2081
+ if (indexInfos.length) {
2082
+ return { collection: { elementtype: this._typeReference(indexInfos[0].valueType), kind: 'map' } };
2083
+ }
2084
+ return { primitive: 'any' };
2049
2085
  }
2050
- /**
2051
- * Validate types against input/output positions in functions and APIs
2052
- *
2053
- * Currently used to validate that intersection types are only used in input position,
2054
- * not output position
2055
- */
2056
- validateTypesAgainstPositions() {
2057
- const self = this;
2058
- const validatedFqns = {
2059
- in: new Set(),
2060
- out: new Set(),
2061
- };
2062
- for (const type of this._types.values()) {
2063
- if (spec.isClassType(type)) {
2064
- for (const ctorParam of type.initializer?.parameters ?? []) {
2065
- validateRefFor.call(this, 'in', ctorParam.type, `a constructor parameter of ${type.name}`);
2066
- }
2067
- }
2068
- if (spec.isClassType(type) || (0, type_visitor_1.isBehavioralInterfaceType)(type)) {
2069
- for (const property of type.properties ?? []) {
2070
- validateRefFor.call(this, 'out', property.type, `type of property ${type.name}.${property.name}`);
2086
+ _unionTypeReference(type, optionalOut, typeNode) {
2087
+ const { TypeFlags } = this.ts;
2088
+ const all = type.getTypes();
2089
+ const parts = all.filter((t) => !(t.flags & (TypeFlags.Undefined | TypeFlags.Null)));
2090
+ if (optionalOut && parts.length !== all.length) {
2091
+ optionalOut.optional = true;
2092
+ }
2093
+ const un = this._unionNodeOf(typeNode);
2094
+ if (un) {
2095
+ const refs = [];
2096
+ const seen = new Set();
2097
+ const pushFlat = (r) => {
2098
+ if (!r) {
2099
+ return;
2071
2100
  }
2072
- for (const method of type.methods ?? []) {
2073
- for (const param of method.parameters ?? []) {
2074
- validateRefFor.call(this, 'in', param.type, `a parameter of method ${type.name}.${method.name}()`);
2101
+ if (r.union) {
2102
+ for (const inner of r.union.types) {
2103
+ pushFlat(inner);
2075
2104
  }
2076
- if (method.returns) {
2077
- validateRefFor.call(this, 'out', method.returns.type, `return type of method ${type.name}.${method.name}()`);
2105
+ return;
2106
+ }
2107
+ const key = JSON.stringify(r);
2108
+ if (!seen.has(key)) {
2109
+ seen.add(key);
2110
+ refs.push(r);
2111
+ }
2112
+ };
2113
+ for (const tn of un.types) {
2114
+ const tt = this.checker.getTypeFromTypeNode(tn);
2115
+ if (tt && tt.flags & (TypeFlags.Undefined | TypeFlags.Null)) {
2116
+ if (optionalOut) {
2117
+ optionalOut.optional = true;
2078
2118
  }
2119
+ continue;
2079
2120
  }
2121
+ pushFlat(this._typeReference(tt, optionalOut, tn));
2122
+ }
2123
+ if (refs.length === 1) {
2124
+ return refs[0];
2125
+ }
2126
+ if (refs.length > 1) {
2127
+ return { union: { types: sortUnionLikeClassic(refs, (fqn) => this._declarationRank(fqn)) } };
2080
2128
  }
2081
2129
  }
2082
- function validateRefFor(dir, typeRef, reason) {
2083
- (0, type_visitor_1.visitTypeReference)(typeRef, {
2084
- named: (ref) => {
2085
- // Named types we'll only validate once for every direction
2086
- if (validatedFqns[dir].has(ref.fqn)) {
2087
- return;
2088
- }
2089
- validatedFqns[dir].add(ref.fqn);
2090
- const type = self._dereference(ref, undefined, 'just-validating');
2091
- if (!type) {
2092
- // Maybe this is an unexported type.
2093
- return;
2094
- }
2095
- validateTypeFor(dir, type, reason);
2096
- },
2097
- primitive: () => { },
2098
- collection: (ref) => {
2099
- validateRefFor(dir, ref.collection.elementtype, reason);
2100
- },
2101
- union: (ref) => {
2102
- for (const t of ref.union.types) {
2103
- validateRefFor(dir, t, reason);
2104
- }
2105
- },
2106
- intersection: (ref) => {
2107
- if (dir === 'out') {
2108
- self._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_1009_INTERSECTION_ONLY_INPUT.createDetached(reason));
2109
- }
2110
- for (const t of ref.intersection.types) {
2111
- validateRefFor(dir, t, reason);
2112
- }
2113
- },
2114
- });
2115
- }
2116
- function validateTypeFor(dir, type, reason) {
2117
- (0, type_visitor_1.visitType)(type, {
2118
- dataType: (t) => {
2119
- // We only need to validate data types, because classes and interfaces
2120
- // are done as part of the main loop.
2121
- //
2122
- // Recurse.
2123
- for (const prop of t.properties ?? []) {
2124
- validateRefFor(dir, prop.type, `type of property ${t.name}.${prop.name}, ${reason}`);
2125
- }
2126
- },
2127
- classType: () => { },
2128
- interfaceType: () => { },
2129
- enumType: () => { },
2130
- });
2130
+ const refs = [];
2131
+ const seen = new Set();
2132
+ for (const p of parts) {
2133
+ const r = this._typeReference(p, optionalOut);
2134
+ const key = JSON.stringify(r);
2135
+ if (r && !seen.has(key)) {
2136
+ seen.add(key);
2137
+ refs.push(r);
2138
+ }
2139
+ }
2140
+ if (refs.length === 1) {
2141
+ return refs[0];
2131
2142
  }
2143
+ return { union: { types: sortUnionLikeClassic(refs, (fqn) => this._declarationRank(fqn)) } };
2132
2144
  }
2133
2145
  /**
2134
- * Make sure that no 2 submodules are emitting into the same target namespaces
2146
+ * Build an intersection type reference (`A & B`), e.g. jsii models
2147
+ * `IFooRef & IGrantable` as `{ intersection: { types: [...] } }`. Mirrors
2148
+ * strada's `type.isIntersection()` branch: each constituent is turned into a
2149
+ * type reference, deduplicated.
2135
2150
  */
2136
- validateSubmoduleConfigs() {
2137
- const self = this;
2138
- const dotNetnamespaces = {};
2139
- const javaPackages = {};
2140
- const pythonModules = {};
2141
- const goPackages = {};
2142
- for (const submodule of this._submodules.values()) {
2143
- const targets = submodule.targets;
2144
- if (targets?.dotnet?.namespace) {
2145
- accumList(dotNetnamespaces, targets.dotnet.namespace, submodule.fqn);
2146
- }
2147
- if (targets?.java?.package) {
2148
- accumList(javaPackages, targets.java.package, submodule.fqn);
2149
- }
2150
- if (targets?.python?.module) {
2151
- accumList(pythonModules, targets.python.module, submodule.fqn);
2152
- }
2153
- if (targets?.go?.packageName) {
2154
- accumList(goPackages, targets.go.packageName, submodule.fqn);
2155
- }
2156
- }
2157
- maybeError('dotnet', dotNetnamespaces);
2158
- maybeError('java', javaPackages);
2159
- maybeError('python', pythonModules);
2160
- maybeError('go', goPackages);
2161
- function accumList(set, key, value) {
2162
- if (!set[key]) {
2163
- set[key] = [];
2164
- }
2165
- set[key].push(value);
2166
- }
2167
- function maybeError(language, set) {
2168
- for (const [namespace, modules] of Object.entries(set)) {
2169
- if (modules.length > 1) {
2170
- self._diagnostics.push(jsii_diagnostic_1.JsiiDiagnostic.JSII_4010_SUBMODULE_NAMESPACE_CONFLICT.create(undefined, language, namespace, modules));
2171
- }
2151
+ _intersectionTypeReference(type) {
2152
+ const refs = [];
2153
+ const seen = new Set();
2154
+ for (const t of type.getTypes()) {
2155
+ const r = this._typeReference(t);
2156
+ if (!r) {
2157
+ continue;
2172
2158
  }
2173
- }
2174
- }
2175
- }
2176
- exports.Assembler = Assembler;
2177
- function _fingerprint(assembly) {
2178
- delete assembly.fingerprint;
2179
- assembly = sortJson(assembly);
2180
- const fingerprint = crypto.createHash('sha256').update(JSON.stringify(assembly)).digest('base64');
2181
- return { ...assembly, fingerprint };
2182
- }
2183
- function _isAbstract(symbol, declaringType) {
2184
- // everything is abstract in interfaces
2185
- if (declaringType.kind === spec.TypeKind.Interface) {
2186
- return true;
2187
- }
2188
- return (!!symbol.valueDeclaration &&
2189
- (ts.getCombinedModifierFlags(symbol.valueDeclaration) & ts.ModifierFlags.Abstract) !== 0);
2190
- }
2191
- function _isEnumLike(type) {
2192
- return (type.flags & ts.TypeFlags.EnumLike) !== 0;
2193
- }
2194
- function _isExported(node) {
2195
- return (ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0;
2196
- }
2197
- /**
2198
- * Members with names starting with `_` (and marked as @internal) and members
2199
- * that are private are hidden.
2200
- *
2201
- * @param symbol the symbol which should be assessed
2202
- *
2203
- * @return `true` if the symbol should be hidden
2204
- */
2205
- function _isPrivate(symbol) {
2206
- // Private identifiers are always private...
2207
- if (symbol.name.startsWith('#')) {
2208
- return true;
2209
- }
2210
- const TYPE_DECLARATION_KINDS = new Set([
2211
- ts.SyntaxKind.ClassDeclaration,
2212
- ts.SyntaxKind.InterfaceDeclaration,
2213
- ts.SyntaxKind.EnumDeclaration,
2214
- ]);
2215
- // if the symbol doesn't have a value declaration, we are assuming it's a type (enum/interface/class)
2216
- // and check that it has an "export" modifier
2217
- if (!isInternalSymbol(symbol) &&
2218
- (!symbol.valueDeclaration || TYPE_DECLARATION_KINDS.has(symbol.valueDeclaration.kind))) {
2219
- let hasExport = false;
2220
- for (const decl of symbol.declarations ?? []) {
2221
- if (ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Export) {
2222
- hasExport = true;
2223
- break;
2159
+ const key = JSON.stringify(r);
2160
+ if (!seen.has(key)) {
2161
+ seen.add(key);
2162
+ refs.push(r);
2163
+ }
2164
+ }
2165
+ if (refs.length === 1) {
2166
+ return refs[0];
2167
+ }
2168
+ this.usedFeatures.add('intersection-types');
2169
+ return { intersection: { types: refs } };
2170
+ }
2171
+ // -------------------------------------------------------------------------
2172
+ // documentation (strada: _visitDocumentation)
2173
+ // -------------------------------------------------------------------------
2174
+ _visitDocumentation(sym) {
2175
+ const summaryRaw = this._docCommentWithClassicLinks(sym);
2176
+ const docs = {};
2177
+ if (summaryRaw) {
2178
+ const text = typeof summaryRaw === 'string' ? summaryRaw.trim() : String(summaryRaw).trim();
2179
+ const { summary, remarks } = this._splitSummary(text);
2180
+ if (remarks) {
2181
+ docs.remarks = remarks;
2182
+ }
2183
+ docs.summary = summary;
2184
+ }
2185
+ // Exact port of jsii's parseDocParts (src/docs.ts of the classic compiler):
2186
+ // every tag is collected once, well-known tags are consumed into their
2187
+ // dedicated fields (with the same aliases and precedence), and whatever is
2188
+ // left over becomes `docs.custom`. `@param` is handled with the parameter
2189
+ // itself and `@jsii` is internal-only; neither surfaces in the API docs.
2190
+ const tagValues = new Map();
2191
+ for (const tag of this._jsDocTags(sym)) {
2192
+ if (tag.name === 'param' || tag.name === 'jsii') {
2193
+ continue;
2224
2194
  }
2225
- // Handle nested classes from project references
2226
- if (ts.isModuleBlock(decl.parent)) {
2227
- const moduleDeclaration = decl.parent.parent;
2228
- const modifiers = ts.getCombinedModifierFlags(moduleDeclaration);
2229
- // The trick is the module is declared as ambient & exported
2230
- if ((modifiers & ts.ModifierFlags.Ambient) !== 0 && (modifiers & ts.ModifierFlags.Export) !== 0) {
2231
- hasExport = true;
2232
- break;
2233
- }
2195
+ let tagText = typeof tag.text === 'string' ? tag.text : (tag.text ?? []).map((p) => p.text).join('');
2196
+ tagText = tagText.replace(/\{@link\s+([^}]*?)\s*\}/g, '{@link $1 }');
2197
+ if (tag.name === 'see' && /^[^\s$A-Za-z_{]/.test(tagText)) {
2198
+ // The classic parser read a name reference first when `@see` starts with an
2199
+ // identifier; otherwise the text came back as [text(''), space, text], i.e.
2200
+ // with a leading space.
2201
+ tagText = ` ${tagText}`;
2234
2202
  }
2235
- }
2236
- return !hasExport;
2237
- }
2238
- const decl = symbol.valueDeclaration ?? symbol.declarations?.[0];
2239
- return decl != null && (ts.getCombinedModifierFlags(decl) & ts.ModifierFlags.Private) !== 0;
2240
- }
2241
- function _hasInternalJsDocTag(symbol) {
2242
- return symbol.getJsDocTags().some((t) => t.name === 'internal');
2243
- }
2244
- function _isProtected(symbol) {
2245
- return (!!symbol.valueDeclaration &&
2246
- (ts.getCombinedModifierFlags(symbol.valueDeclaration) & ts.ModifierFlags.Protected) !== 0);
2247
- }
2248
- function _isStatic(symbol) {
2249
- return (!!symbol.valueDeclaration && (ts.getCombinedModifierFlags(symbol.valueDeclaration) & ts.ModifierFlags.Static) !== 0);
2250
- }
2251
- /**
2252
- * Determines whether a given type is void or Promise<void>.
2253
- *
2254
- * @param type the tested type
2255
- *
2256
- * @returns `true` if the type is void or Promise<void>
2257
- */
2258
- function _isVoid(type) {
2259
- if (_isPromise(type)) {
2260
- const typeRef = type;
2261
- return typeRef.typeArguments != null && typeRef.typeArguments.length === 1 && _isVoid(typeRef.typeArguments[0]);
2262
- }
2263
- return (type.flags & ts.TypeFlags.Void) !== 0;
2264
- }
2265
- function _isPromise(type) {
2266
- return type.symbol?.escapedName === 'Promise';
2267
- }
2268
- function _sortMembers(type) {
2269
- type.methods = type.methods && _sort(type.methods);
2270
- type.properties = type.properties && _sort(type.properties);
2271
- return type;
2272
- /**
2273
- * Sorts a member array such that:
2274
- * 1. Static members appear first
2275
- * 2. Immutable members appear first
2276
- * 3. Non-optional members appear first
2277
- * 4. Members appear in lexicographical order
2278
- *
2279
- * @param values the array of members to be sorted
2280
- *
2281
- * @return a sorted copy of ``values``
2282
- */
2283
- function _sort(values) {
2284
- if (!values) {
2285
- return values;
2286
- }
2287
- return values.sort(_comparator);
2288
- function _comparator(lval, rval) {
2289
- return _format(lval).localeCompare(_format(rval));
2290
- function _format(val) {
2291
- return [val.static ? '0' : '1', val.immutable ? '0' : '1', !val.optional ? '0' : '1', val.name].join('|');
2203
+ else if (tag.name === 'enum') {
2204
+ // The classic parser consumed the type expression of `@enum {T}`.
2205
+ tagText = tagText.replace(/^\{[^}]*\}\s*/, '');
2292
2206
  }
2207
+ tagValues.set(tag.name, tagText);
2293
2208
  }
2209
+ const eatTag = (...names) => {
2210
+ for (const name of names) {
2211
+ if (tagValues.has(name)) {
2212
+ const value = tagValues.get(name);
2213
+ tagValues.delete(name);
2214
+ return value ?? '';
2215
+ }
2216
+ }
2217
+ return undefined;
2218
+ };
2219
+ const setIfDefined = (key, value, transform = (v) => v) => {
2220
+ if (value !== undefined) {
2221
+ docs[key] = transform(value);
2222
+ }
2223
+ };
2224
+ eatTag('struct'); // a type-system hint, consumed by the datatype detection, not documentation
2225
+ setIfDefined('default', eatTag('default', 'defaultValue'));
2226
+ const deprecated = eatTag('deprecated');
2227
+ setIfDefined('deprecated', deprecated);
2228
+ setIfDefined('example', eatTag('example'));
2229
+ setIfDefined('returns', eatTag('returns', 'return'));
2230
+ setIfDefined('see', eatTag('see'));
2231
+ if (eatTag('subclassable') !== undefined) {
2232
+ docs.subclassable = true;
2233
+ }
2234
+ setIfDefined('stability', eatTag('stability'));
2235
+ // @experimental and @stable are shorthands for the matching @stability
2236
+ const experimental = eatTag('experimental') !== undefined;
2237
+ const stable = eatTag('stable') !== undefined;
2238
+ if (experimental) {
2239
+ docs.stability = 'experimental';
2240
+ }
2241
+ if (stable) {
2242
+ docs.stability = 'stable';
2243
+ }
2244
+ if (deprecated !== undefined) {
2245
+ docs.stability = 'deprecated';
2246
+ }
2247
+ if (tagValues.size > 0) {
2248
+ docs.custom = {};
2249
+ for (const [key, value] of tagValues.entries()) {
2250
+ // Key must have a value or it will be stripped from the assembly
2251
+ docs.custom[key] = value === '' ? 'true' : value;
2252
+ }
2253
+ }
2254
+ return Object.keys(docs).length ? docs : undefined;
2255
+ }
2256
+ // Exact port of jsii's summary/remarks split (src/docs.ts splitSummary /
2257
+ // summaryLine / endWithPeriod / noNewlines / uberTrim); the regex constants
2258
+ // are declared at the top of the class (member-ordering).
2259
+ _splitSummary(docBlock) {
2260
+ return splitSummary(docBlock);
2261
+ }
2262
+ _withDefaultDocs(obj) {
2263
+ if (!this.currentStability) {
2264
+ return obj;
2265
+ }
2266
+ if (!obj.docs) {
2267
+ obj.docs = { stability: this.currentStability };
2268
+ }
2269
+ else if (!obj.docs.stability) {
2270
+ obj.docs.stability = this.currentStability;
2271
+ }
2272
+ return obj;
2273
+ }
2274
+ _locationOf(decl) {
2275
+ const sf = decl.getSourceFile();
2276
+ const { line } = sf.getLineAndCharacterOfPosition(decl.getStart(sf));
2277
+ return { filename: path.relative(this.root, sf.fileName), line: line + 1 };
2278
+ }
2279
+ // -------------------------------------------------------------------------
2280
+ // assembly header assembly (strada: emit() tail)
2281
+ // -------------------------------------------------------------------------
2282
+ _buildAssembly() {
2283
+ const info = this.options.projectInfo;
2284
+ // Same header the classic Assembler produces (its emit() tail), sourced from
2285
+ const jsiiVersion = info.jsiiVersionFormat === 'short' ? version_1.SHORT_VERSION : version_1.VERSION;
2286
+ const docs = info.stability || info.deprecated
2287
+ ? {
2288
+ ...(info.deprecated ? { deprecated: info.deprecated } : {}),
2289
+ ...(info.stability ? { stability: info.stability } : {}),
2290
+ }
2291
+ : undefined;
2292
+ const assembly = {
2293
+ schema: spec.SchemaVersion.LATEST,
2294
+ name: this.assemblyName,
2295
+ version: info.version,
2296
+ description: info.description ?? this.assemblyName,
2297
+ license: info.license,
2298
+ keywords: info.keywords && Array.from(info.keywords),
2299
+ homepage: info.homepage ?? info.repository.url,
2300
+ author: info.author,
2301
+ contributors: info.contributors && [...info.contributors],
2302
+ repository: info.repository,
2303
+ dependencies: noEmptyDict({ ...info.dependencies, ...info.peerDependencies }),
2304
+ dependencyClosure: noEmptyDict(toDependencyClosure(info.dependencyClosure)),
2305
+ bundled: info.bundleDependencies,
2306
+ types: this.types,
2307
+ ...(Object.keys(this.submodules).length ? { submodules: this.submodules } : {}),
2308
+ usedFeatures: this._finalizeInheritance(),
2309
+ targets: info.targets,
2310
+ metadata: {
2311
+ ...info.metadata,
2312
+ // Downstream consumers need these to map a symbolId in the outDir to a
2313
+ // symbolId in the rootDir (same as the classic backend records).
2314
+ // rootDir/outDir may be absolute (just like for tsc); they are normalized
2315
+ // to be relative to the package root so no absolute path leaks into the
2316
+ // assembly and breaks the reproducibility check of downstream consumers.
2317
+ ...(this.options.tscRootDir != null
2318
+ ? { tscRootDir: (0, helpers_1.normalizeConfigPath)(this.options.projectRoot, this.options.tscRootDir) }
2319
+ : {}),
2320
+ ...(this.options.tscOutDir != null
2321
+ ? { tscOutDir: (0, helpers_1.normalizeConfigPath)(this.options.projectRoot, this.options.tscOutDir) }
2322
+ : {}),
2323
+ },
2324
+ ...(docs ? { docs } : {}),
2325
+ ...(this.options.readme ? { readme: this.options.readme } : {}),
2326
+ jsiiVersion,
2327
+ bin: info.bin,
2328
+ };
2329
+ return assembly;
2294
2330
  }
2295
2331
  }
2296
- /**
2297
- * Return the last element from a list
2298
- */
2299
- function last(xs) {
2300
- return xs.length > 0 ? xs[xs.length - 1] : undefined;
2301
- }
2302
- /**
2303
- * Apply a function to a value if it's not equal to undefined
2304
- */
2305
- function apply(x, fn) {
2306
- return x !== undefined ? fn(x) : undefined;
2307
- }
2308
- /**
2309
- * Return all members names of a JSII interface type
2310
- *
2311
- * Returns empty string for a non-interface type.
2312
- */
2313
- function memberNames(jsiiType) {
2314
- return Object.keys(typeMembers(jsiiType)).filter((n) => n !== '');
2315
- }
2316
- function typeMembers(jsiiType) {
2317
- const ret = {};
2318
- for (const prop of jsiiType.properties ?? []) {
2319
- ret[prop.name] = prop;
2320
- }
2321
- for (const method of jsiiType.methods ?? []) {
2322
- ret[method.name ?? ''] = method;
2323
- }
2324
- return ret;
2332
+ exports.Assembler = Assembler;
2333
+ /** Port of the classic Assembler's `noEmptyDict`. */
2334
+ function noEmptyDict(xs) {
2335
+ return Object.keys(xs).length === 0 ? undefined : xs;
2325
2336
  }
2326
2337
  /**
2327
- * Whether or not the given name is conventionally an interface name
2328
- *
2329
- * It's an interface name if it starts with I and has another capital
2330
- * (so we don't mark IonicColumnProps as an interface).
2338
+ * Port of the classic Assembler's `toDependencyClosure`: keep only `targets`
2339
+ * and slimmed-down `submodules` (readme / locationInModule stripped) for each
2340
+ * assembly in the closure.
2331
2341
  */
2332
- function isInterfaceName(name) {
2333
- return name.length >= 2 && name.startsWith('I') && name.charAt(1).toUpperCase() === name.charAt(1);
2334
- }
2335
- function getConstructor(type) {
2336
- return type.symbol.members?.get(ts.InternalSymbolName.Constructor);
2337
- }
2338
- function cmpDesc(a, b, desc) {
2339
- const desc1 = desc(a);
2340
- const desc2 = desc(b);
2341
- return desc1 !== desc2 ? [desc1, desc2] : undefined;
2342
- }
2343
- function noEmptyDict(xs) {
2344
- if (xs == null || Object.keys(xs).length === 0) {
2345
- return undefined;
2346
- }
2347
- return xs;
2348
- }
2349
2342
  function toDependencyClosure(assemblies) {
2350
2343
  const result = {};
2351
2344
  for (const assembly of assemblies) {
2352
2345
  if (!assembly.targets) {
2353
2346
  continue;
2354
2347
  }
2355
- result[assembly.name] = {
2356
- submodules: cleanUp(assembly.submodules),
2357
- targets: assembly.targets,
2358
- };
2348
+ const submodules = assembly.submodules &&
2349
+ Object.fromEntries(Object.entries(assembly.submodules).map(([fqn, { targets }]) => [fqn, { targets }]));
2350
+ result[assembly.name] = { submodules, targets: assembly.targets };
2359
2351
  }
2360
2352
  return result;
2361
- /**
2362
- * Removes unneeded fields from the entries part of the `dependencyClosure`
2363
- * property. Fields such as `readme` are not necessary and can bloat up the
2364
- * assembly object.
2365
- *
2366
- * This removes the `readme` and `locationInModule` fields from the submodule
2367
- * descriptios if present.
2368
- *
2369
- * @param submodules the submodules list to clean up.
2370
- *
2371
- * @returns the cleaned up submodules list.
2372
- */
2373
- function cleanUp(submodules) {
2374
- if (submodules == null) {
2375
- return submodules;
2376
- }
2377
- const clean = {};
2378
- for (const [fqn, { targets }] of Object.entries(submodules)) {
2379
- clean[fqn] = { targets };
2380
- }
2381
- return clean;
2382
- }
2383
- }
2384
- function toSubmoduleDeclarations(submodules) {
2385
- const result = {};
2386
- for (const submodule of submodules) {
2387
- result[submodule.fqn] = {
2388
- locationInModule: submodule.locationInModule,
2389
- targets: submodule.targets,
2390
- readme: submodule.readme,
2391
- symbolId: submodule.symbolId,
2392
- };
2393
- }
2394
- return result;
2395
- }
2396
- /**
2397
- * Check whether this type is the intrinsic TypeScript "error type"
2398
- *
2399
- * This type is returned if type lookup fails. Unfortunately no public
2400
- * accessors for it are exposed.
2401
- */
2402
- function isErrorType(t) {
2403
- return t.intrinsicName === 'error';
2404
- }
2405
- /**
2406
- * Those have specific semantics in certain languages that don't always translate cleanly in others
2407
- * (like how equals/hashCode are not a thing in Javascript, but carry meaning in Java and C#). The
2408
- * `build` name is reserved for generated code (Java builders use that).
2409
- */
2410
- const PROHIBITED_MEMBER_NAMES = ['build', 'equals', 'hashcode'];
2411
- /**
2412
- * Whether the given name is prohibited
2413
- */
2414
- function isProhibitedMemberName(name) {
2415
- return PROHIBITED_MEMBER_NAMES.includes(name.toLowerCase());
2416
- }
2417
- /**
2418
- * Information about the context in which a declaration is emitted.
2419
- */
2420
- class EmitContext {
2421
- namespace;
2422
- stability;
2423
- constructor(namespace, stability) {
2424
- this.namespace = namespace;
2425
- this.stability = stability;
2426
- }
2427
- /**
2428
- * Create a new EmitContext by appending a namespace entry at the end.
2429
- * @param element the new namespace entry.
2430
- */
2431
- appendNamespace(element) {
2432
- return new EmitContext([...this.namespace, element], this.stability);
2433
- }
2434
- /**
2435
- * Create a new EmitContext by replacing the stability.
2436
- * @param stability the new stability, if available.
2437
- */
2438
- replaceStability(stability) {
2439
- if (!stability) {
2440
- return this;
2441
- }
2442
- return new EmitContext(this.namespace, stability);
2443
- }
2444
- /**
2445
- * Create a new EmitContext without stability.
2446
- */
2447
- removeStability() {
2448
- return new EmitContext(this.namespace, undefined);
2449
- }
2450
- }
2451
- function inferRootDir(program) {
2452
- const directories = program
2453
- .getRootFileNames()
2454
- .filter((fileName) => {
2455
- const sourceFile = program.getSourceFile(fileName);
2456
- return (sourceFile != null &&
2457
- !program.isSourceFileFromExternalLibrary(sourceFile) &&
2458
- !program.isSourceFileDefaultLibrary(sourceFile));
2459
- })
2460
- .map((fileName) => path.relative(program.getCurrentDirectory(), path.dirname(fileName)))
2461
- .map(segmentPath);
2462
- const maxPrefix = Math.min(...directories.map((segments) => segments.length - 1));
2463
- let commonIndex = -1;
2464
- while (commonIndex < maxPrefix && new Set(directories.map((segments) => segments[commonIndex + 1])).size === 1) {
2465
- commonIndex++;
2466
- }
2467
- if (commonIndex < 0) {
2468
- return undefined;
2469
- }
2470
- return directories[0][commonIndex];
2471
- function segmentPath(fileName) {
2472
- const result = new Array();
2473
- for (let parent = fileName; parent !== path.dirname(parent); parent = path.dirname(parent)) {
2474
- result.unshift(parent);
2475
- }
2476
- return result;
2477
- }
2478
- }
2479
- /**
2480
- * Determines whether the provided type is a single-valued enum. It is necessary
2481
- * to check as enums are union-like in the type model, and single-valued enum
2482
- * types are actually reduced to the only available literal, which can trip
2483
- * the assembler.
2484
- *
2485
- * @param type the type being checked.
2486
- * @param typeChecker the type checker to use to get more information.
2487
- *
2488
- * @return `true` if `type` is a single-valued enum type.
2489
- */
2490
- function isSingleValuedEnum(type, typeChecker) {
2491
- if (type.isLiteral() && _isEnumLike(type)) {
2492
- // Single-Valued enums are reduced to the only literal available.
2493
- return type === typeChecker.getBaseTypeOfLiteralType(type);
2494
- }
2495
- return false;
2496
2353
  }
2354
+ // ---------------------------------------------------------------------------
2355
+ // Pure helpers (exported for unit tests)
2356
+ // ---------------------------------------------------------------------------
2497
2357
  /**
2498
- * Checks is the provided type is "this" (as a type annotation).
2499
- *
2500
- * @param type the validated type.
2501
- * @param typeChecker the type checker.
2502
- *
2503
- * @returns `true` iif the type is `this`
2504
- */
2505
- function _isThisType(type, typeChecker, enclosingDeclaration) {
2506
- return (typeChecker.typeToTypeNode(type, enclosingDeclaration, ts.NodeBuilderFlags.None)?.kind === ts.SyntaxKind.ThisKeyword);
2507
- }
2508
- /**
2509
- * Gets the name node for a given symbol; or it's first declaration if no name can be found. This is
2510
- * intended for use in placing problem markers on the right location.
2511
- *
2512
- * @param symbol the symbol for which the name node is needed.
2513
- *
2514
- * @returns the name node for the symbol, or the symbol's first declaration.
2358
+ * Port of the classic Assembler's `isInterfaceName`: a name denotes a
2359
+ * behavioral interface when it starts with `I` and the second character is
2360
+ * uppercase (so `IonicColumnProps` is not treated as one).
2515
2361
  */
2516
- function _nameOrDeclarationNode(symbol) {
2517
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
2518
- if (declaration == null) {
2519
- return undefined;
2520
- }
2521
- return ts.getNameOfDeclaration(declaration) ?? declaration;
2522
- }
2523
- function _findHint(decl, hint) {
2524
- const [node] = ts.getAllJSDocTags(decl, (tag) => tag.tagName.text === hint);
2525
- return node;
2526
- }
2527
- function containsIntersection(type) {
2528
- if (spec.isIntersectionTypeReference(type)) {
2529
- return true;
2530
- }
2531
- if (spec.isUnionTypeReference(type)) {
2532
- return type.union.types.some(containsIntersection);
2533
- }
2534
- if (spec.isCollectionTypeReference(type)) {
2535
- return containsIntersection(type.collection.elementtype);
2536
- }
2537
- return false;
2538
- }
2539
- /**
2540
- * Resolve a Type to Symbol, taking into account single-valued enums which have a bug
2541
- *
2542
- * Bug reference: https://github.com/microsoft/TypeScript/issues/46755
2543
- */
2544
- function symbolFromType(type, typeChecker) {
2545
- if ((type.flags & ts.TypeFlags.EnumLiteral) === 0) {
2546
- return type.symbol;
2547
- }
2548
- const decl = type.symbol.declarations?.[0];
2549
- if (!decl) {
2550
- return type.symbol;
2551
- }
2552
- if (!ts.isEnumMember(decl)) {
2553
- return type.symbol;
2554
- }
2555
- const parentDecl = decl.parent;
2556
- if (!parentDecl || !ts.isEnumDeclaration(parentDecl)) {
2557
- return type.symbol;
2558
- }
2559
- const name = ts.getNameOfDeclaration(parentDecl);
2560
- if (!name) {
2561
- return type.symbol;
2562
- }
2563
- return typeChecker.getSymbolAtLocation(name) ?? type.symbol;
2564
- }
2565
- const SYMBOLID_CACHE = new WeakMap();
2566
- /**
2567
- * Build and return an index of { symbolId -> fqn }
2568
- *
2569
- * Uses a cache for performance reasons.
2570
- */
2571
- function symbolIdIndex(asm) {
2572
- const existing = SYMBOLID_CACHE.get(asm);
2573
- if (existing) {
2574
- return existing;
2575
- }
2576
- const ret = buildIndex();
2577
- SYMBOLID_CACHE.set(asm, ret);
2578
- return ret;
2579
- function buildIndex() {
2580
- const index = {};
2581
- for (const [fqn, type] of Object.entries(asm.types ?? {})) {
2582
- if (type.symbolId) {
2583
- index[type.symbolId] = fqn;
2584
- }
2585
- }
2586
- return index;
2587
- }
2588
- }
2589
- function getSymbolFromDeclaration(decl, typeChecker) {
2590
- const name = ts.getNameOfDeclaration(decl);
2591
- return name ? typeChecker.getSymbolAtLocation(name) : undefined;
2592
- }
2593
- function isTupleType(type) {
2594
- if (type.objectFlags & ts.ObjectFlags.Tuple) {
2595
- return true;
2596
- }
2597
- if (type.objectFlags & ts.ObjectFlags.Reference) {
2598
- return isTupleType(type.target);
2599
- }
2600
- return false;
2362
+ function isInterfaceName(name) {
2363
+ return name.length >= 2 && name.startsWith('I') && name.charAt(1).toUpperCase() === name.charAt(1);
2601
2364
  }
2602
- function isUnder(file, dir) {
2603
- const relative = path.relative(dir, file);
2604
- return !relative.startsWith(path.sep) && !relative.startsWith('..');
2365
+ /** Whether a declaration path points into a TypeScript standard-library `lib.*.d.ts`. */
2366
+ function isStdlibDeclPath(declPath) {
2367
+ return /(^|\/)lib\.[^/]+\.d\.ts$/.test(declPath);
2605
2368
  }
2606
- function loadAndRenderReadme(readmePath, projectRoot) {
2607
- if (!fs.existsSync(readmePath)) {
2608
- return undefined;
2609
- }
2369
+ // Exact port of jsii's summary/remarks split (src/docs.ts splitSummary /
2370
+ // summaryLine / endWithPeriod): the sentence regex requires whitespace after
2371
+ // the punctuation, and ';' counts as terminal punctuation, so
2372
+ // "the resource type;\nex: ..." splits into summary + remarks.
2373
+ const PUNCTUATION = ['!', '?', '.', ';'].map((s) => `\\${s}`).join('');
2374
+ const ENDS_WITH_PUNCTUATION_REGEX = new RegExp(`[${PUNCTUATION}]$`);
2375
+ const FIRST_SENTENCE_REGEX = new RegExp(`^([^${PUNCTUATION}]+[${PUNCTUATION}][ \\n\\r])`);
2376
+ const SUMMARY_MAX_WORDS = 20;
2377
+ /** Split a doc comment block into the summary sentence and the remaining remarks. */
2378
+ function splitSummary(docBlock) {
2379
+ if (!docBlock) {
2380
+ return {};
2381
+ }
2382
+ const summary = summaryLine(docBlock);
2383
+ const rest = docBlock.slice(summary.length).trim();
2384
+ const s = summary.trim().replace(/\r?\n/g, ' ');
2610
2385
  return {
2611
- markdown: literate
2612
- .includeAndRenderExamples(literate.loadFromFile(readmePath), literate.fileSystemLoader(path.dirname(readmePath)), projectRoot)
2613
- .join('\n'),
2386
+ summary: ENDS_WITH_PUNCTUATION_REGEX.test(s) ? s : `${s}.`,
2387
+ remarks: rest === '' ? undefined : rest,
2614
2388
  };
2615
2389
  }
2616
- const INTERNAL_SYMBOLS = new Set(Object.values(ts.InternalSymbolName));
2617
- function isInternalSymbol(symbol) {
2618
- return INTERNAL_SYMBOLS.has(symbol.name);
2390
+ function summaryLine(str) {
2391
+ const paras = str.split(/(\r?\n){2}/);
2392
+ if (paras.length > 1 && paras[0].split(' ').length < SUMMARY_MAX_WORDS) {
2393
+ return paras[0];
2394
+ }
2395
+ const m = FIRST_SENTENCE_REGEX.exec(str);
2396
+ return m ? m[1] : paras[0];
2619
2397
  }
2620
2398
  //# sourceMappingURL=assembler.js.map