tsc-ts 0.0.4 → 0.0.5

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 (584) hide show
  1. package/README.md +33 -1
  2. package/dist/api/compiler/ast-utilities.d.ts +82 -0
  3. package/dist/api/compiler/ast-utilities.js +462 -0
  4. package/dist/api/compiler/ast.d.ts +2350 -0
  5. package/dist/api/compiler/ast.js +11206 -0
  6. package/dist/api/compiler/astnav.d.ts +37 -0
  7. package/dist/api/compiler/astnav.js +767 -0
  8. package/dist/api/compiler/binder-utilities.d.ts +182 -0
  9. package/dist/api/compiler/binder-utilities.js +1240 -0
  10. package/dist/api/compiler/binder.d.ts +33 -0
  11. package/dist/api/compiler/binder.js +2358 -0
  12. package/dist/api/compiler/character-codes.d.ts +161 -0
  13. package/dist/api/compiler/character-codes.js +160 -0
  14. package/dist/api/compiler/checker-calls.d.ts +46 -0
  15. package/dist/api/compiler/checker-calls.js +1640 -0
  16. package/dist/api/compiler/checker-classes.d.ts +30 -0
  17. package/dist/api/compiler/checker-classes.js +582 -0
  18. package/dist/api/compiler/checker-contextual.d.ts +77 -0
  19. package/dist/api/compiler/checker-contextual.js +1136 -0
  20. package/dist/api/compiler/checker-declaration-order.d.ts +12 -0
  21. package/dist/api/compiler/checker-declaration-order.js +356 -0
  22. package/dist/api/compiler/checker-declarations.d.ts +33 -0
  23. package/dist/api/compiler/checker-declarations.js +888 -0
  24. package/dist/api/compiler/checker-declared-types.d.ts +48 -0
  25. package/dist/api/compiler/checker-declared-types.js +787 -0
  26. package/dist/api/compiler/checker-decorators.d.ts +26 -0
  27. package/dist/api/compiler/checker-decorators.js +562 -0
  28. package/dist/api/compiler/checker-deprecation.d.ts +33 -0
  29. package/dist/api/compiler/checker-deprecation.js +315 -0
  30. package/dist/api/compiler/checker-destructuring.d.ts +34 -0
  31. package/dist/api/compiler/checker-destructuring.js +584 -0
  32. package/dist/api/compiler/checker-elaboration.d.ts +15 -0
  33. package/dist/api/compiler/checker-elaboration.js +290 -0
  34. package/dist/api/compiler/checker-emit-helpers.d.ts +58 -0
  35. package/dist/api/compiler/checker-emit-helpers.js +154 -0
  36. package/dist/api/compiler/checker-emit-resolver.d.ts +75 -0
  37. package/dist/api/compiler/checker-emit-resolver.js +579 -0
  38. package/dist/api/compiler/checker-evaluator.d.ts +27 -0
  39. package/dist/api/compiler/checker-evaluator.js +188 -0
  40. package/dist/api/compiler/checker-expressions.d.ts +67 -0
  41. package/dist/api/compiler/checker-expressions.js +1351 -0
  42. package/dist/api/compiler/checker-features.d.ts +6 -0
  43. package/dist/api/compiler/checker-features.js +354 -0
  44. package/dist/api/compiler/checker-flow.d.ts +86 -0
  45. package/dist/api/compiler/checker-flow.js +169 -0
  46. package/dist/api/compiler/checker-functions.d.ts +43 -0
  47. package/dist/api/compiler/checker-functions.js +1002 -0
  48. package/dist/api/compiler/checker-generated-code.d.ts +25 -0
  49. package/dist/api/compiler/checker-generated-code.js +168 -0
  50. package/dist/api/compiler/checker-globals.d.ts +14 -0
  51. package/dist/api/compiler/checker-globals.js +37 -0
  52. package/dist/api/compiler/checker-grammar.d.ts +35 -0
  53. package/dist/api/compiler/checker-grammar.js +2573 -0
  54. package/dist/api/compiler/checker-heritage.d.ts +28 -0
  55. package/dist/api/compiler/checker-heritage.js +900 -0
  56. package/dist/api/compiler/checker-inference.d.ts +179 -0
  57. package/dist/api/compiler/checker-inference.js +2105 -0
  58. package/dist/api/compiler/checker-iteration.d.ts +115 -0
  59. package/dist/api/compiler/checker-iteration.js +857 -0
  60. package/dist/api/compiler/checker-javascript.d.ts +42 -0
  61. package/dist/api/compiler/checker-javascript.js +441 -0
  62. package/dist/api/compiler/checker-jsdoc.d.ts +30 -0
  63. package/dist/api/compiler/checker-jsdoc.js +320 -0
  64. package/dist/api/compiler/checker-jsx.d.ts +94 -0
  65. package/dist/api/compiler/checker-jsx.js +1433 -0
  66. package/dist/api/compiler/checker-literals.d.ts +6 -0
  67. package/dist/api/compiler/checker-literals.js +43 -0
  68. package/dist/api/compiler/checker-members.d.ts +198 -0
  69. package/dist/api/compiler/checker-members.js +2126 -0
  70. package/dist/api/compiler/checker-modules.d.ts +85 -0
  71. package/dist/api/compiler/checker-modules.js +2141 -0
  72. package/dist/api/compiler/checker-narrowing.d.ts +120 -0
  73. package/dist/api/compiler/checker-narrowing.js +2797 -0
  74. package/dist/api/compiler/checker-object-literals.d.ts +14 -0
  75. package/dist/api/compiler/checker-object-literals.js +479 -0
  76. package/dist/api/compiler/checker-operators.d.ts +33 -0
  77. package/dist/api/compiler/checker-operators.js +1040 -0
  78. package/dist/api/compiler/checker-overloads.d.ts +7 -0
  79. package/dist/api/compiler/checker-overloads.js +270 -0
  80. package/dist/api/compiler/checker-property-access.d.ts +34 -0
  81. package/dist/api/compiler/checker-property-access.js +672 -0
  82. package/dist/api/compiler/checker-services.d.ts +49 -0
  83. package/dist/api/compiler/checker-services.js +995 -0
  84. package/dist/api/compiler/checker-signatures.d.ts +55 -0
  85. package/dist/api/compiler/checker-signatures.js +788 -0
  86. package/dist/api/compiler/checker-source-file.d.ts +27 -0
  87. package/dist/api/compiler/checker-source-file.js +619 -0
  88. package/dist/api/compiler/checker-statements.d.ts +18 -0
  89. package/dist/api/compiler/checker-statements.js +226 -0
  90. package/dist/api/compiler/checker-super.d.ts +13 -0
  91. package/dist/api/compiler/checker-super.js +241 -0
  92. package/dist/api/compiler/checker-symbol-types.d.ts +67 -0
  93. package/dist/api/compiler/checker-symbol-types.js +1885 -0
  94. package/dist/api/compiler/checker-symbols.d.ts +181 -0
  95. package/dist/api/compiler/checker-symbols.js +1782 -0
  96. package/dist/api/compiler/checker-type-factory.d.ts +142 -0
  97. package/dist/api/compiler/checker-type-factory.js +2501 -0
  98. package/dist/api/compiler/checker-type-nodes.d.ts +26 -0
  99. package/dist/api/compiler/checker-type-nodes.js +828 -0
  100. package/dist/api/compiler/checker-type-operators.d.ts +109 -0
  101. package/dist/api/compiler/checker-type-operators.js +1842 -0
  102. package/dist/api/compiler/checker-types.d.ts +1027 -0
  103. package/dist/api/compiler/checker-types.js +1697 -0
  104. package/dist/api/compiler/checker-unused.d.ts +19 -0
  105. package/dist/api/compiler/checker-unused.js +524 -0
  106. package/dist/api/compiler/checker-utilities.d.ts +33 -0
  107. package/dist/api/compiler/checker-utilities.js +141 -0
  108. package/dist/api/compiler/checker.d.ts +491 -0
  109. package/dist/api/compiler/checker.js +912 -0
  110. package/dist/api/compiler/command-line.d.ts +32 -0
  111. package/dist/api/compiler/command-line.js +383 -0
  112. package/dist/api/compiler/compile-program.d.ts +118 -0
  113. package/dist/api/compiler/compile-program.js +384 -0
  114. package/dist/api/compiler/diagnostic-locales.d.ts +22 -0
  115. package/dist/api/compiler/diagnostic-locales.js +64 -0
  116. package/dist/api/compiler/diagnostic-messages.d.ts +2166 -0
  117. package/dist/api/compiler/diagnostic-messages.js +184 -0
  118. package/dist/api/compiler/diagnostics.d.ts +167 -0
  119. package/dist/api/compiler/diagnostics.js +820 -0
  120. package/dist/api/compiler/emitter.d.ts +71 -0
  121. package/dist/api/compiler/emitter.js +327 -0
  122. package/dist/api/compiler/file-include.d.ts +117 -0
  123. package/dist/api/compiler/file-include.js +536 -0
  124. package/dist/api/compiler/file-loader.d.ts +261 -0
  125. package/dist/api/compiler/file-loader.js +1257 -0
  126. package/dist/api/compiler/file-system.d.ts +51 -0
  127. package/dist/api/compiler/file-system.js +132 -0
  128. package/dist/api/compiler/flow.d.ts +60 -0
  129. package/dist/api/compiler/flow.js +45 -0
  130. package/dist/api/compiler/instantiation.d.ts +74 -0
  131. package/dist/api/compiler/instantiation.js +799 -0
  132. package/dist/api/compiler/jsdoc.d.ts +75 -0
  133. package/dist/api/compiler/jsdoc.js +1229 -0
  134. package/dist/api/compiler/link-tables.d.ts +36 -0
  135. package/dist/api/compiler/link-tables.js +83 -0
  136. package/dist/api/compiler/locale-data.d.ts +24 -0
  137. package/dist/api/compiler/locale-data.js +183 -0
  138. package/dist/api/compiler/locale.d.ts +4 -0
  139. package/dist/api/compiler/locale.js +317 -0
  140. package/dist/api/compiler/locales/cs-CZ.d.ts +2 -0
  141. package/dist/api/compiler/locales/cs-CZ.js +3 -0
  142. package/dist/api/compiler/locales/de-DE.d.ts +2 -0
  143. package/dist/api/compiler/locales/de-DE.js +3 -0
  144. package/dist/api/compiler/locales/es-ES.d.ts +2 -0
  145. package/dist/api/compiler/locales/es-ES.js +3 -0
  146. package/dist/api/compiler/locales/fr-FR.d.ts +2 -0
  147. package/dist/api/compiler/locales/fr-FR.js +3 -0
  148. package/dist/api/compiler/locales/it-IT.d.ts +2 -0
  149. package/dist/api/compiler/locales/it-IT.js +3 -0
  150. package/dist/api/compiler/locales/ja-JP.d.ts +2 -0
  151. package/dist/api/compiler/locales/ja-JP.js +3 -0
  152. package/dist/api/compiler/locales/ko-KR.d.ts +2 -0
  153. package/dist/api/compiler/locales/ko-KR.js +3 -0
  154. package/dist/api/compiler/locales/pl-PL.d.ts +2 -0
  155. package/dist/api/compiler/locales/pl-PL.js +3 -0
  156. package/dist/api/compiler/locales/pt-BR.d.ts +2 -0
  157. package/dist/api/compiler/locales/pt-BR.js +3 -0
  158. package/dist/api/compiler/locales/ru-RU.d.ts +2 -0
  159. package/dist/api/compiler/locales/ru-RU.js +3 -0
  160. package/dist/api/compiler/locales/tr-TR.d.ts +2 -0
  161. package/dist/api/compiler/locales/tr-TR.js +3 -0
  162. package/dist/api/compiler/locales/zh-CN.d.ts +2 -0
  163. package/dist/api/compiler/locales/zh-CN.js +3 -0
  164. package/dist/api/compiler/locales/zh-TW.d.ts +2 -0
  165. package/dist/api/compiler/locales/zh-TW.js +3 -0
  166. package/dist/api/compiler/module-resolution-types.d.ts +83 -0
  167. package/dist/api/compiler/module-resolution-types.js +176 -0
  168. package/dist/api/compiler/module-resolution.d.ts +71 -0
  169. package/dist/api/compiler/module-resolution.js +1598 -0
  170. package/dist/api/compiler/module-specifiers.d.ts +64 -0
  171. package/dist/api/compiler/module-specifiers.js +1101 -0
  172. package/dist/api/compiler/name-resolver.d.ts +43 -0
  173. package/dist/api/compiler/name-resolver.js +509 -0
  174. package/dist/api/compiler/node-builder-names.d.ts +32 -0
  175. package/dist/api/compiler/node-builder-names.js +854 -0
  176. package/dist/api/compiler/node-builder-pseudo.d.ts +36 -0
  177. package/dist/api/compiler/node-builder-pseudo.js +744 -0
  178. package/dist/api/compiler/node-builder-reuse.d.ts +4 -0
  179. package/dist/api/compiler/node-builder-reuse.js +647 -0
  180. package/dist/api/compiler/node-builder.d.ts +270 -0
  181. package/dist/api/compiler/node-builder.js +2645 -0
  182. package/dist/api/compiler/option-declarations.d.ts +90 -0
  183. package/dist/api/compiler/option-declarations.js +1460 -0
  184. package/dist/api/compiler/options.d.ts +289 -0
  185. package/dist/api/compiler/options.js +1197 -0
  186. package/dist/api/compiler/output-paths.d.ts +42 -0
  187. package/dist/api/compiler/output-paths.js +195 -0
  188. package/dist/api/compiler/package-json.d.ts +175 -0
  189. package/dist/api/compiler/package-json.js +1015 -0
  190. package/dist/api/compiler/parallel-parse.d.ts +219 -0
  191. package/dist/api/compiler/parallel-parse.js +537 -0
  192. package/dist/api/compiler/parser.d.ts +587 -0
  193. package/dist/api/compiler/parser.js +6407 -0
  194. package/dist/api/compiler/path.d.ts +91 -0
  195. package/dist/api/compiler/path.js +705 -0
  196. package/dist/api/compiler/printer/async-helpers.d.ts +22 -0
  197. package/dist/api/compiler/printer/async-helpers.js +91 -0
  198. package/dist/api/compiler/printer/auto-generate.d.ts +13 -0
  199. package/dist/api/compiler/printer/auto-generate.js +20 -0
  200. package/dist/api/compiler/printer/decorator-helpers.d.ts +24 -0
  201. package/dist/api/compiler/printer/decorator-helpers.js +118 -0
  202. package/dist/api/compiler/printer/emit-context.d.ts +154 -0
  203. package/dist/api/compiler/printer/emit-context.js +576 -0
  204. package/dist/api/compiler/printer/emit-flags.d.ts +60 -0
  205. package/dist/api/compiler/printer/emit-flags.js +2 -0
  206. package/dist/api/compiler/printer/factory-base.d.ts +171 -0
  207. package/dist/api/compiler/printer/factory-base.js +1505 -0
  208. package/dist/api/compiler/printer/factory.d.ts +147 -0
  209. package/dist/api/compiler/printer/factory.js +542 -0
  210. package/dist/api/compiler/printer/helpers.d.ts +27 -0
  211. package/dist/api/compiler/printer/helpers.js +164 -0
  212. package/dist/api/compiler/printer/name-generator.d.ts +41 -0
  213. package/dist/api/compiler/printer/name-generator.js +283 -0
  214. package/dist/api/compiler/printer/printer.d.ts +411 -0
  215. package/dist/api/compiler/printer/printer.js +4517 -0
  216. package/dist/api/compiler/printer/text-writer.d.ts +46 -0
  217. package/dist/api/compiler/printer/text-writer.js +172 -0
  218. package/dist/api/compiler/printer/utilities.d.ts +82 -0
  219. package/dist/api/compiler/printer/utilities.js +817 -0
  220. package/dist/api/compiler/program-checker.d.ts +156 -0
  221. package/dist/api/compiler/program-checker.js +526 -0
  222. package/dist/api/compiler/program-utilities.d.ts +52 -0
  223. package/dist/api/compiler/program-utilities.js +365 -0
  224. package/dist/api/compiler/program.d.ts +180 -0
  225. package/dist/api/compiler/program.js +1011 -0
  226. package/dist/api/compiler/pseudo-bigint.d.ts +5 -0
  227. package/dist/api/compiler/pseudo-bigint.js +61 -0
  228. package/dist/api/compiler/regexp-checker.d.ts +38 -0
  229. package/dist/api/compiler/regexp-checker.js +942 -0
  230. package/dist/api/compiler/relations.d.ts +263 -0
  231. package/dist/api/compiler/relations.js +4002 -0
  232. package/dist/api/compiler/reparser.d.ts +48 -0
  233. package/dist/api/compiler/reparser.js +1323 -0
  234. package/dist/api/compiler/scanner.d.ts +256 -0
  235. package/dist/api/compiler/scanner.js +2853 -0
  236. package/dist/api/compiler/side-state.d.ts +16 -0
  237. package/dist/api/compiler/side-state.js +89 -0
  238. package/dist/api/compiler/sourcemap.d.ts +55 -0
  239. package/dist/api/compiler/sourcemap.js +340 -0
  240. package/dist/api/compiler/spelling.d.ts +14 -0
  241. package/dist/api/compiler/spelling.js +128 -0
  242. package/dist/api/compiler/symbol-accessibility.d.ts +57 -0
  243. package/dist/api/compiler/symbol-accessibility.js +894 -0
  244. package/dist/api/compiler/symbol.d.ts +240 -0
  245. package/dist/api/compiler/symbol.js +228 -0
  246. package/dist/api/compiler/symlinks.d.ts +32 -0
  247. package/dist/api/compiler/symlinks.js +114 -0
  248. package/dist/api/compiler/syntax-kind.d.ts +389 -0
  249. package/dist/api/compiler/syntax-kind.js +2 -0
  250. package/dist/api/compiler/timeline.d.ts +9 -0
  251. package/dist/api/compiler/timeline.js +54 -0
  252. package/dist/api/compiler/transformers/alias-references.d.ts +39 -0
  253. package/dist/api/compiler/transformers/alias-references.js +676 -0
  254. package/dist/api/compiler/transformers/async-utilities.d.ts +51 -0
  255. package/dist/api/compiler/transformers/async-utilities.js +260 -0
  256. package/dist/api/compiler/transformers/async.d.ts +53 -0
  257. package/dist/api/compiler/transformers/async.js +645 -0
  258. package/dist/api/compiler/transformers/class-fields.d.ts +206 -0
  259. package/dist/api/compiler/transformers/class-fields.js +2418 -0
  260. package/dist/api/compiler/transformers/class-utilities.d.ts +46 -0
  261. package/dist/api/compiler/transformers/class-utilities.js +261 -0
  262. package/dist/api/compiler/transformers/commonjs-module.d.ts +103 -0
  263. package/dist/api/compiler/transformers/commonjs-module.js +1180 -0
  264. package/dist/api/compiler/transformers/const-enum-inliner.d.ts +11 -0
  265. package/dist/api/compiler/transformers/const-enum-inliner.js +36 -0
  266. package/dist/api/compiler/transformers/declarations-diagnostics.d.ts +52 -0
  267. package/dist/api/compiler/transformers/declarations-diagnostics.js +538 -0
  268. package/dist/api/compiler/transformers/declarations-pseudo.d.ts +160 -0
  269. package/dist/api/compiler/transformers/declarations-pseudo.js +797 -0
  270. package/dist/api/compiler/transformers/declarations-resolver.d.ts +152 -0
  271. package/dist/api/compiler/transformers/declarations-resolver.js +35 -0
  272. package/dist/api/compiler/transformers/declarations-syntactic.d.ts +119 -0
  273. package/dist/api/compiler/transformers/declarations-syntactic.js +1582 -0
  274. package/dist/api/compiler/transformers/declarations-tracker.d.ts +46 -0
  275. package/dist/api/compiler/transformers/declarations-tracker.js +197 -0
  276. package/dist/api/compiler/transformers/declarations.d.ts +175 -0
  277. package/dist/api/compiler/transformers/declarations.js +2380 -0
  278. package/dist/api/compiler/transformers/decorator-metadata.d.ts +54 -0
  279. package/dist/api/compiler/transformers/decorator-metadata.js +554 -0
  280. package/dist/api/compiler/transformers/decorator-utilities.d.ts +38 -0
  281. package/dist/api/compiler/transformers/decorator-utilities.js +238 -0
  282. package/dist/api/compiler/transformers/destructuring.d.ts +25 -0
  283. package/dist/api/compiler/transformers/destructuring.js +626 -0
  284. package/dist/api/compiler/transformers/downlevel.d.ts +6 -0
  285. package/dist/api/compiler/transformers/downlevel.js +45 -0
  286. package/dist/api/compiler/transformers/emit-resolver.d.ts +61 -0
  287. package/dist/api/compiler/transformers/emit-resolver.js +197 -0
  288. package/dist/api/compiler/transformers/es-decorators.d.ts +118 -0
  289. package/dist/api/compiler/transformers/es-decorators.js +1901 -0
  290. package/dist/api/compiler/transformers/exponentiation.d.ts +11 -0
  291. package/dist/api/compiler/transformers/exponentiation.js +76 -0
  292. package/dist/api/compiler/transformers/external-module-info.d.ts +35 -0
  293. package/dist/api/compiler/transformers/external-module-info.js +351 -0
  294. package/dist/api/compiler/transformers/for-await.d.ts +43 -0
  295. package/dist/api/compiler/transformers/for-await.js +469 -0
  296. package/dist/api/compiler/transformers/import-elision.d.ts +16 -0
  297. package/dist/api/compiler/transformers/import-elision.js +124 -0
  298. package/dist/api/compiler/transformers/jsx-entities.d.ts +1 -0
  299. package/dist/api/compiler/transformers/jsx-entities.js +256 -0
  300. package/dist/api/compiler/transformers/jsx.d.ts +71 -0
  301. package/dist/api/compiler/transformers/jsx.js +700 -0
  302. package/dist/api/compiler/transformers/legacy-decorators.d.ts +56 -0
  303. package/dist/api/compiler/transformers/legacy-decorators.js +564 -0
  304. package/dist/api/compiler/transformers/logical-assignment.d.ts +14 -0
  305. package/dist/api/compiler/transformers/logical-assignment.js +62 -0
  306. package/dist/api/compiler/transformers/module-utilities.d.ts +9 -0
  307. package/dist/api/compiler/transformers/module-utilities.js +36 -0
  308. package/dist/api/compiler/transformers/module.d.ts +49 -0
  309. package/dist/api/compiler/transformers/module.js +296 -0
  310. package/dist/api/compiler/transformers/named-evaluation.d.ts +26 -0
  311. package/dist/api/compiler/transformers/named-evaluation.js +266 -0
  312. package/dist/api/compiler/transformers/nullish-coalescing.d.ts +9 -0
  313. package/dist/api/compiler/transformers/nullish-coalescing.js +26 -0
  314. package/dist/api/compiler/transformers/object-rest-spread.d.ts +34 -0
  315. package/dist/api/compiler/transformers/object-rest-spread.js +411 -0
  316. package/dist/api/compiler/transformers/optional-catch.d.ts +9 -0
  317. package/dist/api/compiler/transformers/optional-catch.js +20 -0
  318. package/dist/api/compiler/transformers/optional-chain.d.ts +14 -0
  319. package/dist/api/compiler/transformers/optional-chain.js +188 -0
  320. package/dist/api/compiler/transformers/reference-resolver.d.ts +128 -0
  321. package/dist/api/compiler/transformers/reference-resolver.js +1155 -0
  322. package/dist/api/compiler/transformers/runtime-syntax.d.ts +71 -0
  323. package/dist/api/compiler/transformers/runtime-syntax.js +753 -0
  324. package/dist/api/compiler/transformers/subtree-facts.d.ts +9 -0
  325. package/dist/api/compiler/transformers/subtree-facts.js +203 -0
  326. package/dist/api/compiler/transformers/syntax-facts.d.ts +51 -0
  327. package/dist/api/compiler/transformers/syntax-facts.js +254 -0
  328. package/dist/api/compiler/transformers/tagged-template.d.ts +17 -0
  329. package/dist/api/compiler/transformers/tagged-template.js +148 -0
  330. package/dist/api/compiler/transformers/transformer.d.ts +17 -0
  331. package/dist/api/compiler/transformers/transformer.js +54 -0
  332. package/dist/api/compiler/transformers/type-eraser.d.ts +21 -0
  333. package/dist/api/compiler/transformers/type-eraser.js +346 -0
  334. package/dist/api/compiler/transformers/type-serialization.d.ts +20 -0
  335. package/dist/api/compiler/transformers/type-serialization.js +347 -0
  336. package/dist/api/compiler/transformers/using.d.ts +56 -0
  337. package/dist/api/compiler/transformers/using.js +453 -0
  338. package/dist/api/compiler/transformers/utilities.d.ts +50 -0
  339. package/dist/api/compiler/transformers/utilities.js +347 -0
  340. package/dist/api/compiler/transformers/visitor-base.d.ts +6 -0
  341. package/dist/api/compiler/transformers/visitor-base.js +817 -0
  342. package/dist/api/compiler/transformers/visitor-hooks.d.ts +29 -0
  343. package/dist/api/compiler/transformers/visitor-hooks.js +189 -0
  344. package/dist/api/compiler/tsconfig.d.ts +177 -0
  345. package/dist/api/compiler/tsconfig.js +1311 -0
  346. package/dist/api/compiler/type-printer.d.ts +15 -0
  347. package/dist/api/compiler/type-printer.js +74 -0
  348. package/dist/api/compiler/types.d.ts +87 -0
  349. package/dist/api/compiler/types.js +23 -0
  350. package/dist/api/compiler/unicode-identifiers.d.ts +2 -0
  351. package/dist/api/compiler/unicode-identifiers.js +209 -0
  352. package/dist/api/compiler/unicode-properties.d.ts +8 -0
  353. package/dist/api/compiler/unicode-properties.js +531 -0
  354. package/dist/api/compiler/vfs-match.d.ts +24 -0
  355. package/dist/api/compiler/vfs-match.js +587 -0
  356. package/dist/api/library/ast.d.ts +3 -2
  357. package/dist/api/library/ast.generated.d.ts +127 -139
  358. package/dist/api/library/checker.d.ts +51 -0
  359. package/dist/api/library/checker.js +318 -0
  360. package/dist/api/library/diagnostics.d.ts +13 -0
  361. package/dist/api/library/diagnostics.js +50 -0
  362. package/dist/api/library/disk.d.ts +13 -0
  363. package/dist/api/library/disk.js +66 -0
  364. package/dist/api/library/errors.d.ts +13 -0
  365. package/dist/api/library/errors.js +24 -0
  366. package/dist/api/library/host.d.ts +24 -0
  367. package/dist/api/library/host.js +52 -0
  368. package/dist/api/library/index.d.ts +5 -1
  369. package/dist/api/library/index.js +4 -0
  370. package/dist/api/library/nodes.d.ts +51 -0
  371. package/dist/api/library/nodes.js +196 -0
  372. package/dist/api/library/options.d.ts +144 -0
  373. package/dist/api/library/options.js +308 -0
  374. package/dist/api/library/parse.d.ts +19 -0
  375. package/dist/api/library/parse.js +41 -0
  376. package/dist/api/library/program.d.ts +21 -0
  377. package/dist/api/library/program.js +234 -0
  378. package/dist/api/library/types.d.ts +14 -1
  379. package/package.json +12 -8
  380. package/src/compiler/ast-utilities.ts +548 -0
  381. package/src/compiler/ast.ts +12862 -0
  382. package/src/compiler/astnav.ts +799 -0
  383. package/src/compiler/binder-utilities.ts +1392 -0
  384. package/src/compiler/binder.ts +2703 -0
  385. package/src/compiler/build-info.ts +1197 -0
  386. package/src/compiler/character-codes.ts +323 -0
  387. package/src/compiler/checker-calls.ts +2155 -0
  388. package/src/compiler/checker-classes.ts +706 -0
  389. package/src/compiler/checker-contextual.ts +1457 -0
  390. package/src/compiler/checker-declaration-order.ts +438 -0
  391. package/src/compiler/checker-declarations.ts +1194 -0
  392. package/src/compiler/checker-declared-types.ts +919 -0
  393. package/src/compiler/checker-decorators.ts +694 -0
  394. package/src/compiler/checker-deprecation.ts +359 -0
  395. package/src/compiler/checker-destructuring.ts +805 -0
  396. package/src/compiler/checker-elaboration.ts +477 -0
  397. package/src/compiler/checker-emit-helpers.ts +224 -0
  398. package/src/compiler/checker-emit-resolver.ts +769 -0
  399. package/src/compiler/checker-evaluator.ts +243 -0
  400. package/src/compiler/checker-expressions.ts +1831 -0
  401. package/src/compiler/checker-features.ts +361 -0
  402. package/src/compiler/checker-flow.ts +394 -0
  403. package/src/compiler/checker-functions.ts +1296 -0
  404. package/src/compiler/checker-generated-code.ts +227 -0
  405. package/src/compiler/checker-globals.ts +52 -0
  406. package/src/compiler/checker-grammar.ts +3584 -0
  407. package/src/compiler/checker-heritage.ts +1233 -0
  408. package/src/compiler/checker-inference.ts +2576 -0
  409. package/src/compiler/checker-iteration.ts +1206 -0
  410. package/src/compiler/checker-javascript.ts +502 -0
  411. package/src/compiler/checker-jsdoc.ts +360 -0
  412. package/src/compiler/checker-jsx.ts +1924 -0
  413. package/src/compiler/checker-literals.ts +61 -0
  414. package/src/compiler/checker-members.ts +2436 -0
  415. package/src/compiler/checker-modules.ts +2886 -0
  416. package/src/compiler/checker-narrowing.ts +3230 -0
  417. package/src/compiler/checker-object-literals.ts +575 -0
  418. package/src/compiler/checker-operators.ts +1422 -0
  419. package/src/compiler/checker-overloads.ts +328 -0
  420. package/src/compiler/checker-property-access.ts +906 -0
  421. package/src/compiler/checker-services.ts +1149 -0
  422. package/src/compiler/checker-signatures.ts +1032 -0
  423. package/src/compiler/checker-source-file.ts +732 -0
  424. package/src/compiler/checker-statements.ts +292 -0
  425. package/src/compiler/checker-super.ts +261 -0
  426. package/src/compiler/checker-symbol-types.ts +2107 -0
  427. package/src/compiler/checker-symbols.ts +2150 -0
  428. package/src/compiler/checker-type-factory.ts +2579 -0
  429. package/src/compiler/checker-type-nodes.ts +1033 -0
  430. package/src/compiler/checker-type-operators.ts +2502 -0
  431. package/src/compiler/checker-types.ts +2340 -0
  432. package/src/compiler/checker-unused.ts +642 -0
  433. package/src/compiler/checker-utilities.ts +161 -0
  434. package/src/compiler/checker.ts +1116 -0
  435. package/src/compiler/command-line.ts +436 -0
  436. package/src/compiler/compile-program.ts +439 -0
  437. package/src/compiler/decoder.ts +1209 -0
  438. package/src/compiler/diagnostic-locales.ts +86 -0
  439. package/src/compiler/diagnostic-messages.ts +2349 -0
  440. package/src/compiler/diagnostics.ts +897 -0
  441. package/src/compiler/emitter.ts +434 -0
  442. package/src/compiler/encoder.ts +1945 -0
  443. package/src/compiler/file-include.ts +673 -0
  444. package/src/compiler/file-loader.ts +1528 -0
  445. package/src/compiler/file-system.ts +143 -0
  446. package/src/compiler/flow.ts +89 -0
  447. package/src/compiler/help.ts +473 -0
  448. package/src/compiler/incremental.ts +2784 -0
  449. package/src/compiler/init.ts +141 -0
  450. package/src/compiler/instantiation.ts +894 -0
  451. package/src/compiler/jsdoc.ts +1386 -0
  452. package/src/compiler/link-tables.ts +98 -0
  453. package/src/compiler/locale-data.ts +203 -0
  454. package/src/compiler/locale.ts +307 -0
  455. package/src/compiler/locales/cs-CZ.ts +5 -0
  456. package/src/compiler/locales/de-DE.ts +5 -0
  457. package/src/compiler/locales/es-ES.ts +5 -0
  458. package/src/compiler/locales/fr-FR.ts +5 -0
  459. package/src/compiler/locales/it-IT.ts +5 -0
  460. package/src/compiler/locales/ja-JP.ts +5 -0
  461. package/src/compiler/locales/ko-KR.ts +5 -0
  462. package/src/compiler/locales/pl-PL.ts +5 -0
  463. package/src/compiler/locales/pt-BR.ts +5 -0
  464. package/src/compiler/locales/ru-RU.ts +5 -0
  465. package/src/compiler/locales/tr-TR.ts +5 -0
  466. package/src/compiler/locales/zh-CN.ts +5 -0
  467. package/src/compiler/locales/zh-TW.ts +5 -0
  468. package/src/compiler/module-resolution-types.ts +243 -0
  469. package/src/compiler/module-resolution.ts +2072 -0
  470. package/src/compiler/module-specifiers.ts +1491 -0
  471. package/src/compiler/name-resolver.ts +646 -0
  472. package/src/compiler/node-builder-names.ts +1069 -0
  473. package/src/compiler/node-builder-pseudo.ts +892 -0
  474. package/src/compiler/node-builder-reuse.ts +764 -0
  475. package/src/compiler/node-builder.ts +3425 -0
  476. package/src/compiler/option-declarations.ts +1560 -0
  477. package/src/compiler/options.ts +1576 -0
  478. package/src/compiler/output-paths.ts +334 -0
  479. package/src/compiler/package-json.ts +1083 -0
  480. package/src/compiler/parallel-check.ts +1951 -0
  481. package/src/compiler/parallel-parse.ts +590 -0
  482. package/src/compiler/parse-thread.ts +140 -0
  483. package/src/compiler/parser.ts +7716 -0
  484. package/src/compiler/path.ts +717 -0
  485. package/src/compiler/printer/async-helpers.ts +183 -0
  486. package/src/compiler/printer/auto-generate.ts +27 -0
  487. package/src/compiler/printer/decorator-helpers.ts +218 -0
  488. package/src/compiler/printer/emit-context.ts +679 -0
  489. package/src/compiler/printer/emit-flags.ts +64 -0
  490. package/src/compiler/printer/factory-base.ts +2577 -0
  491. package/src/compiler/printer/factory.ts +764 -0
  492. package/src/compiler/printer/helpers.ts +291 -0
  493. package/src/compiler/printer/name-generator.ts +372 -0
  494. package/src/compiler/printer/printer.ts +5072 -0
  495. package/src/compiler/printer/text-writer.ts +183 -0
  496. package/src/compiler/printer/utilities.ts +884 -0
  497. package/src/compiler/program-checker.ts +592 -0
  498. package/src/compiler/program-utilities.ts +435 -0
  499. package/src/compiler/program.ts +1419 -0
  500. package/src/compiler/pseudo-bigint.ts +62 -0
  501. package/src/compiler/regexp-checker.ts +1142 -0
  502. package/src/compiler/relations.ts +5149 -0
  503. package/src/compiler/reparser.ts +1566 -0
  504. package/src/compiler/scanner.ts +2951 -0
  505. package/src/compiler/show-config.ts +239 -0
  506. package/src/compiler/side-state.ts +125 -0
  507. package/src/compiler/sourcemap.ts +366 -0
  508. package/src/compiler/spelling.ts +122 -0
  509. package/src/compiler/symbol-accessibility.ts +1071 -0
  510. package/src/compiler/symbol.ts +439 -0
  511. package/src/compiler/symlinks.ts +137 -0
  512. package/src/compiler/syntax-kind.ts +391 -0
  513. package/src/compiler/thread-entry.ts +191 -0
  514. package/src/compiler/timeline.ts +53 -0
  515. package/src/compiler/transformers/alias-references.ts +757 -0
  516. package/src/compiler/transformers/async-utilities.ts +335 -0
  517. package/src/compiler/transformers/async.ts +838 -0
  518. package/src/compiler/transformers/class-fields.ts +2967 -0
  519. package/src/compiler/transformers/class-utilities.ts +324 -0
  520. package/src/compiler/transformers/commonjs-module.ts +1621 -0
  521. package/src/compiler/transformers/const-enum-inliner.ts +50 -0
  522. package/src/compiler/transformers/declarations-diagnostics.ts +832 -0
  523. package/src/compiler/transformers/declarations-pseudo.ts +966 -0
  524. package/src/compiler/transformers/declarations-resolver.ts +249 -0
  525. package/src/compiler/transformers/declarations-syntactic.ts +1859 -0
  526. package/src/compiler/transformers/declarations-tracker.ts +269 -0
  527. package/src/compiler/transformers/declarations.ts +3120 -0
  528. package/src/compiler/transformers/decorator-metadata.ts +697 -0
  529. package/src/compiler/transformers/decorator-utilities.ts +283 -0
  530. package/src/compiler/transformers/destructuring.ts +708 -0
  531. package/src/compiler/transformers/downlevel.ts +50 -0
  532. package/src/compiler/transformers/emit-resolver.ts +258 -0
  533. package/src/compiler/transformers/es-decorators.ts +2682 -0
  534. package/src/compiler/transformers/exponentiation.ts +80 -0
  535. package/src/compiler/transformers/external-module-info.ts +412 -0
  536. package/src/compiler/transformers/for-await.ts +687 -0
  537. package/src/compiler/transformers/import-elision.ts +152 -0
  538. package/src/compiler/transformers/jsx-entities.ts +256 -0
  539. package/src/compiler/transformers/jsx.ts +824 -0
  540. package/src/compiler/transformers/legacy-decorators.ts +726 -0
  541. package/src/compiler/transformers/logical-assignment.ts +75 -0
  542. package/src/compiler/transformers/module-utilities.ts +42 -0
  543. package/src/compiler/transformers/module.ts +474 -0
  544. package/src/compiler/transformers/named-evaluation.ts +389 -0
  545. package/src/compiler/transformers/nullish-coalescing.ts +35 -0
  546. package/src/compiler/transformers/object-rest-spread.ts +577 -0
  547. package/src/compiler/transformers/optional-catch.ts +29 -0
  548. package/src/compiler/transformers/optional-chain.ts +246 -0
  549. package/src/compiler/transformers/reference-resolver.ts +1201 -0
  550. package/src/compiler/transformers/runtime-syntax.ts +942 -0
  551. package/src/compiler/transformers/subtree-facts.ts +245 -0
  552. package/src/compiler/transformers/syntax-facts.ts +353 -0
  553. package/src/compiler/transformers/tagged-template.ts +167 -0
  554. package/src/compiler/transformers/transformer.ts +56 -0
  555. package/src/compiler/transformers/type-eraser.ts +520 -0
  556. package/src/compiler/transformers/type-serialization.ts +374 -0
  557. package/src/compiler/transformers/using.ts +613 -0
  558. package/src/compiler/transformers/utilities.ts +419 -0
  559. package/src/compiler/transformers/visitor-base.ts +1601 -0
  560. package/src/compiler/transformers/visitor-hooks.ts +252 -0
  561. package/src/compiler/tsc-build.ts +1418 -0
  562. package/src/compiler/tsc-cli.ts +666 -0
  563. package/src/compiler/tsc-compile.ts +437 -0
  564. package/src/compiler/tsc-watch.ts +854 -0
  565. package/src/compiler/tsconfig.ts +1574 -0
  566. package/src/compiler/type-printer.ts +110 -0
  567. package/src/compiler/types.ts +115 -0
  568. package/src/compiler/unicode-identifiers.ts +212 -0
  569. package/src/compiler/unicode-properties.ts +537 -0
  570. package/src/compiler/vfs-match.ts +597 -0
  571. package/src/compiler/xxh3.ts +650 -0
  572. package/src/library/ast.generated.ts +141 -167
  573. package/src/library/ast.ts +4 -1
  574. package/src/library/checker.ts +384 -0
  575. package/src/library/diagnostics.ts +72 -0
  576. package/src/library/disk.ts +73 -0
  577. package/src/library/errors.ts +26 -0
  578. package/src/library/host.ts +63 -0
  579. package/src/library/index.ts +21 -0
  580. package/src/library/nodes.ts +232 -0
  581. package/src/library/options.ts +449 -0
  582. package/src/library/parse.ts +63 -0
  583. package/src/library/program.ts +293 -0
  584. package/src/library/types.ts +14 -1
@@ -0,0 +1,3120 @@
1
+ // The declaration transform: turns a source file into its declaration file. Keeps exported and
2
+ // referenced declarations without their implementations, writes the types of declarations from
3
+ // their annotations or the resolver, and elides imports the output doesn't use.
4
+ import { getJSDoc } from '../parser.js';
5
+ import {
6
+ BindingElement,
7
+ BindingPattern,
8
+ CallSignatureDeclaration,
9
+ ClassDeclaration,
10
+ ClassExpression,
11
+ ComputedPropertyName,
12
+ ConditionalTypeNode,
13
+ ConstructSignatureDeclaration,
14
+ ConstructorDeclaration,
15
+ ConstructorTypeNode,
16
+ EnumDeclaration,
17
+ EnumMember,
18
+ ExportAssignment,
19
+ ExportDeclaration,
20
+ ExpressionWithTypeArguments,
21
+ ExternalModuleReference,
22
+ FileReference,
23
+ ArrayTypeNode,
24
+ ArrowFunction,
25
+ BinaryExpression,
26
+ JSDocNonNullableType,
27
+ JSDocNullableType,
28
+ JSDocOptionalType,
29
+ JSDocParameterOrPropertyTag,
30
+ JSDocTypeLiteral,
31
+ JSDocVariadicType,
32
+ TypeLiteralNode,
33
+ UnionTypeNode,
34
+ ElementAccessExpression,
35
+ ExportSpecifier,
36
+ FunctionDeclaration,
37
+ FunctionExpression,
38
+ FunctionTypeNode,
39
+ ImportSpecifier,
40
+ NodeVisitor,
41
+ PropertyAccessExpression,
42
+ QualifiedName,
43
+ getArguments,
44
+ GetAccessorDeclaration,
45
+ HeritageClause,
46
+ Identifier,
47
+ ImportAttributes,
48
+ ImportClause,
49
+ ImportDeclaration,
50
+ ImportEqualsDeclaration,
51
+ ImportTypeNode,
52
+ IndexSignatureDeclaration,
53
+ InterfaceDeclaration,
54
+ JSDocTypeExpression,
55
+ KeywordTypeNode,
56
+ LiteralTypeNode,
57
+ MappedTypeNode,
58
+ MethodDeclaration,
59
+ MethodSignatureDeclaration,
60
+ ModifierFlags,
61
+ ModifierList,
62
+ ModuleBlock,
63
+ ModuleDeclaration,
64
+ NamedExports,
65
+ NamedImports,
66
+ NamespaceImport,
67
+ type Node,
68
+ NodeFlags,
69
+ NodeList,
70
+ NumericLiteral,
71
+ ParameterDeclaration,
72
+ PrefixUnaryExpression,
73
+ PrivateIdentifier,
74
+ PropertyDeclaration,
75
+ PropertySignatureDeclaration,
76
+ JSDoc,
77
+ JSDocText,
78
+ ScriptKind,
79
+ SetAccessorDeclaration,
80
+ SourceFile,
81
+ StringLiteral,
82
+ SyntaxList,
83
+ Token,
84
+ TypeAliasDeclaration,
85
+ TypeParameterDeclaration,
86
+ TypeQueryNode,
87
+ TypeReferenceNode,
88
+ VariableDeclaration,
89
+ VariableDeclarationList,
90
+ VariableStatement,
91
+ getExpression,
92
+ getHeritageClauses,
93
+ getMembers,
94
+ getInitializer,
95
+ getModifiers,
96
+ getName,
97
+ getParameters,
98
+ getSymbol,
99
+ getText,
100
+ getType,
101
+ getTypeParameters,
102
+ isDeclarationNode,
103
+ } from '../ast.js';
104
+ import {
105
+ isAmbientModule,
106
+ isAnyImportOrReExport,
107
+ isFunctionLike,
108
+ isGlobalScopeAugmentation,
109
+ isInJSFile,
110
+ isLiteralImportTypeNode,
111
+ modifierToFlag,
112
+ nodeIsMissing,
113
+ nodeIsPresent,
114
+ } from '../ast-utilities.js';
115
+ import {
116
+ JSDeclarationKind,
117
+ getAssignmentDeclarationKind,
118
+ getCombinedModifierFlags,
119
+ getCombinedNodeFlags,
120
+ getElementOrPropertyAccessName,
121
+ getThisContainer,
122
+ isVariableDeclarationInitializedToRequire,
123
+ getSourceFileOfNode,
124
+ getSourceTextOfNode,
125
+ hasDynamicName,
126
+ hasSyntacticModifier,
127
+ isEntityNameExpression,
128
+ isExternalOrCommonJSModule,
129
+ isStatic,
130
+ } from '../binder-utilities.js';
131
+ import { type Diagnostic, Diagnostics } from '../diagnostics.js';
132
+ import type { CompilerOptions } from '../options.js';
133
+ import { type OutputPathsHost, getOutputPathsFor } from '../output-paths.js';
134
+ import { getDirectoryPath, normalizeSlashes } from '../path.js';
135
+ import type { EmitContext } from '../printer/emit-context.js';
136
+ import { EmitFlags, GeneratedIdentifierFlags } from '../printer/emit-flags.js';
137
+ import { isModifier } from '../printer/utilities.js';
138
+ import {
139
+ getLeadingCommentRanges,
140
+ getTrailingCommentRanges,
141
+ identifierToKeywordKind,
142
+ isIdentifierText,
143
+ skipTrivia,
144
+ stringToToken,
145
+ } from '../scanner.js';
146
+ import { SymbolFlags } from '../symbol.js';
147
+ import type { CommentRange } from '../types.js';
148
+ import { getRelativePathToDirectoryOrUrl } from '../sourcemap.js';
149
+ import { SyntaxKind } from '../syntax-kind.js';
150
+ import { TokenFlags } from '../types.js';
151
+ import {
152
+ DiagnosticContext,
153
+ DiagnosticContextKind,
154
+ canProduceDiagnostics,
155
+ createDiagnosticForNode,
156
+ declarationContext,
157
+ declarationNameContext,
158
+ noDiagnosticContext,
159
+ } from './declarations-diagnostics.js';
160
+ import { type DeclarationEmitResolver, NodeBuilderFlags } from './declarations-resolver.js';
161
+ import { ConstantKind } from './reference-resolver.js';
162
+ import { DeclarationTracker } from './declarations-tracker.js';
163
+ import { Transformer } from './transformer.js';
164
+
165
+ export class DeclarationTransformer extends Transformer {
166
+ readonly host: OutputPathsHost;
167
+ readonly options: CompilerOptions;
168
+ readonly resolver: DeclarationEmitResolver;
169
+ readonly tracker: DeclarationTracker;
170
+ private readonly declarationFilePath: string;
171
+
172
+ private needsDeclare: boolean;
173
+ private needsScopeFixMarker: boolean;
174
+ private resultHasScopeMarker: boolean;
175
+ private resultHasExternalModuleIndicator: boolean;
176
+ private enclosingDeclaration: Node;
177
+ /** Whether types are inside an object type, where new diagnostic contexts aren't entered. */
178
+ private suppressNewDiagnosticContexts: boolean;
179
+ private inClassExpressionDeclaration: boolean;
180
+ /** Transformed top-level declarations by original node; undefined for removed ones. */
181
+ private lateStatementReplacements: Map<Node, Node | undefined>;
182
+ /** Functions with assigned properties (`f.x = 1`), transformed, by statement. */
183
+ private readonly expandoHosts: Map<Node, Node | undefined>;
184
+ /** The namespace members for the assigned properties of each function, by statement. */
185
+ private readonly expandoMembers: Map<Node, Node[]>;
186
+ /** The `export =` for a CommonJS `module.exports = …`. */
187
+ private cjsExportAssignment: Node | undefined;
188
+ /** The exports for CommonJS `exports.x = …` assignments. */
189
+ private cjsExportMembers: Node[];
190
+ /** The name of the `module.exports` value, which `exports.x` members are nested in. */
191
+ private cjsExportAssignmentName: Identifier | undefined;
192
+ private readonly witnessedCjsExports: Set<string>;
193
+ /** `this.x` members found in a JavaScript class, and their keys. */
194
+ private thisPropertyAssignments: Node[];
195
+ private readonly seenProperties: Set<string>;
196
+
197
+ constructor(
198
+ context: EmitContext,
199
+ host: OutputPathsHost,
200
+ options: CompilerOptions,
201
+ resolver: DeclarationEmitResolver,
202
+ declarationFilePath: string,
203
+ ) {
204
+ super(context);
205
+ this.host = host;
206
+ this.options = options;
207
+ this.resolver = resolver;
208
+ this.tracker = new DeclarationTracker(
209
+ resolver,
210
+ options.isolatedDeclarations === true,
211
+ options.stripInternal === true,
212
+ );
213
+ this.declarationFilePath = declarationFilePath;
214
+ this.needsDeclare = true;
215
+ this.needsScopeFixMarker = false;
216
+ this.resultHasScopeMarker = false;
217
+ this.resultHasExternalModuleIndicator = false;
218
+ this.enclosingDeclaration = context.factory.createToken(SyntaxKind.Unknown);
219
+ this.suppressNewDiagnosticContexts = false;
220
+ this.inClassExpressionDeclaration = false;
221
+ this.lateStatementReplacements = new Map<Node, Node | undefined>();
222
+ this.expandoHosts = new Map<Node, Node | undefined>();
223
+ this.expandoMembers = new Map<Node, Node[]>();
224
+ this.cjsExportAssignment = undefined;
225
+ this.cjsExportMembers = [];
226
+ this.cjsExportAssignmentName = undefined;
227
+ this.witnessedCjsExports = new Set<string>();
228
+ this.thisPropertyAssignments = [];
229
+ this.seenProperties = new Set<string>();
230
+ }
231
+
232
+ get diagnostics(): Diagnostic[] {
233
+ return this.tracker.diagnostics;
234
+ }
235
+
236
+ visit(node: Node): Node | undefined {
237
+ switch (node.kind) {
238
+ case SyntaxKind.SourceFile:
239
+ if (node instanceof SourceFile) {
240
+ const narrowed: SourceFile = node;
241
+ return this.visitSourceFile(narrowed);
242
+ }
243
+ break;
244
+ case SyntaxKind.FunctionDeclaration:
245
+ case SyntaxKind.ModuleDeclaration:
246
+ case SyntaxKind.ImportEqualsDeclaration:
247
+ case SyntaxKind.InterfaceDeclaration:
248
+ case SyntaxKind.ClassDeclaration:
249
+ case SyntaxKind.JSTypeAliasDeclaration:
250
+ case SyntaxKind.TypeAliasDeclaration:
251
+ case SyntaxKind.EnumDeclaration:
252
+ case SyntaxKind.VariableStatement:
253
+ case SyntaxKind.ImportDeclaration:
254
+ case SyntaxKind.JSImportDeclaration:
255
+ case SyntaxKind.ExportDeclaration:
256
+ case SyntaxKind.ExportAssignment:
257
+ return this.visitDeclarationStatement(node);
258
+ case SyntaxKind.BreakStatement:
259
+ case SyntaxKind.ContinueStatement:
260
+ case SyntaxKind.DebuggerStatement:
261
+ case SyntaxKind.DoStatement:
262
+ case SyntaxKind.EmptyStatement:
263
+ case SyntaxKind.ForInStatement:
264
+ case SyntaxKind.ForOfStatement:
265
+ case SyntaxKind.ForStatement:
266
+ case SyntaxKind.IfStatement:
267
+ case SyntaxKind.LabeledStatement:
268
+ case SyntaxKind.ReturnStatement:
269
+ case SyntaxKind.SwitchStatement:
270
+ case SyntaxKind.ThrowStatement:
271
+ case SyntaxKind.TryStatement:
272
+ case SyntaxKind.WhileStatement:
273
+ case SyntaxKind.WithStatement:
274
+ case SyntaxKind.NotEmittedStatement:
275
+ case SyntaxKind.Block:
276
+ case SyntaxKind.MissingDeclaration:
277
+ case SyntaxKind.ExpressionStatement:
278
+ return undefined;
279
+ }
280
+ return this.visitDeclarationSubtree(node);
281
+ }
282
+
283
+ // Source files
284
+
285
+ private visitSourceFile(file: SourceFile): Node {
286
+ if (file.isDeclarationFile) return file;
287
+ this.needsDeclare = true;
288
+ this.needsScopeFixMarker = false;
289
+ this.resultHasScopeMarker = false;
290
+ this.resultHasExternalModuleIndicator = false;
291
+ this.enclosingDeclaration = file;
292
+ this.suppressNewDiagnosticContexts = false;
293
+ this.lateStatementReplacements = new Map<Node, Node | undefined>();
294
+ this.expandoHosts.clear();
295
+ this.expandoMembers.clear();
296
+ this.witnessedCjsExports.clear();
297
+ this.cjsExportAssignment = undefined;
298
+ this.cjsExportAssignmentName = undefined;
299
+ this.cjsExportMembers = [];
300
+ const tracker = this.tracker;
301
+ tracker.diagnosticContext = noDiagnosticContext;
302
+ tracker.lateMarkedStatements = [];
303
+ tracker.currentSourceFile = file;
304
+ this.resolver.precalculateDeclarationEmitVisibility(this.originalSourceFile(file));
305
+ // `module.exports =` first: `exports.x` members are nested under its name.
306
+ if (file.commonJSModuleIndicator !== undefined)
307
+ file.forEachChild(new ExpressionWalker(this, ExpressionWalkerKind.ModuleExports));
308
+ file.forEachChild(new ExpressionWalker(this, ExpressionWalkerKind.Members));
309
+ const statements = this.visitNodes(file.statements)!;
310
+ let combined = this.appendCjsExports(this.transformAndReplaceLatePaintedStatements(statements));
311
+ combined.pos = statements.pos;
312
+ combined.end = statements.end;
313
+ if (isExternalOrCommonJSModule(file) && file.isJS()) this.reportMultipleModuleExports(file);
314
+ if (
315
+ isExternalOrCommonJSModule(file) &&
316
+ (!this.resultHasExternalModuleIndicator || (this.needsScopeFixMarker && !this.resultHasScopeMarker))
317
+ ) {
318
+ const nodes = combined.nodes.slice();
319
+ nodes.push(this.createEmptyExports());
320
+ const withMarker = new NodeList(combined.pos, combined.end, nodes);
321
+ combined = withMarker;
322
+ }
323
+ const result = this.factory.updateSourceFile(file, combined, file.endOfFileToken);
324
+ // Always a new node: references and the declaration flag differ from the input.
325
+ const updated =
326
+ result === file
327
+ ? this.factory.updateSourceFile(
328
+ file,
329
+ new NodeList(combined.pos, combined.end, combined.nodes),
330
+ file.endOfFileToken,
331
+ )
332
+ : result;
333
+ updated.isDeclarationFile = true;
334
+ updated.libReferenceDirectives = preservedReferences(file.libReferenceDirectives);
335
+ updated.typeReferenceDirectives = preservedReferences(file.typeReferenceDirectives);
336
+ updated.referencedFiles = this.getReferencedFiles(
337
+ file,
338
+ getDirectoryPath(normalizeSlashes(this.declarationFilePath)),
339
+ );
340
+ tracker.currentSourceFile = undefined;
341
+ this.cjsExportAssignment = undefined;
342
+ this.cjsExportAssignmentName = undefined;
343
+ this.cjsExportMembers = [];
344
+ return updated;
345
+ }
346
+
347
+ private originalSourceFile(file: SourceFile): SourceFile {
348
+ const original = this.context.mostOriginal(file);
349
+ if (original === undefined || original.kind !== SyntaxKind.SourceFile) return file;
350
+ return original as SourceFile;
351
+ }
352
+
353
+ private appendCjsExports(statements: NodeList): NodeList {
354
+ if (this.cjsExportAssignment === undefined && this.cjsExportMembers.length === 0) return statements;
355
+ const result: Node[] = [];
356
+ if (this.cjsExportAssignment !== undefined) appendFlattened(result, this.cjsExportAssignment);
357
+ for (const member of this.cjsExportMembers) appendFlattened(result, member);
358
+ for (const statement of statements.nodes) result.push(statement);
359
+ return this.factory.createNodeList(result);
360
+ }
361
+
362
+ private reportMultipleModuleExports(file: SourceFile): boolean {
363
+ const symbol = file.symbol;
364
+ const exportEquals =
365
+ symbol === undefined || symbol.exports === undefined ? undefined : symbol.exports.get('export=');
366
+ if (exportEquals === undefined || exportEquals.declarations.length <= 1) return false;
367
+ for (const declaration of exportEquals.declarations)
368
+ this.tracker.addDiagnostic(
369
+ createDiagnosticForNode(
370
+ declaration,
371
+ Diagnostics.Multiple_module_exports_assignments_cannot_be_serialized_for_declaration_emit,
372
+ [],
373
+ ),
374
+ );
375
+ return true;
376
+ }
377
+
378
+ private createEmptyExports(): Node {
379
+ return this.factory.created(
380
+ new ExportDeclaration(
381
+ undefined,
382
+ false,
383
+ this.factory.created(new NamedExports(this.factory.createNodeList([]))),
384
+ undefined,
385
+ undefined,
386
+ ),
387
+ );
388
+ }
389
+
390
+ /** `/// <reference path>` directives with `preserve="true"`, relative to the output. */
391
+ private getReferencedFiles(file: SourceFile, outputDirectory: string): FileReference[] {
392
+ const result: FileReference[] = [];
393
+ for (const reference of file.referencedFiles) {
394
+ if (!reference.preserve) continue;
395
+ const target = this.resolver.getSourceFileFromReference(file, reference);
396
+ if (target === undefined) continue;
397
+ let fileName = target.fileName;
398
+ if (!target.isDeclarationFile) {
399
+ // The referenced file's declaration output, else its JavaScript output.
400
+ const paths = getOutputPathsFor(
401
+ target.fileName,
402
+ target.scriptKind === ScriptKind.JSON,
403
+ this.options,
404
+ this.host,
405
+ true,
406
+ );
407
+ fileName = paths.declarationFilePath !== '' ? paths.declarationFilePath : paths.jsFilePath;
408
+ if (fileName === '') fileName = target.fileName;
409
+ }
410
+ if (fileName === '') continue;
411
+ const relative = getRelativePathToDirectoryOrUrl(
412
+ outputDirectory,
413
+ fileName,
414
+ this.host.useCaseSensitiveFileNames,
415
+ this.host.currentDirectory,
416
+ );
417
+ result.push(new FileReference(-1, -1, relative, reference.resolutionMode, reference.preserve));
418
+ }
419
+ return result;
420
+ }
421
+
422
+ /**
423
+ * Replaces top-level declarations with their transformed forms. Transforming a declaration can
424
+ * mark more unexported declarations as referenced, so this runs until none are left.
425
+ */
426
+ private transformAndReplaceLatePaintedStatements(statements: NodeList): NodeList {
427
+ const tracker = this.tracker;
428
+ while (tracker.lateMarkedStatements.length > 0) {
429
+ const next = tracker.lateMarkedStatements.shift()!;
430
+ const saveNeedsDeclare = this.needsDeclare;
431
+ this.needsDeclare = next.parent !== undefined && next.parent.kind === SyntaxKind.SourceFile;
432
+ const result = this.transformTopLevelDeclaration(next);
433
+ this.needsDeclare = saveNeedsDeclare;
434
+ this.lateStatementReplacements.set(this.context.mostOriginal(next), result);
435
+ }
436
+ const results: Node[] = [];
437
+ for (const statement of statements.nodes) {
438
+ if (!isLateVisibilityPaintedStatement(statement)) {
439
+ results.push(statement);
440
+ continue;
441
+ }
442
+ const original = this.context.mostOriginal(statement);
443
+ if (!this.lateStatementReplacements.has(original)) {
444
+ results.push(statement);
445
+ continue;
446
+ }
447
+ const replacement = this.lateStatementReplacements.get(original);
448
+ if (replacement === undefined) continue;
449
+ const atTopLevel = statement.parent !== undefined && statement.parent.kind === SyntaxKind.SourceFile;
450
+ if (replacement instanceof SyntaxList) {
451
+ if (!this.needsScopeFixMarker || !this.resultHasExternalModuleIndicator)
452
+ for (const child of replacement.children) {
453
+ if (needsScopeMarker(child)) this.needsScopeFixMarker = true;
454
+ if (atTopLevel && isExternalModuleIndicator(child)) this.resultHasExternalModuleIndicator = true;
455
+ }
456
+ for (const child of replacement.children) results.push(child);
457
+ } else {
458
+ if (needsScopeMarker(replacement)) this.needsScopeFixMarker = true;
459
+ if (atTopLevel && isExternalModuleIndicator(replacement)) this.resultHasExternalModuleIndicator = true;
460
+ results.push(replacement);
461
+ }
462
+ }
463
+ return this.factory.createNodeList(results);
464
+ }
465
+
466
+ // Diagnostic contexts
467
+
468
+ private enterDiagnosticContext(input: Node): DiagnosticScope {
469
+ const tracker = this.tracker;
470
+ const scope = new DiagnosticScope(
471
+ tracker.diagnosticContext,
472
+ tracker.errorNameNode,
473
+ this.suppressNewDiagnosticContexts,
474
+ );
475
+ if (canProduceDiagnostics(input) && !this.suppressNewDiagnosticContexts)
476
+ tracker.diagnosticContext = declarationContext(input);
477
+ if (
478
+ (input.kind === SyntaxKind.TypeLiteral || input.kind === SyntaxKind.MappedType) &&
479
+ input.parent !== undefined &&
480
+ input.parent.kind !== SyntaxKind.TypeAliasDeclaration &&
481
+ input.parent.kind !== SyntaxKind.JSTypeAliasDeclaration
482
+ )
483
+ this.suppressNewDiagnosticContexts = true;
484
+ return scope;
485
+ }
486
+
487
+ private exitDiagnosticContext(scope: DiagnosticScope): boolean {
488
+ this.tracker.diagnosticContext = scope.context;
489
+ this.tracker.errorNameNode = scope.errorNameNode;
490
+ this.suppressNewDiagnosticContexts = scope.suppressNewDiagnosticContexts;
491
+ return true;
492
+ }
493
+
494
+ // Declarations below the top level
495
+
496
+ private visitDeclarationSubtree(input: Node): Node | undefined {
497
+ if (input === undefined) return undefined;
498
+ if (this.shouldStripInternal(input)) return undefined;
499
+ if (isDeclaration(input)) {
500
+ if (this.isDeclarationAndNotVisible(input)) return undefined;
501
+ if (hasDynamicName(input)) {
502
+ const expression = getExpression(getName(input)!)!;
503
+ if (this.tracker.isolatedDeclarations) {
504
+ // Computed names that aren't literal types can't be checked without types.
505
+ if (!this.resolver.isDefinitelyReferenceToGlobalSymbolObject(expression)) {
506
+ const parentKind = input.parent!.kind;
507
+ if (parentKind === SyntaxKind.ClassDeclaration || parentKind === SyntaxKind.ObjectLiteralExpression) {
508
+ this.tracker.addDiagnostic(
509
+ createDiagnosticForNode(
510
+ input,
511
+ Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations,
512
+ [],
513
+ ),
514
+ );
515
+ return undefined;
516
+ }
517
+ if (
518
+ (parentKind === SyntaxKind.InterfaceDeclaration || parentKind === SyntaxKind.TypeLiteral) &&
519
+ !isEntityNameExpression(expression, false)
520
+ ) {
521
+ this.tracker.addDiagnostic(
522
+ createDiagnosticForNode(
523
+ input,
524
+ Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations,
525
+ [],
526
+ ),
527
+ );
528
+ return undefined;
529
+ }
530
+ }
531
+ } else if (!this.resolver.isLateBound(this.parseNode(input)) || !isEntityNameExpression(expression, false))
532
+ return undefined;
533
+ }
534
+ }
535
+ // Implementations of overloads are elided.
536
+ if (isFunctionLike(input) && this.resolver.isImplementationOfOverload(input)) return undefined;
537
+ if (input.kind === SyntaxKind.SemicolonClassElement) return undefined;
538
+ if (input instanceof HeritageClause) {
539
+ const types = input.types.nodes;
540
+ if (types.length === 0 || (types.length === 1 && nodeIsMissing(types[0]))) return undefined;
541
+ }
542
+ const previousEnclosingDeclaration = this.enclosingDeclaration;
543
+ if (isEnclosingDeclaration(input)) this.enclosingDeclaration = input;
544
+ const canProduceDiagnostic = canProduceDiagnostics(input);
545
+ const scope = this.enterDiagnosticContext(input);
546
+ const result = this.transformDeclarationSubtree(input);
547
+ if (result !== undefined && canProduceDiagnostic && hasDynamicName(input)) this.checkName(input);
548
+ this.exitDiagnosticContext(scope);
549
+ this.enclosingDeclaration = previousEnclosingDeclaration;
550
+ return result;
551
+ }
552
+
553
+ private transformDeclarationSubtree(input: Node): Node | undefined {
554
+ switch (input.kind) {
555
+ case SyntaxKind.MappedType:
556
+ if (input instanceof MappedTypeNode) {
557
+ const narrowed: MappedTypeNode = input;
558
+ return this.transformMappedType(narrowed);
559
+ }
560
+ break;
561
+ case SyntaxKind.HeritageClause:
562
+ if (input instanceof HeritageClause) {
563
+ const narrowed: HeritageClause = input;
564
+ return this.transformHeritageClause(narrowed);
565
+ }
566
+ break;
567
+ case SyntaxKind.MethodSignature:
568
+ if (input instanceof MethodSignatureDeclaration) {
569
+ const narrowed: MethodSignatureDeclaration = input;
570
+ return this.transformMethodSignature(narrowed);
571
+ }
572
+ break;
573
+ case SyntaxKind.MethodDeclaration:
574
+ if (input instanceof MethodDeclaration) {
575
+ const narrowed: MethodDeclaration = input;
576
+ return this.transformMethodDeclaration(narrowed);
577
+ }
578
+ break;
579
+ case SyntaxKind.ConstructSignature:
580
+ if (input instanceof ConstructSignatureDeclaration) {
581
+ const narrowed: ConstructSignatureDeclaration = input;
582
+ return this.transformConstructSignature(narrowed);
583
+ }
584
+ break;
585
+ case SyntaxKind.Constructor:
586
+ if (input instanceof ConstructorDeclaration) {
587
+ const narrowed: ConstructorDeclaration = input;
588
+ return this.transformConstructor(narrowed);
589
+ }
590
+ break;
591
+ case SyntaxKind.GetAccessor:
592
+ if (input instanceof GetAccessorDeclaration) {
593
+ const narrowed: GetAccessorDeclaration = input;
594
+ return this.transformGetAccessor(narrowed);
595
+ }
596
+ break;
597
+ case SyntaxKind.SetAccessor:
598
+ if (input instanceof SetAccessorDeclaration) {
599
+ const narrowed: SetAccessorDeclaration = input;
600
+ return this.transformSetAccessor(narrowed);
601
+ }
602
+ break;
603
+ case SyntaxKind.PropertyDeclaration:
604
+ if (input instanceof PropertyDeclaration) {
605
+ const narrowed: PropertyDeclaration = input;
606
+ return this.transformPropertyDeclaration(narrowed);
607
+ }
608
+ break;
609
+ case SyntaxKind.PropertySignature:
610
+ if (input instanceof PropertySignatureDeclaration) {
611
+ const narrowed: PropertySignatureDeclaration = input;
612
+ return this.transformPropertySignature(narrowed);
613
+ }
614
+ break;
615
+ case SyntaxKind.CallSignature:
616
+ if (input instanceof CallSignatureDeclaration) {
617
+ const narrowed: CallSignatureDeclaration = input;
618
+ return this.transformCallSignature(narrowed);
619
+ }
620
+ break;
621
+ case SyntaxKind.IndexSignature:
622
+ if (input instanceof IndexSignatureDeclaration) {
623
+ const narrowed: IndexSignatureDeclaration = input;
624
+ return this.transformIndexSignature(narrowed);
625
+ }
626
+ break;
627
+ case SyntaxKind.VariableDeclaration:
628
+ if (input instanceof VariableDeclaration) {
629
+ const narrowed: VariableDeclaration = input;
630
+ return this.transformVariableDeclaration(narrowed);
631
+ }
632
+ break;
633
+ case SyntaxKind.TypeParameter:
634
+ if (input instanceof TypeParameterDeclaration) {
635
+ const narrowed: TypeParameterDeclaration = input;
636
+ return this.transformTypeParameter(narrowed);
637
+ }
638
+ break;
639
+ case SyntaxKind.ExpressionWithTypeArguments: {
640
+ const expression = (input as ExpressionWithTypeArguments).expression;
641
+ if (isEntityName(expression) || isEntityNameExpression(expression, false))
642
+ this.checkEntityNameVisibility(expression, this.enclosingDeclaration);
643
+ return this.visitEachChild(input);
644
+ }
645
+ case SyntaxKind.TypeReference:
646
+ this.checkEntityNameVisibility((input as TypeReferenceNode).typeName, this.enclosingDeclaration);
647
+ return this.visitEachChild(input);
648
+ case SyntaxKind.ConditionalType:
649
+ if (input instanceof ConditionalTypeNode) {
650
+ const narrowed: ConditionalTypeNode = input;
651
+ return this.transformConditionalType(narrowed);
652
+ }
653
+ break;
654
+ case SyntaxKind.FunctionType:
655
+ if (input instanceof FunctionTypeNode) {
656
+ const narrowed: FunctionTypeNode = input;
657
+ return this.transformFunctionType(narrowed);
658
+ }
659
+ break;
660
+ case SyntaxKind.ConstructorType:
661
+ if (input instanceof ConstructorTypeNode) {
662
+ const narrowed: ConstructorTypeNode = input;
663
+ return this.transformConstructorType(narrowed);
664
+ }
665
+ break;
666
+ case SyntaxKind.ImportType:
667
+ if (input instanceof ImportTypeNode) {
668
+ const narrowed: ImportTypeNode = input;
669
+ return this.transformImportType(narrowed);
670
+ }
671
+ break;
672
+ case SyntaxKind.TypeQuery:
673
+ this.checkEntityNameVisibility((input as TypeQueryNode).exprName, this.enclosingDeclaration);
674
+ return this.visitEachChild(input);
675
+ case SyntaxKind.TupleType: {
676
+ const result = this.visitEachChild(input);
677
+ if (isOriginalNodeSingleLine(this.context, input)) this.context.addEmitFlags(result, EmitFlags.SingleLine);
678
+ return result;
679
+ }
680
+ case SyntaxKind.JSDocTypeExpression:
681
+ return this.visitNode((input as JSDocTypeExpression).type);
682
+ case SyntaxKind.JSDocAllType:
683
+ return this.replaceWith(input, this.keyword(SyntaxKind.AnyKeyword));
684
+ case SyntaxKind.JSDocNullableType:
685
+ // `?T` is `T | null`.
686
+ return this.replaceWith(
687
+ input,
688
+ this.createUnion(
689
+ this.visitNode((input as JSDocNullableType).type)!,
690
+ this.factory.created(new LiteralTypeNode(this.factory.createKeywordExpression(SyntaxKind.NullKeyword))),
691
+ ),
692
+ );
693
+ case SyntaxKind.JSDocNonNullableType:
694
+ return this.visitNode((input as JSDocNonNullableType).type);
695
+ case SyntaxKind.JSDocOptionalType:
696
+ // `T=` is `T | undefined`.
697
+ return this.replaceWith(
698
+ input,
699
+ this.createUnion(
700
+ this.visitNode((input as JSDocOptionalType).type)!,
701
+ this.keyword(SyntaxKind.UndefinedKeyword),
702
+ ),
703
+ );
704
+ case SyntaxKind.JSDocVariadicType:
705
+ // `...T` is `T[]`.
706
+ return this.replaceWith(
707
+ input,
708
+ this.factory.created(new ArrayTypeNode(this.visitNode((input as JSDocVariadicType).type)!)),
709
+ );
710
+ case SyntaxKind.JSDocTypeLiteral: {
711
+ const members = this.visitArray((input as JSDocTypeLiteral).jsdocPropertyTags ?? []);
712
+ return this.replaceWith(input, this.factory.created(new TypeLiteralNode(this.factory.createNodeList(members))));
713
+ }
714
+ case SyntaxKind.JSDocPropertyTag: {
715
+ const tag = input as JSDocParameterOrPropertyTag;
716
+ const type = tag.typeExpression === undefined ? undefined : this.visitNode(tag.typeExpression);
717
+ return this.replaceWith(
718
+ input,
719
+ this.factory.created(
720
+ new PropertySignatureDeclaration(undefined, this.visitNode(tag.name)!, undefined, type, undefined),
721
+ ),
722
+ );
723
+ }
724
+ }
725
+ return this.visitEachChild(input);
726
+ }
727
+
728
+ private createUnion(first: Node, second: Node): Node {
729
+ return this.factory.created(new UnionTypeNode(this.factory.createNodeList([first, second])));
730
+ }
731
+
732
+ private replaceWith(original: Node, replacement: Node): Node {
733
+ this.context.setOriginal(replacement, original);
734
+ return replacement;
735
+ }
736
+
737
+ private keyword(kind: SyntaxKind): Node {
738
+ return this.factory.created(new KeywordTypeNode(kind));
739
+ }
740
+
741
+ private checkName(node: Node): boolean {
742
+ const tracker = this.tracker;
743
+ const oldContext = tracker.diagnosticContext;
744
+ if (!this.suppressNewDiagnosticContexts) tracker.diagnosticContext = declarationNameContext(node);
745
+ const name = getName(node)!;
746
+ tracker.errorNameNode = name;
747
+ this.checkEntityNameVisibility(getExpression(name)!, this.enclosingDeclaration);
748
+ if (!this.suppressNewDiagnosticContexts) tracker.diagnosticContext = oldContext;
749
+ tracker.errorNameNode = undefined;
750
+ return true;
751
+ }
752
+
753
+ private checkEntityNameVisibility(entityName: Node, enclosingDeclaration: Node): boolean {
754
+ return this.tracker.handleSymbolAccessibilityError(
755
+ this.resolver.isEntityNameVisible(entityName, enclosingDeclaration),
756
+ );
757
+ }
758
+
759
+ private transformMappedType(input: MappedTypeNode): Node {
760
+ // The printer needs a template type.
761
+ const type = input.type === undefined ? this.keyword(SyntaxKind.AnyKeyword) : this.visitNode(input.type);
762
+ return this.factory.updateMappedTypeNode(
763
+ input,
764
+ input.readonlyToken,
765
+ this.visitNode(input.typeParameter) as TypeParameterDeclaration,
766
+ this.visitNode(input.nameType),
767
+ input.questionToken,
768
+ type,
769
+ undefined,
770
+ );
771
+ }
772
+
773
+ private transformHeritageClause(clause: HeritageClause): Node | undefined {
774
+ const types = clause.types.nodes;
775
+ const retained: Node[] = [];
776
+ for (const type of types) {
777
+ const expression = (type as ExpressionWithTypeArguments).expression;
778
+ if (
779
+ isEntityNameExpression(expression, false) ||
780
+ (clause.token === SyntaxKind.ExtendsKeyword && expression.kind === SyntaxKind.NullKeyword)
781
+ )
782
+ retained.push(type);
783
+ }
784
+ if (retained.length === 0) return undefined;
785
+ if (retained.length === types.length) return this.visitEachChild(clause);
786
+ return this.factory.updateHeritageClause(
787
+ clause,
788
+ clause.token,
789
+ this.visitNodes(this.factory.createNodeList(retained))!,
790
+ );
791
+ }
792
+
793
+ private transformImportType(input: ImportTypeNode): Node {
794
+ if (!isLiteralImportTypeNode(input)) return input;
795
+ const argument = input.argument as LiteralTypeNode;
796
+ return this.factory.updateImportTypeNode(
797
+ input,
798
+ input.isTypeOf,
799
+ this.factory.updateLiteralTypeNode(argument, this.rewriteModuleSpecifier(input, argument.literal)!),
800
+ input.attributes,
801
+ input.qualifier,
802
+ this.visitNodes(input.typeArguments),
803
+ );
804
+ }
805
+
806
+ private transformConstructorType(input: ConstructorTypeNode): Node {
807
+ return this.factory.updateConstructorTypeNode(
808
+ input,
809
+ this.ensureModifiers(input),
810
+ this.visitNodes(input.typeParameters),
811
+ this.updateParamList(input, input.parameters),
812
+ this.visitNode(input.type),
813
+ );
814
+ }
815
+
816
+ private transformFunctionType(input: FunctionTypeNode): Node {
817
+ return this.factory.updateFunctionTypeNode(
818
+ input,
819
+ this.visitNodes(input.typeParameters),
820
+ this.updateParamList(input, input.parameters),
821
+ this.visitNode(input.type),
822
+ );
823
+ }
824
+
825
+ private transformConditionalType(input: ConditionalTypeNode): Node {
826
+ const checkType = this.visitNode(input.checkType)!;
827
+ const extendsType = this.visitNode(input.extendsType)!;
828
+ const previousEnclosingDeclaration = this.enclosingDeclaration;
829
+ this.enclosingDeclaration = input.trueType;
830
+ const trueType = this.visitNode(input.trueType)!;
831
+ this.enclosingDeclaration = previousEnclosingDeclaration;
832
+ const falseType = this.visitNode(input.falseType)!;
833
+ return this.factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType);
834
+ }
835
+
836
+ private transformTypeParameter(input: TypeParameterDeclaration): Node {
837
+ // Type parameters of private methods lose their constraints and defaults.
838
+ const parent = input.parent;
839
+ if (
840
+ parent !== undefined &&
841
+ parent.kind === SyntaxKind.MethodDeclaration &&
842
+ this.isPrivate(parent) &&
843
+ (input.defaultType !== undefined || input.constraint !== undefined)
844
+ )
845
+ return this.factory.updateTypeParameterDeclaration(
846
+ input,
847
+ input.modifiers,
848
+ input.name,
849
+ undefined,
850
+ input.expression,
851
+ undefined,
852
+ );
853
+ return this.visitEachChild(input);
854
+ }
855
+
856
+ private transformVariableDeclaration(input: VariableDeclaration): Node | undefined {
857
+ const file = this.tracker.currentSourceFile;
858
+ if (
859
+ file !== undefined &&
860
+ file.commonJSModuleIndicator !== undefined &&
861
+ isVariableDeclarationInitializedToRequire(input)
862
+ )
863
+ return this.transformCjsRequireVariableDeclaration(input);
864
+ if (input.name instanceof BindingPattern) return this.recreateBindingPattern(input.name);
865
+ // Variable types don't enter new diagnostic contexts.
866
+ this.suppressNewDiagnosticContexts = true;
867
+ return this.factory.updateVariableDeclaration(
868
+ input,
869
+ input.name,
870
+ undefined,
871
+ this.ensureType(input, false),
872
+ this.ensureNoInitializer(input),
873
+ );
874
+ }
875
+
876
+ private recreateBindingPattern(pattern: BindingPattern): Node | undefined {
877
+ const results: Node[] = [];
878
+ for (const element of pattern.elements.nodes) {
879
+ if (element === undefined || !(element instanceof BindingElement)) continue;
880
+ const result = this.recreateBindingElement(element);
881
+ if (result instanceof SyntaxList) for (const child of result.children) results.push(child);
882
+ else if (result !== undefined) results.push(result);
883
+ }
884
+ if (results.length === 0) return undefined;
885
+ if (results.length === 1) return results[0];
886
+ return this.factory.createSyntaxList(results);
887
+ }
888
+
889
+ private recreateBindingElement(element: BindingElement): Node | undefined {
890
+ const name = element.name;
891
+ if (name === undefined || !this.getBindingNameVisible(element)) return undefined;
892
+ if (name instanceof BindingPattern) {
893
+ const narrowed: BindingPattern = name;
894
+ return this.recreateBindingPattern(narrowed);
895
+ }
896
+ return this.factory.createVariableDeclaration(name, undefined, this.ensureType(element, false), undefined);
897
+ }
898
+
899
+ private transformIndexSignature(input: IndexSignatureDeclaration): Node {
900
+ const type = this.visitNode(input.type) ?? this.keyword(SyntaxKind.AnyKeyword);
901
+ return this.factory.updateIndexSignatureDeclaration(
902
+ input,
903
+ this.ensureModifiers(input),
904
+ this.updateParamList(input, input.parameters),
905
+ type,
906
+ );
907
+ }
908
+
909
+ private transformCallSignature(input: CallSignatureDeclaration): Node {
910
+ return this.factory.updateCallSignatureDeclaration(
911
+ input,
912
+ this.ensureTypeParams(input, input.typeParameters),
913
+ this.updateParamList(input, input.parameters),
914
+ this.ensureType(input, false),
915
+ );
916
+ }
917
+
918
+ private transformPropertySignature(input: PropertySignatureDeclaration): Node | undefined {
919
+ if (input.name instanceof PrivateIdentifier) return undefined;
920
+ const result = this.factory.updatePropertySignatureDeclaration(
921
+ input,
922
+ this.ensureModifiers(input),
923
+ input.name,
924
+ input.postfixToken,
925
+ this.ensureType(input, false),
926
+ this.ensureNoInitializer(input),
927
+ );
928
+ this.preservePartialJsDoc(result, input);
929
+ return result;
930
+ }
931
+
932
+ /** Writes the description of a property from a JSDoc `@property` tag as its comment. */
933
+ private preservePartialJsDoc(updated: Node, original: Node): boolean {
934
+ if ((original.flags & NodeFlags.Reparsed) === 0) return false;
935
+ const docs = getJSDoc(getSourceFileOfNode(original), original);
936
+ if (docs.length === 0 || !(docs[0] instanceof JSDoc)) return false;
937
+ const description = getTextOfJSDocComment(docs[0].comment);
938
+ if (description === '') return false;
939
+ const comment = '*\n * ' + description.split('\n').join('\n * ') + '\n ';
940
+ this.context.addSyntheticLeadingComment(updated, SyntaxKind.MultiLineCommentTrivia, comment, true);
941
+ return true;
942
+ }
943
+
944
+ private transformPropertyDeclaration(input: PropertyDeclaration): Node | undefined {
945
+ if (input.name instanceof PrivateIdentifier) return undefined;
946
+ // Definite assignment assertions (`!`) are dropped.
947
+ const postfix = input.postfixToken;
948
+ return this.factory.updatePropertyDeclaration(
949
+ input,
950
+ this.ensureModifiers(input),
951
+ input.name,
952
+ postfix !== undefined && postfix.kind === SyntaxKind.ExclamationToken ? undefined : postfix,
953
+ this.ensureType(input, false),
954
+ this.ensureNoInitializer(input),
955
+ );
956
+ }
957
+
958
+ private transformSetAccessor(input: SetAccessorDeclaration): Node | undefined {
959
+ if (input.name instanceof PrivateIdentifier) return undefined;
960
+ return this.factory.updateSetAccessorDeclaration(
961
+ input,
962
+ this.ensureModifiers(input),
963
+ input.name,
964
+ undefined,
965
+ this.updateAccessorParamList(input, this.isPrivate(this.parseNode(input))),
966
+ undefined,
967
+ undefined,
968
+ undefined,
969
+ );
970
+ }
971
+
972
+ private transformGetAccessor(input: GetAccessorDeclaration): Node | undefined {
973
+ if (input.name instanceof PrivateIdentifier) return undefined;
974
+ return this.factory.updateGetAccessorDeclaration(
975
+ input,
976
+ this.ensureModifiers(input),
977
+ input.name,
978
+ undefined,
979
+ this.updateAccessorParamList(input, this.isPrivate(this.parseNode(input))),
980
+ this.ensureType(input, false),
981
+ undefined,
982
+ undefined,
983
+ );
984
+ }
985
+
986
+ private updateAccessorParamList(input: Node, isPrivate: boolean): NodeList {
987
+ const params: Node[] = [];
988
+ const parameters = getParameters(input)!.nodes;
989
+ if (!isPrivate) {
990
+ const thisParameter = parameters.length > 0 && isThisParameterNode(parameters[0]) ? parameters[0] : undefined;
991
+ if (thisParameter !== undefined) params.push(this.ensureParameterNode(thisParameter));
992
+ }
993
+ if (input.kind === SyntaxKind.SetAccessor) {
994
+ let valueParameter: Node | undefined = undefined;
995
+ if (!isPrivate) {
996
+ if (params.length === 1 && parameters.length >= 2) valueParameter = this.ensureParameterNode(parameters[1]);
997
+ else if (params.length === 0 && parameters.length >= 1)
998
+ valueParameter = this.ensureParameterNode(parameters[0]);
999
+ }
1000
+ // A missing value parameter is `value: any`, untyped when private.
1001
+ valueParameter ??= this.factory.created(
1002
+ new ParameterDeclaration(
1003
+ undefined,
1004
+ undefined,
1005
+ this.factory.createIdentifier('value'),
1006
+ undefined,
1007
+ isPrivate ? undefined : this.keyword(SyntaxKind.AnyKeyword),
1008
+ undefined,
1009
+ ),
1010
+ );
1011
+ params.push(valueParameter);
1012
+ }
1013
+ return this.factory.createNodeList(params);
1014
+ }
1015
+
1016
+ private transformConstructor(input: ConstructorDeclaration): Node {
1017
+ return this.factory.updateConstructorDeclaration(
1018
+ input,
1019
+ this.ensureModifiers(input),
1020
+ undefined,
1021
+ this.updateParamList(input, input.parameters),
1022
+ undefined,
1023
+ undefined,
1024
+ undefined,
1025
+ );
1026
+ }
1027
+
1028
+ private transformConstructSignature(input: ConstructSignatureDeclaration): Node {
1029
+ return this.factory.updateConstructSignatureDeclaration(
1030
+ input,
1031
+ this.ensureTypeParams(input, input.typeParameters),
1032
+ this.updateParamList(input, input.parameters),
1033
+ this.ensureType(input, false),
1034
+ );
1035
+ }
1036
+
1037
+ /** A private method is written as a property without a type. */
1038
+ private omitPrivateMethodType(input: Node): Node | undefined {
1039
+ const symbol = getSymbol(input);
1040
+ if (symbol !== undefined && symbol.declarations.length > 0 && symbol.declarations[0] !== input) return undefined;
1041
+ const result = this.factory.created(
1042
+ new PropertyDeclaration(this.ensureModifiers(input), getName(input)!, undefined, undefined, undefined),
1043
+ );
1044
+ this.context.assignCommentRange(result, input);
1045
+ return result;
1046
+ }
1047
+
1048
+ private transformMethodSignature(input: MethodSignatureDeclaration): Node | undefined {
1049
+ if (this.isPrivate(this.parseNode(input))) return this.omitPrivateMethodType(input);
1050
+ if (input.name instanceof PrivateIdentifier) return undefined;
1051
+ return this.factory.updateMethodSignatureDeclaration(
1052
+ input,
1053
+ this.ensureModifiers(input),
1054
+ input.name,
1055
+ input.postfixToken,
1056
+ this.ensureTypeParams(input, input.typeParameters),
1057
+ this.updateParamList(input, input.parameters),
1058
+ this.ensureType(input, false),
1059
+ );
1060
+ }
1061
+
1062
+ private transformMethodDeclaration(input: MethodDeclaration): Node | undefined {
1063
+ if (this.isPrivate(this.parseNode(input))) return this.omitPrivateMethodType(input);
1064
+ if (input.name instanceof PrivateIdentifier) return undefined;
1065
+ return this.factory.updateMethodDeclaration(
1066
+ input,
1067
+ this.ensureModifiers(input),
1068
+ undefined,
1069
+ input.name,
1070
+ input.postfixToken,
1071
+ this.ensureTypeParams(input, input.typeParameters),
1072
+ this.updateParamList(input, input.parameters),
1073
+ this.ensureType(input, false),
1074
+ undefined,
1075
+ undefined,
1076
+ );
1077
+ }
1078
+
1079
+ // Top-level declarations
1080
+
1081
+ private visitDeclarationStatement(input: Node): Node | undefined {
1082
+ if (input === undefined) return undefined;
1083
+ if (this.shouldStripInternal(input)) return undefined;
1084
+ if (input instanceof ExportDeclaration) {
1085
+ if (input.parent !== undefined && input.parent.kind === SyntaxKind.SourceFile)
1086
+ this.resultHasExternalModuleIndicator = true;
1087
+ this.resultHasScopeMarker = true;
1088
+ return this.factory.updateExportDeclaration(
1089
+ input,
1090
+ input.modifiers,
1091
+ input.isTypeOnly,
1092
+ input.exportClause,
1093
+ this.rewriteModuleSpecifier(input, input.moduleSpecifier),
1094
+ this.tryGetResolutionModeOverride(input.attributes),
1095
+ );
1096
+ }
1097
+ if (input instanceof ExportAssignment)
1098
+ return this.transformExportAssignment(input, input, input.expression, input.isExportEquals);
1099
+ // Transformed later, when it's known which unexported declarations are referenced.
1100
+ const original = this.context.mostOriginal(input);
1101
+ if (this.lateStatementReplacements.get(original) === undefined)
1102
+ this.lateStatementReplacements.set(original, this.transformTopLevelDeclaration(input));
1103
+ return input;
1104
+ }
1105
+
1106
+ /** `export =`, `export default` or `module.exports =` of `expression`. */
1107
+ transformExportAssignment(
1108
+ input: Node,
1109
+ assignment: Node,
1110
+ expression: Node,
1111
+ isExportEquals: boolean,
1112
+ ): Node | undefined {
1113
+ if (input.parent !== undefined && input.parent.kind === SyntaxKind.SourceFile)
1114
+ this.resultHasExternalModuleIndicator = true;
1115
+ this.resultHasScopeMarker = true;
1116
+ if (
1117
+ expression instanceof Identifier &&
1118
+ input.parent !== undefined &&
1119
+ (input.parent.kind === SyntaxKind.SourceFile || input.parent.kind === SyntaxKind.ModuleBlock)
1120
+ ) {
1121
+ const result = this.factory.created(new ExportAssignment(undefined, isExportEquals, undefined, expression));
1122
+ this.context.assignCommentRange(result, input);
1123
+ return result;
1124
+ }
1125
+ const unwrapped = skipOuterExpressions(expression);
1126
+ const name = this.getNameOfExportedExpression(unwrapped, isExportEquals);
1127
+ // Class and function expressions become declarations.
1128
+ if (unwrapped instanceof ClassExpression || isFunctionLike(unwrapped)) {
1129
+ const declaration =
1130
+ unwrapped instanceof ClassExpression
1131
+ ? this.transformClassExpressionToDeclaration(unwrapped, name, this.declareModifiers())
1132
+ : this.transformFunctionLikeToDeclaration(unwrapped, name, this.declareModifiers());
1133
+ this.context.assignCommentRange(declaration, input);
1134
+ const exportAssignment = this.factory.created(new ExportAssignment(undefined, isExportEquals, undefined, name));
1135
+ this.context.addEmitFlags(exportAssignment, EmitFlags.NoComments);
1136
+ return this.factory.createSyntaxList([exportAssignment, declaration]);
1137
+ }
1138
+ // Other expressions are written as a `_default` variable with the expression's type.
1139
+ const tracker = this.tracker;
1140
+ tracker.diagnosticContext = new DiagnosticContext(DiagnosticContextKind.DefaultExport, input, undefined);
1141
+ this.cjsExportAssignmentName = name;
1142
+ tracker.pushErrorFallbackNode(assignment);
1143
+ let initializer: Node | undefined = undefined;
1144
+ if (isPrimitiveLiteralValue(skipParenthesesOnly(expression), true))
1145
+ initializer = this.resolver.createLiteralConstValue(this.context, this.parseNode(assignment), tracker);
1146
+ const type = initializer === undefined ? this.ensureType(assignment, false) : undefined;
1147
+ const declaration = this.factory.createVariableDeclaration(name, undefined, type, initializer);
1148
+ tracker.popErrorFallbackNode();
1149
+ const statement = this.createConstStatement(declaration);
1150
+ const exportAssignment = this.factory.created(new ExportAssignment(undefined, isExportEquals, undefined, name));
1151
+ this.context.assignCommentRange(statement, input);
1152
+ return this.factory.createSyntaxList([statement, exportAssignment]);
1153
+ }
1154
+
1155
+ private createConstStatement(declaration: VariableDeclaration): Node {
1156
+ return this.factory.createVariableStatement(
1157
+ this.declareModifiers(),
1158
+ this.factory.createVariableDeclarationList(this.factory.createNodeList([declaration]), NodeFlags.Const),
1159
+ );
1160
+ }
1161
+
1162
+ private transformFunctionLikeToDeclaration(fn: Node, name: Identifier, modifiers: ModifierList): Node {
1163
+ const fullSignature = getFullSignature(fn);
1164
+ return this.factory.created(
1165
+ new FunctionDeclaration(
1166
+ modifiers,
1167
+ undefined,
1168
+ name,
1169
+ this.ensureTypeParams(fn, getTypeParameters(fn)),
1170
+ this.updateParamList(fn, getParameters(fn)!),
1171
+ this.ensureType(fn, false),
1172
+ fullSignature === undefined ? undefined : this.visitNode(fullSignature),
1173
+ undefined,
1174
+ ),
1175
+ );
1176
+ }
1177
+
1178
+ /** A class expression as a declaration, for `export default (class {})` and CommonJS exports. */
1179
+ private transformClassExpressionToDeclaration(
1180
+ classExpression: ClassExpression,
1181
+ name: Identifier,
1182
+ modifiers: ModifierList,
1183
+ ): Node {
1184
+ const previousEnclosingDeclaration = this.enclosingDeclaration;
1185
+ this.enclosingDeclaration = classExpression;
1186
+ const previousInClassExpression = this.inClassExpressionDeclaration;
1187
+ this.inClassExpressionDeclaration = true;
1188
+ const extraMembers = isInJSFile(classExpression) ? this.collectThisPropertyAssignments(classExpression) : [];
1189
+ const members = this.buildClassMembers(classExpression, extraMembers);
1190
+ const typeParameters = this.ensureTypeParams(classExpression, classExpression.typeParameters);
1191
+ const heritageClauses = this.visitNodes(classExpression.heritageClauses);
1192
+ this.enclosingDeclaration = previousEnclosingDeclaration;
1193
+ this.inClassExpressionDeclaration = previousInClassExpression;
1194
+ return this.factory.created(new ClassDeclaration(modifiers, name, typeParameters, heritageClauses, members));
1195
+ }
1196
+
1197
+ private declareModifiers(): ModifierList {
1198
+ return this.factory.createModifierList(
1199
+ this.needsDeclare ? [this.factory.createToken(SyntaxKind.DeclareKeyword)] : [],
1200
+ );
1201
+ }
1202
+
1203
+ /** The name of the variable for an exported expression: its own name if it has one, else `_default`. */
1204
+ private getNameOfExportedExpression(expression: Node, isExportEquals: boolean): Identifier {
1205
+ const name = this.tryGetNameOfAssignedExpression(expression);
1206
+ if (name !== undefined) {
1207
+ this.cjsExportAssignmentName = name;
1208
+ return name;
1209
+ }
1210
+ const file = this.tracker.currentSourceFile;
1211
+ // Only JavaScript names `export =` expressions `_exports`.
1212
+ const base = isExportEquals && file !== undefined && file.isJS() ? '_exports' : '_default';
1213
+ const result = this.factory.createUniqueName(base, GeneratedIdentifierFlags.Optimistic);
1214
+ this.cjsExportAssignmentName = result;
1215
+ return result;
1216
+ }
1217
+
1218
+ /** The name of a named function or class expression, unique if it would shadow something. */
1219
+ private tryGetNameOfAssignedExpression(expression: Node): Identifier | undefined {
1220
+ let text = '';
1221
+ if (expression.kind !== SyntaxKind.PropertyAccessExpression) {
1222
+ const name = getName(expression);
1223
+ if (name instanceof Identifier) text = name.text;
1224
+ }
1225
+ if (expression instanceof Identifier) text = expression.text;
1226
+ if (text === '' || text === 'default') return undefined;
1227
+ if (this.resolver.isNameResolvable(this.enclosingDeclaration, text))
1228
+ return this.factory.createUniqueName(text, GeneratedIdentifierFlags.Optimistic);
1229
+ return this.factory.createIdentifier(text);
1230
+ }
1231
+
1232
+ private rewriteModuleSpecifier(parent: Node, input: Node | undefined): Node | undefined {
1233
+ if (input === undefined) return undefined;
1234
+ if (parent.kind !== SyntaxKind.ModuleDeclaration && parent.kind !== SyntaxKind.ImportType)
1235
+ this.resultHasExternalModuleIndicator = true;
1236
+ return input;
1237
+ }
1238
+
1239
+ private tryGetResolutionModeOverride(node: ImportAttributes | undefined): ImportAttributes | undefined {
1240
+ if (node === undefined) return undefined;
1241
+ return this.resolver.getResolutionModeOverride(node) !== undefined ? node : undefined;
1242
+ }
1243
+
1244
+ /** The replacement statements for a direct child of a source file or module block. */
1245
+ private transformTopLevelDeclaration(input: Node): Node | undefined {
1246
+ if (input === undefined) return undefined;
1247
+ const tracker = this.tracker;
1248
+ const marked = tracker.lateMarkedStatements;
1249
+ if (marked.length > 0) {
1250
+ const remaining: Node[] = [];
1251
+ for (const node of marked) if (node !== input) remaining.push(node);
1252
+ tracker.lateMarkedStatements = remaining;
1253
+ }
1254
+ if (this.shouldStripInternal(input)) return undefined;
1255
+ if (input instanceof ImportEqualsDeclaration) {
1256
+ const narrowed: ImportEqualsDeclaration = input;
1257
+ return this.transformImportEquals(narrowed);
1258
+ }
1259
+ if (input instanceof ImportDeclaration) {
1260
+ const result = this.transformImportDeclaration(input);
1261
+ // `import x = require()` in JavaScript is written as an import declaration.
1262
+ if (result !== undefined && result.kind !== SyntaxKind.ImportDeclaration) {
1263
+ // A copy of the declaration, as tsgo's clone: with its position and emit node.
1264
+ const clone = this.factory.created(
1265
+ new ImportDeclaration(
1266
+ SyntaxKind.ImportDeclaration,
1267
+ result.modifiers,
1268
+ result.importClause,
1269
+ result.moduleSpecifier,
1270
+ result.attributes,
1271
+ ),
1272
+ );
1273
+ clone.pos = result.pos;
1274
+ clone.end = result.end;
1275
+ this.context.setOriginal(clone, result);
1276
+ return clone;
1277
+ }
1278
+ return result;
1279
+ }
1280
+ if (isDeclaration(input) && this.isDeclarationAndNotVisible(input)) return undefined;
1281
+ if (isFunctionLike(input) && this.resolver.isImplementationOfOverload(input)) return undefined;
1282
+ const original = this.context.mostOriginal(input);
1283
+ if (this.expandoHosts.has(original)) return this.createFullExpandoBlock(original);
1284
+ const previousEnclosingDeclaration = this.enclosingDeclaration;
1285
+ if (isEnclosingDeclaration(input)) this.enclosingDeclaration = input;
1286
+ const oldContext = tracker.diagnosticContext;
1287
+ const oldName = tracker.errorNameNode;
1288
+ if (canProduceDiagnostics(input)) tracker.diagnosticContext = declarationContext(input);
1289
+ const saveNeedsDeclare = this.needsDeclare;
1290
+ let result: Node | undefined = undefined;
1291
+ switch (input.kind) {
1292
+ case SyntaxKind.TypeAliasDeclaration:
1293
+ case SyntaxKind.JSTypeAliasDeclaration:
1294
+ if (input instanceof TypeAliasDeclaration) {
1295
+ const narrowed: TypeAliasDeclaration = input;
1296
+ result = this.transformTypeAlias(narrowed);
1297
+ }
1298
+ break;
1299
+ case SyntaxKind.InterfaceDeclaration:
1300
+ if (input instanceof InterfaceDeclaration) {
1301
+ const narrowed: InterfaceDeclaration = input;
1302
+ result = this.transformInterface(narrowed);
1303
+ }
1304
+ break;
1305
+ case SyntaxKind.FunctionDeclaration:
1306
+ if (input instanceof FunctionDeclaration) {
1307
+ const narrowed: FunctionDeclaration = input;
1308
+ result = this.transformFunctionDeclaration(narrowed);
1309
+ }
1310
+ break;
1311
+ case SyntaxKind.ModuleDeclaration:
1312
+ if (input instanceof ModuleDeclaration) {
1313
+ const narrowed: ModuleDeclaration = input;
1314
+ result = this.transformModuleDeclaration(narrowed);
1315
+ }
1316
+ break;
1317
+ case SyntaxKind.ClassDeclaration:
1318
+ if (input instanceof ClassDeclaration) {
1319
+ const narrowed: ClassDeclaration = input;
1320
+ result = this.transformClassDeclaration(narrowed);
1321
+ }
1322
+ break;
1323
+ case SyntaxKind.VariableStatement:
1324
+ if (input instanceof VariableStatement) {
1325
+ const narrowed: VariableStatement = input;
1326
+ result = this.transformVariableStatement(narrowed);
1327
+ }
1328
+ break;
1329
+ case SyntaxKind.EnumDeclaration:
1330
+ if (input instanceof EnumDeclaration) {
1331
+ const narrowed: EnumDeclaration = input;
1332
+ result = this.transformEnumDeclaration(narrowed);
1333
+ }
1334
+ break;
1335
+ default:
1336
+ throw new Error('Unhandled top-level node in declaration emit');
1337
+ }
1338
+ this.enclosingDeclaration = previousEnclosingDeclaration;
1339
+ tracker.diagnosticContext = oldContext;
1340
+ this.needsDeclare = saveNeedsDeclare;
1341
+ tracker.errorNameNode = oldName;
1342
+ return result;
1343
+ }
1344
+
1345
+ private transformTypeAlias(input: TypeAliasDeclaration): Node {
1346
+ this.needsDeclare = false;
1347
+ return this.factory.updateTypeAliasDeclaration(
1348
+ input,
1349
+ this.ensureModifiers(input),
1350
+ input.name,
1351
+ this.visitNodes(input.typeParameters),
1352
+ this.visitNode(input.type)!,
1353
+ );
1354
+ }
1355
+
1356
+ private transformInterface(input: InterfaceDeclaration): Node {
1357
+ return this.factory.updateInterfaceDeclaration(
1358
+ input,
1359
+ this.ensureModifiers(input),
1360
+ input.name,
1361
+ this.visitNodes(input.typeParameters),
1362
+ this.visitNodes(input.heritageClauses),
1363
+ this.visitNodes(input.members)!,
1364
+ );
1365
+ }
1366
+
1367
+ private transformFunctionDeclaration(input: FunctionDeclaration): Node {
1368
+ if (this.resolver.isExpandoFunctionDeclaration(input)) this.tracker.reportExpandoFunctionErrors(input);
1369
+ return this.factory.updateFunctionDeclaration(
1370
+ input,
1371
+ this.ensureModifiers(input),
1372
+ undefined,
1373
+ input.name,
1374
+ this.ensureTypeParams(input, input.typeParameters),
1375
+ this.updateParamList(input, input.parameters),
1376
+ this.ensureType(input, false),
1377
+ undefined,
1378
+ undefined,
1379
+ );
1380
+ }
1381
+
1382
+ private transformModuleDeclaration(input: ModuleDeclaration): Node {
1383
+ const modifiers = this.ensureModifiers(input);
1384
+ const saveNeedsDeclare = this.needsDeclare;
1385
+ this.needsDeclare = false;
1386
+ const body = input.body;
1387
+ let keyword = input.keyword;
1388
+ if (keyword !== SyntaxKind.GlobalKeyword && !(input.name instanceof StringLiteral))
1389
+ keyword = SyntaxKind.NamespaceKeyword;
1390
+ if (body !== undefined && body instanceof ModuleBlock) {
1391
+ const oldNeedsScopeFix = this.needsScopeFixMarker;
1392
+ const oldHasScopeFix = this.resultHasScopeMarker;
1393
+ this.resultHasScopeMarker = false;
1394
+ this.needsScopeFixMarker = false;
1395
+ const statements = this.visitNodes(body.statements)!;
1396
+ let lateStatements = this.transformAndReplaceLatePaintedStatements(statements);
1397
+ // In a `declare`d namespace everything is exported already; unexported "privates" don't matter.
1398
+ if ((input.flags & NodeFlags.Ambient) !== 0) this.needsScopeFixMarker = false;
1399
+ // With an `export {}` or `export =` there's nothing to do. Otherwise, if some statements
1400
+ // are unexported, add `export {}`; if all are exported, drop the redundant `export`s.
1401
+ if (!isGlobalScopeAugmentation(input) && !this.resultHasScopeMarker && !hasScopeMarker(lateStatements)) {
1402
+ if (this.needsScopeFixMarker) {
1403
+ const nodes = lateStatements.nodes.slice();
1404
+ nodes.push(this.createEmptyExports());
1405
+ lateStatements = this.factory.createNodeList(nodes);
1406
+ } else lateStatements = this.stripExportModifiersOfList(lateStatements);
1407
+ }
1408
+ const updatedBody = this.factory.updateModuleBlock(body, lateStatements);
1409
+ this.needsDeclare = saveNeedsDeclare;
1410
+ this.needsScopeFixMarker = oldNeedsScopeFix;
1411
+ this.resultHasScopeMarker = oldHasScopeFix;
1412
+ return this.factory.updateModuleDeclaration(input, modifiers, keyword, input.name, updatedBody);
1413
+ }
1414
+ if (body !== undefined) {
1415
+ // A nested `namespace a.b` is transformed now: it needs no visibility painting.
1416
+ this.visitNode(body);
1417
+ const original = this.context.mostOriginal(body);
1418
+ const inner = this.lateStatementReplacements.get(original);
1419
+ this.lateStatementReplacements.delete(original);
1420
+ this.needsDeclare = saveNeedsDeclare;
1421
+ return this.factory.updateModuleDeclaration(input, modifiers, keyword, input.name, inner);
1422
+ }
1423
+ this.needsDeclare = saveNeedsDeclare;
1424
+ return this.factory.updateModuleDeclaration(input, modifiers, keyword, input.name, undefined);
1425
+ }
1426
+
1427
+ private stripExportModifiersOfList(list: NodeList): NodeList {
1428
+ const nodes: Node[] = [];
1429
+ let changed = false;
1430
+ for (const statement of list.nodes) {
1431
+ const stripped = this.stripExportModifiers(statement);
1432
+ if (stripped !== statement) changed = true;
1433
+ nodes.push(stripped);
1434
+ }
1435
+ return changed ? new NodeList(list.pos, list.end, nodes) : list;
1436
+ }
1437
+
1438
+ private stripExportModifiers(statement: Node): Node {
1439
+ const parseNode = this.context.parseNode(statement);
1440
+ // `export import` stays: imports aren't implicitly exported. So does `export default`.
1441
+ if (
1442
+ statement.kind === SyntaxKind.ImportEqualsDeclaration ||
1443
+ (parseNode !== undefined && this.resolver.getEffectiveDeclarationFlags(parseNode, ModifierFlags.Default) !== 0) ||
1444
+ !canHaveModifiers(statement)
1445
+ )
1446
+ return statement;
1447
+ const flags = getCombinedModifierFlags(statement);
1448
+ if ((flags & ModifierFlags.Export) === 0) return statement;
1449
+ return this.replaceModifiers(statement, this.createModifiers(flags & (ModifierFlags.All ^ ModifierFlags.Export)));
1450
+ }
1451
+
1452
+ /** `node` with other modifiers; for statements that can be exported. */
1453
+ private replaceModifiers(node: Node, modifiers: ModifierList | undefined): Node {
1454
+ if (node === undefined) return node;
1455
+ const factory = this.factory;
1456
+ if (node instanceof VariableStatement)
1457
+ return factory.updateVariableStatement(node, modifiers, node.declarationList);
1458
+ if (node instanceof FunctionDeclaration)
1459
+ return factory.updateFunctionDeclaration(
1460
+ node,
1461
+ modifiers,
1462
+ node.asteriskToken,
1463
+ node.name,
1464
+ node.typeParameters,
1465
+ node.parameters,
1466
+ node.type,
1467
+ node.fullSignature,
1468
+ node.body,
1469
+ );
1470
+ if (node instanceof ClassDeclaration)
1471
+ return factory.updateClassDeclaration(
1472
+ node,
1473
+ modifiers,
1474
+ node.name,
1475
+ node.typeParameters,
1476
+ node.heritageClauses,
1477
+ node.members,
1478
+ );
1479
+ if (node instanceof InterfaceDeclaration)
1480
+ return factory.updateInterfaceDeclaration(
1481
+ node,
1482
+ modifiers,
1483
+ node.name,
1484
+ node.typeParameters,
1485
+ node.heritageClauses,
1486
+ node.members,
1487
+ );
1488
+ if (node instanceof TypeAliasDeclaration)
1489
+ return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
1490
+ if (node instanceof EnumDeclaration) return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
1491
+ if (node instanceof ModuleDeclaration)
1492
+ return factory.updateModuleDeclaration(node, modifiers, node.keyword, node.name, node.body);
1493
+ if (node instanceof ImportDeclaration)
1494
+ return factory.updateImportDeclaration(node, modifiers, node.importClause, node.moduleSpecifier, node.attributes);
1495
+ if (node instanceof ExportDeclaration)
1496
+ return factory.updateExportDeclaration(
1497
+ node,
1498
+ modifiers,
1499
+ node.isTypeOnly,
1500
+ node.exportClause,
1501
+ node.moduleSpecifier,
1502
+ node.attributes,
1503
+ );
1504
+ if (node instanceof ExportAssignment)
1505
+ return factory.updateExportAssignment(node, modifiers, node.isExportEquals, node.type, node.expression);
1506
+ return node;
1507
+ }
1508
+
1509
+ /** Class members: parameter properties, a `#private` marker and the visited members. */
1510
+ /** The members of a class declaration or expression. */
1511
+ private buildClassMembers(classNode: Node, extraMembers: Node[]): NodeList {
1512
+ const classMembers = getMembers(classNode)!;
1513
+ const tracker = this.tracker;
1514
+ const parameterProperties: Node[] = [];
1515
+ const constructor = getFirstConstructorWithBody(classMembers);
1516
+ if (constructor !== undefined) {
1517
+ const oldContext = tracker.diagnosticContext;
1518
+ for (const parameter of constructor.parameters.nodes) {
1519
+ if (!(parameter instanceof ParameterDeclaration)) continue;
1520
+ if (
1521
+ !hasSyntacticModifier(parameter, ModifierFlags.ParameterPropertyModifier) ||
1522
+ this.shouldStripInternal(parameter)
1523
+ )
1524
+ continue;
1525
+ tracker.diagnosticContext = declarationContext(parameter);
1526
+ if (parameter.name instanceof Identifier) {
1527
+ const property = this.factory.created(
1528
+ new PropertyDeclaration(
1529
+ this.ensureModifiers(parameter),
1530
+ parameter.name,
1531
+ parameter.questionToken,
1532
+ this.ensureType(parameter, false),
1533
+ this.ensureNoInitializer(parameter),
1534
+ ),
1535
+ );
1536
+ this.context.assignCommentRange(property, parameter);
1537
+ parameterProperties.push(property);
1538
+ } else if (parameter.name instanceof BindingPattern)
1539
+ // A binding pattern is an error, but written as properties anyway.
1540
+ this.walkBindingPattern(parameter.name, parameter, parameterProperties);
1541
+ }
1542
+ tracker.diagnosticContext = oldContext;
1543
+ }
1544
+ const members: Node[] = [];
1545
+ // A class with private names gets a `#private` member to keep it nominal.
1546
+ for (const member of classMembers.nodes) {
1547
+ const name = getName(member);
1548
+ if (name instanceof PrivateIdentifier) {
1549
+ members.push(
1550
+ this.factory.created(
1551
+ new PropertyDeclaration(
1552
+ undefined,
1553
+ this.factory.created(new PrivateIdentifier('#private')),
1554
+ undefined,
1555
+ undefined,
1556
+ undefined,
1557
+ ),
1558
+ ),
1559
+ );
1560
+ break;
1561
+ }
1562
+ }
1563
+ const lateIndexes = this.resolver.createLateBoundIndexSignatures(
1564
+ this.context,
1565
+ classNode,
1566
+ this.enclosingDeclaration,
1567
+ NodeBuilderFlags.DeclarationEmit,
1568
+ tracker,
1569
+ );
1570
+ for (const index of lateIndexes) members.push(index);
1571
+ for (const property of parameterProperties) members.push(property);
1572
+ for (const member of extraMembers) members.push(member);
1573
+ const visited = this.visitNodes(classMembers);
1574
+ if (visited !== undefined) for (const member of visited.nodes) members.push(member);
1575
+ return this.factory.createNodeList(members);
1576
+ }
1577
+
1578
+ private walkBindingPattern(pattern: BindingPattern, parameter: ParameterDeclaration, result: Node[]): boolean {
1579
+ for (const element of pattern.elements.nodes) {
1580
+ if (!(element instanceof BindingElement) || element.name === undefined) continue;
1581
+ if (element.name instanceof BindingPattern) {
1582
+ this.walkBindingPattern(element.name, parameter, result);
1583
+ continue;
1584
+ }
1585
+ result.push(
1586
+ this.factory.created(
1587
+ new PropertyDeclaration(
1588
+ this.ensureModifiers(parameter),
1589
+ element.name,
1590
+ undefined,
1591
+ this.ensureType(element, false),
1592
+ undefined,
1593
+ ),
1594
+ ),
1595
+ );
1596
+ }
1597
+ return true;
1598
+ }
1599
+
1600
+ private transformClassDeclaration(input: ClassDeclaration): Node {
1601
+ const previousEnclosingDeclaration = this.enclosingDeclaration;
1602
+ this.enclosingDeclaration = defined(input);
1603
+ const tracker = this.tracker;
1604
+ tracker.errorNameNode = input.name;
1605
+ tracker.pushErrorFallbackNode(input);
1606
+ const modifiers = this.ensureModifiers(input);
1607
+ const typeParameters = this.ensureTypeParams(input, input.typeParameters);
1608
+ const extraMembers = isInJSFile(input) ? this.collectThisPropertyAssignments(input) : [];
1609
+ const members = this.buildClassMembers(input, extraMembers);
1610
+ const extendsClause = getClassExtendsHeritageElement(input);
1611
+ let result: Node;
1612
+ if (
1613
+ extendsClause !== undefined &&
1614
+ !isEntityNameExpression(extendsClause.expression, false) &&
1615
+ extendsClause.expression.kind !== SyntaxKind.NullKeyword
1616
+ ) {
1617
+ // `class C extends f() {}` becomes `declare const C_base: T; class C extends C_base {}`.
1618
+ tracker.reportInferenceFallback(extendsClause.expression);
1619
+ const oldId =
1620
+ input.name !== undefined && nodeIsPresent(input.name) && input.name.text.length > 0
1621
+ ? input.name.text
1622
+ : 'default';
1623
+ const newId = this.factory.createUniqueName(oldId + '_base', GeneratedIdentifierFlags.Optimistic);
1624
+ tracker.diagnosticContext = new DiagnosticContext(
1625
+ DiagnosticContextKind.ExtendsExpression,
1626
+ extendsClause,
1627
+ input.name,
1628
+ );
1629
+ const declaration = this.factory.createVariableDeclaration(
1630
+ newId,
1631
+ undefined,
1632
+ this.resolver.createTypeOfExpression(
1633
+ this.context,
1634
+ extendsClause.expression,
1635
+ input,
1636
+ NodeBuilderFlags.DeclarationEmit,
1637
+ tracker,
1638
+ ) ?? this.keyword(SyntaxKind.AnyKeyword),
1639
+ undefined,
1640
+ );
1641
+ const statement = this.factory.createVariableStatement(
1642
+ this.needsDeclare
1643
+ ? this.factory.createModifierList([this.factory.createToken(SyntaxKind.DeclareKeyword)])
1644
+ : undefined,
1645
+ this.factory.createVariableDeclarationList(this.factory.createNodeList([declaration]), NodeFlags.Const),
1646
+ );
1647
+ const clause = extendsClause.parent as HeritageClause;
1648
+ const heritageClause = this.factory.updateHeritageClause(
1649
+ clause,
1650
+ clause.token,
1651
+ this.factory.createNodeList([
1652
+ defined(
1653
+ this.factory.updateExpressionWithTypeArguments(
1654
+ extendsClause,
1655
+ newId,
1656
+ this.visitNodes(extendsClause.typeArguments),
1657
+ ),
1658
+ ),
1659
+ ]),
1660
+ );
1661
+ const heritageClauses: Node[] = [defined(heritageClause)];
1662
+ // The rest are `implements` clauses.
1663
+ const retained = this.visitNodes(input.heritageClauses);
1664
+ if (retained !== undefined) for (const other of retained.nodes) heritageClauses.push(other);
1665
+ result = this.factory.createSyntaxList([
1666
+ statement,
1667
+ defined(
1668
+ this.factory.updateClassDeclaration(
1669
+ input,
1670
+ modifiers,
1671
+ input.name,
1672
+ typeParameters,
1673
+ this.factory.createNodeList(heritageClauses),
1674
+ members,
1675
+ ),
1676
+ ),
1677
+ ]);
1678
+ } else
1679
+ result = defined(
1680
+ this.factory.updateClassDeclaration(
1681
+ input,
1682
+ modifiers,
1683
+ input.name,
1684
+ typeParameters,
1685
+ this.visitNodes(input.heritageClauses),
1686
+ members,
1687
+ ),
1688
+ );
1689
+ tracker.popErrorFallbackNode();
1690
+ this.enclosingDeclaration = previousEnclosingDeclaration;
1691
+ return result;
1692
+ }
1693
+
1694
+ private transformVariableStatement(input: VariableStatement): Node | undefined {
1695
+ const declarations = input.declarationList.declarations.nodes;
1696
+ let visible = false;
1697
+ for (const declaration of declarations)
1698
+ if (this.getBindingNameVisible(declaration)) {
1699
+ visible = true;
1700
+ break;
1701
+ }
1702
+ if (!visible) return undefined;
1703
+ let normal = declarations;
1704
+ const imports: Node[] = [];
1705
+ const file = this.tracker.currentSourceFile;
1706
+ if (file !== undefined && file.commonJSModuleIndicator !== undefined) {
1707
+ // `const x = require("m")` declarations become imports.
1708
+ normal = [];
1709
+ for (const declaration of declarations) {
1710
+ if (isVariableDeclarationInitializedToRequire(declaration)) {
1711
+ const visited = this.visit(declaration);
1712
+ if (visited !== undefined) imports.push(visited);
1713
+ } else normal.push(declaration);
1714
+ }
1715
+ }
1716
+ const nodes = this.visitArray(normal);
1717
+ if (nodes.length === 0) return imports.length > 0 ? this.factory.createSyntaxList(imports) : undefined;
1718
+ const list = this.factory.createNodeList(nodes);
1719
+ const modifiers = this.ensureModifiers(input);
1720
+ const declarationList = input.declarationList;
1721
+ let updatedList: VariableDeclarationList;
1722
+ const blockScope = getCombinedNodeFlags(declarationList) & NodeFlags.BlockScoped;
1723
+ if (blockScope === NodeFlags.Using || blockScope === NodeFlags.AwaitUsing) {
1724
+ // `using` declarations are written as `const`.
1725
+ updatedList = this.factory.createVariableDeclarationList(list, NodeFlags.Const);
1726
+ this.context.setOriginal(updatedList, declarationList);
1727
+ this.context.setCommentRange(updatedList, declarationList.pos, declarationList.end);
1728
+ updatedList.pos = declarationList.pos;
1729
+ updatedList.end = declarationList.end;
1730
+ } else updatedList = this.factory.updateVariableDeclarationList(declarationList, list, declarationList.flags);
1731
+ const result = this.factory.updateVariableStatement(input, modifiers, updatedList);
1732
+ if (imports.length === 0) return result;
1733
+ imports.push(defined(result));
1734
+ return this.factory.createSyntaxList(imports);
1735
+ }
1736
+
1737
+ private transformEnumDeclaration(input: EnumDeclaration): Node {
1738
+ const members: Node[] = [];
1739
+ for (const member of input.members.nodes) {
1740
+ if (member === undefined || !(member instanceof EnumMember) || this.shouldStripInternal(member)) continue;
1741
+ // Initializers are rewritten to their constant values.
1742
+ const value = this.resolver.getEnumMemberValue(member);
1743
+ if (
1744
+ this.tracker.isolatedDeclarations &&
1745
+ member.initializer !== undefined &&
1746
+ value.hasExternalReferences &&
1747
+ member.name.kind !== SyntaxKind.ComputedPropertyName
1748
+ )
1749
+ this.tracker.addDiagnostic(
1750
+ createDiagnosticForNode(
1751
+ member,
1752
+ Diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations,
1753
+ [],
1754
+ ),
1755
+ );
1756
+ let initializer: Node | undefined = undefined;
1757
+ if (value.kind === ConstantKind.Number) initializer = this.createNumber(value.number);
1758
+ else if (value.kind === ConstantKind.String)
1759
+ initializer = this.factory.createStringLiteral(value.string, TokenFlags.None);
1760
+ const result = defined(this.factory.updateEnumMember(member, member.name, initializer));
1761
+ this.context.assignCommentRange(result, member);
1762
+ members.push(result);
1763
+ }
1764
+ return this.factory.updateEnumDeclaration(
1765
+ input,
1766
+ this.ensureModifiers(input),
1767
+ input.name,
1768
+ this.factory.createNodeList(members),
1769
+ );
1770
+ }
1771
+
1772
+ /** A number as an expression: a literal, `-literal`, `Infinity`, `-Infinity` or `NaN`. */
1773
+ createNumber(value: number): Node {
1774
+ const factory = this.factory;
1775
+ if (value !== value) return factory.createIdentifier('NaN');
1776
+ if (value === Infinity) return factory.createIdentifier('Infinity');
1777
+ if (value === -Infinity)
1778
+ return factory.created(new PrefixUnaryExpression(SyntaxKind.MinusToken, factory.createIdentifier('Infinity')));
1779
+ if (value < 0 || (value === 0 && 1 / value < 0))
1780
+ return factory.created(
1781
+ new PrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(String(-value))),
1782
+ );
1783
+ return factory.createNumericLiteral(String(value));
1784
+ }
1785
+
1786
+ // JavaScript and assigned properties
1787
+
1788
+ /** `const x = require("m")` as `import x = require("m")`, `const { a } = require("m")` as `import { a } from "m"`. */
1789
+ private transformCjsRequireVariableDeclaration(input: VariableDeclaration): Node | undefined {
1790
+ const call = skipParenthesesOnly(input.initializer!);
1791
+ const specifier = this.rewriteModuleSpecifier(input, getArguments(call)!.nodes[0])!;
1792
+ const name = input.name;
1793
+ if (name instanceof Identifier)
1794
+ return this.factory.created(
1795
+ new ImportEqualsDeclaration(
1796
+ undefined,
1797
+ false,
1798
+ name,
1799
+ this.factory.created(new ExternalModuleReference(specifier)),
1800
+ ),
1801
+ );
1802
+ if (!(name instanceof BindingPattern) || name.kind === SyntaxKind.ArrayBindingPattern) return undefined;
1803
+ const specifiers: Node[] = [];
1804
+ for (const element of name.elements.nodes) {
1805
+ // Nested destructuring is skipped.
1806
+ if (!(element instanceof BindingElement) || !(element.name instanceof Identifier)) continue;
1807
+ specifiers.push(this.factory.created(new ImportSpecifier(false, element.propertyName, element.name)));
1808
+ }
1809
+ const clause = this.factory.created(
1810
+ new ImportClause(
1811
+ undefined,
1812
+ undefined,
1813
+ this.factory.created(new NamedImports(this.factory.createNodeList(specifiers))),
1814
+ ),
1815
+ );
1816
+ return this.factory.created(
1817
+ new ImportDeclaration(SyntaxKind.ImportDeclaration, undefined, clause, specifier, undefined),
1818
+ );
1819
+ }
1820
+
1821
+ /** Finds `module.exports =` assignments anywhere in the file. */
1822
+ visitModuleExportsAssignment(node: Node): boolean {
1823
+ const file = this.tracker.currentSourceFile!;
1824
+ if (
1825
+ file.commonJSModuleIndicator === undefined ||
1826
+ getAssignmentDeclarationKind(node) !== JSDeclarationKind.ModuleExports
1827
+ )
1828
+ return false;
1829
+ const scope = this.enterDiagnosticContext(node);
1830
+ const result = this.transformExportAssignment(node.parent!, node, (node as BinaryExpression).right, true);
1831
+ this.exitDiagnosticContext(scope);
1832
+ if (result === undefined) return false;
1833
+ this.cjsExportAssignment = result;
1834
+ this.resultHasScopeMarker = true;
1835
+ this.resultHasExternalModuleIndicator = true;
1836
+ return true;
1837
+ }
1838
+
1839
+ /** Finds assigned properties (`f.x = 1`) and CommonJS exports (`exports.x = 1`) anywhere in the file. */
1840
+ visitNestedExpression(node: Node): boolean {
1841
+ if (node === undefined) return false;
1842
+ const kind = getAssignmentDeclarationKind(node);
1843
+ if (kind === JSDeclarationKind.None) return false;
1844
+ const scope = this.enterDiagnosticContext(node);
1845
+ const file = this.tracker.currentSourceFile!;
1846
+ switch (kind) {
1847
+ case JSDeclarationKind.Property:
1848
+ if (node instanceof BinaryExpression) this.transformExpandoAssignment(node);
1849
+ break;
1850
+ case JSDeclarationKind.ExportsProperty:
1851
+ if (file.commonJSModuleIndicator !== undefined) {
1852
+ const name = getElementOrPropertyAccessName((node as BinaryExpression).left);
1853
+ if (name !== undefined) {
1854
+ const result = this.transformCommonJSExport(node, this.getNameExpressionPreferringIdentifier(name));
1855
+ if (result !== undefined) this.cjsExportMembers.push(result);
1856
+ }
1857
+ }
1858
+ break;
1859
+ case JSDeclarationKind.ObjectDefinePropertyExports:
1860
+ if (file.commonJSModuleIndicator !== undefined) {
1861
+ const result = this.transformCommonJSExport(
1862
+ node,
1863
+ this.getNameExpressionPreferringIdentifier(getArguments(node)!.nodes[1]),
1864
+ );
1865
+ if (result !== undefined) this.cjsExportMembers.push(result);
1866
+ }
1867
+ break;
1868
+ }
1869
+ this.exitDiagnosticContext(scope);
1870
+ return true;
1871
+ }
1872
+
1873
+ /** A property name as an identifier when it can be one; keywords other than `default` stay strings. */
1874
+ private getNameExpressionPreferringIdentifier(name: Node): Node {
1875
+ let result = name;
1876
+ if (name instanceof NumericLiteral) result = this.factory.createStringLiteral(name.text, TokenFlags.None);
1877
+ if (
1878
+ (result.kind === SyntaxKind.StringLiteral || result.kind === SyntaxKind.NoSubstitutionTemplateLiteral) &&
1879
+ isIdentifierText(getText(result))
1880
+ ) {
1881
+ const text = getText(result);
1882
+ const keyword = identifierToKeywordKind(text);
1883
+ if (
1884
+ keyword === SyntaxKind.Unknown ||
1885
+ keyword === SyntaxKind.Identifier ||
1886
+ keyword === SyntaxKind.DefaultKeyword
1887
+ ) {
1888
+ // A parse tree node, so names it uses are resolved where it's written.
1889
+ const identifier = new Identifier(text);
1890
+ identifier.parent = name.parent;
1891
+ return identifier;
1892
+ }
1893
+ }
1894
+ return result;
1895
+ }
1896
+
1897
+ private transformCommonJSExport(input: Node, name: Node): Node | undefined {
1898
+ const result = this.transformCommonJSExportWorker(input, name);
1899
+ return result === undefined ? undefined : this.wrapInCJSExportNamespace(result);
1900
+ }
1901
+
1902
+ private transformCommonJSExportWorker(input: Node, name: Node): Node | undefined {
1903
+ if (input === undefined) return undefined;
1904
+ const nameText = name.kind === SyntaxKind.Identifier || name.kind === SyntaxKind.StringLiteral ? getText(name) : '';
1905
+ if (nameText !== '' && this.witnessedCjsExports.has(nameText)) return undefined;
1906
+ this.witnessedCjsExports.add(nameText);
1907
+ this.resultHasExternalModuleIndicator = true;
1908
+ this.resultHasScopeMarker = true;
1909
+ const tracker = this.tracker;
1910
+ // At the top level, `exports.x = y` is written as `export { y as x }`.
1911
+ const statement = input.parent;
1912
+ if (
1913
+ isCommonJSAliasExport(input) &&
1914
+ statement !== undefined &&
1915
+ statement.kind === SyntaxKind.ExpressionStatement &&
1916
+ statement.parent !== undefined &&
1917
+ statement.parent.kind === SyntaxKind.SourceFile
1918
+ )
1919
+ return this.transformBinaryExpressionToExportDeclaration(input as BinaryExpression, name);
1920
+ if (input instanceof BinaryExpression) {
1921
+ const right = skipParenthesesOnly(input.right);
1922
+ if (right instanceof ClassExpression) return this.transformCommonJSClassExport(input, right, name);
1923
+ }
1924
+ if (name instanceof Identifier) {
1925
+ if (name.text === 'default') {
1926
+ // `declare const _default: T; export default _default;`
1927
+ const newId = this.factory.createUniqueName('_default', GeneratedIdentifierFlags.Optimistic);
1928
+ tracker.diagnosticContext = new DiagnosticContext(DiagnosticContextKind.DefaultExport, input, undefined);
1929
+ tracker.pushErrorFallbackNode(input);
1930
+ const declaration = this.factory.createVariableDeclaration(
1931
+ newId,
1932
+ undefined,
1933
+ this.ensureType(input, false),
1934
+ undefined,
1935
+ );
1936
+ tracker.popErrorFallbackNode();
1937
+ const variable = this.createConstStatement(declaration);
1938
+ const assignment = this.factory.created(new ExportAssignment(getModifiers(input), false, undefined, newId));
1939
+ this.context.assignCommentRange(variable, input);
1940
+ this.context.addEmitFlags(assignment, EmitFlags.NoComments);
1941
+ return this.factory.createSyntaxList([variable, assignment]);
1942
+ }
1943
+ const referenced = this.resolver.getReferencedValueDeclaration(name);
1944
+ // Inlined as `export var x: T` unless the name refers to something else.
1945
+ if (referenced === input || referenced === undefined) {
1946
+ tracker.pushErrorFallbackNode(input);
1947
+ const declaration = this.factory.createVariableDeclaration(
1948
+ name,
1949
+ undefined,
1950
+ this.ensureType(input, false),
1951
+ undefined,
1952
+ );
1953
+ tracker.popErrorFallbackNode();
1954
+ const modifiers: Node[] = [this.factory.createToken(SyntaxKind.ExportKeyword)];
1955
+ if (this.needsDeclare) modifiers.push(this.factory.createToken(SyntaxKind.DeclareKeyword));
1956
+ return this.factory.createVariableStatement(
1957
+ this.factory.createModifierList(modifiers),
1958
+ this.factory.createVariableDeclarationList(this.factory.createNodeList([declaration]), NodeFlags.None),
1959
+ );
1960
+ }
1961
+ }
1962
+ // `declare const _exported: T; export { _exported as "name" };`
1963
+ const newId = this.factory.createUniqueName('_exported', GeneratedIdentifierFlags.Optimistic);
1964
+ tracker.diagnosticContext = new DiagnosticContext(DiagnosticContextKind.DefaultExport, input, undefined);
1965
+ tracker.pushErrorFallbackNode(input);
1966
+ const declaration = this.factory.createVariableDeclaration(
1967
+ newId,
1968
+ undefined,
1969
+ this.ensureType(input, false),
1970
+ undefined,
1971
+ );
1972
+ tracker.popErrorFallbackNode();
1973
+ const variable = this.createConstStatement(declaration);
1974
+ const exportDeclaration = this.createExportDeclaration(newId, name);
1975
+ this.context.assignCommentRange(variable, input);
1976
+ this.context.addEmitFlags(exportDeclaration, EmitFlags.NoComments);
1977
+ return this.factory.createSyntaxList([variable, exportDeclaration]);
1978
+ }
1979
+
1980
+ /** `exports.K = class K {}` as a class declaration, in a namespace if its name differs or is used inside. */
1981
+ private transformCommonJSClassExport(input: BinaryExpression, right: ClassExpression, name: Node): Node {
1982
+ const factory = this.factory;
1983
+ const tracker = this.tracker;
1984
+ const classExpressionName = right.name;
1985
+ if (classExpressionName !== undefined && classExpressionName.text.length > 0) {
1986
+ // Watch for the class naming itself in its members' types.
1987
+ tracker.watchedClassSymbol = right.symbol;
1988
+ tracker.classSymbolTracked = false;
1989
+ const className = factory.createIdentifier(classExpressionName.text);
1990
+ const classDeclaration = this.transformClassExpressionToDeclaration(
1991
+ right,
1992
+ className,
1993
+ factory.createModifierList([factory.createToken(SyntaxKind.ExportKeyword)]),
1994
+ );
1995
+ this.context.assignCommentRange(classDeclaration, input);
1996
+ const namesDiffer = !(name instanceof Identifier) || classExpressionName.text !== name.text;
1997
+ const needsIsolation = namesDiffer || tracker.classSymbolTracked;
1998
+ tracker.watchedClassSymbol = undefined;
1999
+ tracker.classSymbolTracked = false;
2000
+ if (needsIsolation) {
2001
+ const namespaceName = factory.createUniqueName('_ns', GeneratedIdentifierFlags.Optimistic);
2002
+ const namespace = factory.created(
2003
+ new ModuleDeclaration(
2004
+ this.declareModifiers(),
2005
+ SyntaxKind.NamespaceKeyword,
2006
+ namespaceName,
2007
+ factory.created(new ModuleBlock(factory.createNodeList([classDeclaration]))),
2008
+ ),
2009
+ );
2010
+ const aliasBase =
2011
+ name instanceof Identifier && isIdentifierText('_' + name.text) ? '_' + name.text : '_exported';
2012
+ const alias = factory.createUniqueName(aliasBase, GeneratedIdentifierFlags.Optimistic);
2013
+ const importEquals = factory.created(
2014
+ new ImportEqualsDeclaration(
2015
+ undefined,
2016
+ false,
2017
+ alias,
2018
+ factory.created(new QualifiedName(namespaceName, className)),
2019
+ ),
2020
+ );
2021
+ const exportDeclaration = this.createExportDeclaration(alias, name);
2022
+ this.context.addEmitFlags(exportDeclaration, EmitFlags.NoComments);
2023
+ return factory.createSyntaxList([namespace, importEquals, exportDeclaration]);
2024
+ }
2025
+ const modifiers: Node[] = [factory.createToken(SyntaxKind.ExportKeyword)];
2026
+ if (this.needsDeclare) modifiers.push(factory.createToken(SyntaxKind.DeclareKeyword));
2027
+ return this.replaceModifiers(classDeclaration, factory.createModifierList(modifiers));
2028
+ }
2029
+ const modifiers: Node[] = [factory.createToken(SyntaxKind.ExportKeyword)];
2030
+ if (this.needsDeclare) modifiers.push(factory.createToken(SyntaxKind.DeclareKeyword));
2031
+ const className =
2032
+ name !== undefined && name instanceof Identifier
2033
+ ? name
2034
+ : factory.createUniqueName('_class', GeneratedIdentifierFlags.Optimistic);
2035
+ const classDeclaration = this.transformClassExpressionToDeclaration(
2036
+ right,
2037
+ className,
2038
+ factory.createModifierList(modifiers),
2039
+ );
2040
+ this.context.assignCommentRange(classDeclaration, input);
2041
+ if (name instanceof Identifier) return classDeclaration;
2042
+ // A name that isn't an identifier is exported by a specifier.
2043
+ const exportDeclaration = this.createExportDeclaration(className, name);
2044
+ this.context.addEmitFlags(exportDeclaration, EmitFlags.NoComments);
2045
+ return factory.createSyntaxList([classDeclaration, exportDeclaration]);
2046
+ }
2047
+
2048
+ private createExportDeclaration(local: Node | undefined, name: Node): ExportDeclaration {
2049
+ const factory = this.factory;
2050
+ return factory.created(
2051
+ new ExportDeclaration(
2052
+ undefined,
2053
+ false,
2054
+ factory.created(
2055
+ new NamedExports(factory.createNodeList([factory.created(new ExportSpecifier(false, local, name))])),
2056
+ ),
2057
+ undefined,
2058
+ undefined,
2059
+ ),
2060
+ );
2061
+ }
2062
+
2063
+ /** `exports.x = y` and `f.x = y` as `export { y as x }`. */
2064
+ private transformBinaryExpressionToExportDeclaration(input: BinaryExpression, name: Node): Node {
2065
+ let propertyName: Node | undefined = input.right;
2066
+ // Keeps the declaration the name refers to.
2067
+ this.tracker.handleSymbolAccessibilityError(
2068
+ this.resolver.isEntityNameVisible(propertyName, this.enclosingDeclaration),
2069
+ );
2070
+ if (name instanceof Identifier && propertyName instanceof Identifier && propertyName.text === name.text)
2071
+ propertyName = undefined;
2072
+ return this.createExportDeclaration(propertyName, name);
2073
+ }
2074
+
2075
+ /** CommonJS exports of a file with `module.exports =` are members of a namespace of its name. */
2076
+ private wrapInCJSExportNamespace(content: Node): Node {
2077
+ const name = this.cjsExportAssignmentName;
2078
+ if (name === undefined) return content;
2079
+ const members = content instanceof SyntaxList ? content.children : [content];
2080
+ const stripped: Node[] = [];
2081
+ for (const member of members) stripped.push(this.stripDeclareModifier(member));
2082
+ return this.factory.created(
2083
+ new ModuleDeclaration(
2084
+ this.declareModifiers(),
2085
+ SyntaxKind.NamespaceKeyword,
2086
+ name,
2087
+ this.factory.created(new ModuleBlock(this.factory.createNodeList(stripped))),
2088
+ ),
2089
+ );
2090
+ }
2091
+
2092
+ private stripDeclareModifier(node: Node): Node {
2093
+ const modifiers = getModifiers(node);
2094
+ if (modifiers === undefined || (modifiers.modifierFlags & ModifierFlags.Ambient) === 0) return node;
2095
+ const kept: Node[] = [];
2096
+ for (const modifier of modifiers.nodes) if (modifier.kind !== SyntaxKind.DeclareKeyword) kept.push(modifier);
2097
+ return this.replaceModifiers(node, this.factory.createModifierList(kept));
2098
+ }
2099
+
2100
+ /** Writes `f.x = 1` as a namespace member of `f`, kept with `f` if it's emitted. */
2101
+ private transformExpandoAssignment(node: BinaryExpression): boolean {
2102
+ const symbol = node.symbol;
2103
+ if (symbol === undefined || (symbol.flags & SymbolFlags.Assignment) === 0) return false;
2104
+ const left = node.left;
2105
+ const namespace = getLeftmostAccessExpression(left);
2106
+ if (!(namespace instanceof Identifier)) return false;
2107
+ const declaration = this.resolver.getReferencedValueDeclaration(namespace);
2108
+ if (declaration === undefined || this.shouldStripInternal(declaration)) return false;
2109
+ if (declaration instanceof VariableDeclaration && declaration.type !== undefined) return false;
2110
+ if (declaration instanceof FunctionDeclaration && declaration.fullSignature !== undefined) return false;
2111
+ // A variable gets a type instead, unless it's a function.
2112
+ if (
2113
+ declaration instanceof VariableDeclaration &&
2114
+ (declaration.initializer === undefined || !isFunctionLike(declaration.initializer))
2115
+ )
2116
+ return false;
2117
+ const host = getSymbol(declaration);
2118
+ if (host === undefined) return false;
2119
+ const name = this.factory.createIdentifier(namespace.text);
2120
+ const property = this.tryGetPropertyName(left);
2121
+ if (property === '' || !isIdentifierText(property)) return false;
2122
+ if (isDeclaration(declaration) && this.isDeclarationAndNotVisible(declaration)) return false;
2123
+ if (declaration instanceof FunctionDeclaration && !shouldEmitFunctionProperties(declaration)) return false;
2124
+ this.transformExpandoHost(name, declaration);
2125
+ const exportName = this.factory.createIdentifier(property);
2126
+ let localName = this.tryGetNameOfAssignedExpression(node);
2127
+ // The property's name works as the local name if it neither conflicts nor is a keyword.
2128
+ if (
2129
+ localName === undefined &&
2130
+ !this.resolver.isNameResolvable(this.enclosingDeclaration, property) &&
2131
+ !isNonContextualKeyword(stringToToken(property))
2132
+ )
2133
+ localName = exportName;
2134
+ if (localName === undefined || isNonContextualKeyword(stringToToken(localName.text)))
2135
+ localName = this.factory.createGeneratedNameForNode(node, GeneratedIdentifierFlags.None, '', '');
2136
+ const hostId = this.getExpandoHostId(declaration);
2137
+ const scope = this.enterDiagnosticContext(node);
2138
+ let members = this.expandoMembers.get(hostId);
2139
+ if (members === undefined) {
2140
+ members = [];
2141
+ this.expandoMembers.set(hostId, members);
2142
+ }
2143
+ if (node.right instanceof Identifier) {
2144
+ // Alias-like: `export { name }` or `export { name as alias }`.
2145
+ members.push(this.transformBinaryExpressionToExportDeclaration(node, exportName));
2146
+ this.exitDiagnosticContext(scope);
2147
+ return true;
2148
+ }
2149
+ let hasExport = false;
2150
+ for (const member of members) if (member.kind === SyntaxKind.ExportDeclaration) hasExport = true;
2151
+ const variable = this.factory.createVariableStatement(
2152
+ hasExport ? this.factory.createModifierList([this.factory.createToken(SyntaxKind.ExportKeyword)]) : undefined,
2153
+ this.factory.createVariableDeclarationList(
2154
+ this.factory.createNodeList([
2155
+ this.factory.createVariableDeclaration(localName, undefined, this.ensureType(node, false), undefined),
2156
+ ]),
2157
+ NodeFlags.None,
2158
+ ),
2159
+ );
2160
+ const statements: Node[] = [variable];
2161
+ const local = defined(localName) as Identifier;
2162
+ if (local.text !== exportName.text || this.context.hasAutoGenerateInfo(local))
2163
+ statements.push(this.createExportDeclaration(local, exportName));
2164
+ // Members stay exported after an `export {}` is added.
2165
+ if (statements.length > 1 && !hasExport)
2166
+ for (let i = 0; i < members.length; i++)
2167
+ members[i] = this.replaceModifiers(
2168
+ members[i],
2169
+ this.createModifiers(ModifierFlags.Export | getCombinedModifierFlags(members[i])),
2170
+ );
2171
+ for (const statement of statements) members.push(statement);
2172
+ this.exitDiagnosticContext(scope);
2173
+ return true;
2174
+ }
2175
+
2176
+ private tryGetPropertyName(node: Node): string {
2177
+ if (node instanceof ElementAccessExpression) return this.resolver.getElementAccessExpressionName(node);
2178
+ if (node instanceof PropertyAccessExpression && node.name instanceof Identifier) return node.name.text;
2179
+ return '';
2180
+ }
2181
+
2182
+ private getExpandoHostId(declaration: Node): Node {
2183
+ const root = declaration instanceof VariableDeclaration ? declaration.parent!.parent! : declaration;
2184
+ return this.context.mostOriginal(root);
2185
+ }
2186
+
2187
+ /** The function a property is assigned to, written as a declaration once. */
2188
+ private transformExpandoHost(name: Identifier, declaration: Node): boolean {
2189
+ if (name === undefined) return false;
2190
+ const root = declaration instanceof VariableDeclaration ? declaration.parent!.parent! : declaration;
2191
+ const id = this.getExpandoHostId(declaration);
2192
+ if (this.expandoHosts.has(id)) return false;
2193
+ const saveNeedsDeclare = this.needsDeclare;
2194
+ this.needsDeclare = true;
2195
+ let flags = this.ensureModifierFlags(root);
2196
+ this.needsDeclare = saveNeedsDeclare;
2197
+ const defaultExport = (flags & ModifierFlags.Export) !== 0 && (flags & ModifierFlags.Default) !== 0;
2198
+ if (defaultExport) flags = (flags | ModifierFlags.Ambient) & ~(ModifierFlags.Default | ModifierFlags.Export);
2199
+ const scope = this.enterDiagnosticContext(declaration);
2200
+ const modifiers = this.createModifiers(flags);
2201
+ const replacement: Node[] = [];
2202
+ if (declaration instanceof FunctionDeclaration)
2203
+ replacement.push(
2204
+ defined(
2205
+ this.factory.updateFunctionDeclaration(
2206
+ declaration,
2207
+ modifiers,
2208
+ declaration.asteriskToken,
2209
+ declaration.name,
2210
+ this.ensureTypeParams(declaration, declaration.typeParameters),
2211
+ this.updateParamList(declaration, declaration.parameters),
2212
+ this.ensureType(declaration, false),
2213
+ undefined,
2214
+ undefined,
2215
+ ),
2216
+ ),
2217
+ );
2218
+ else if (isFunctionValuedVariable(declaration)) {
2219
+ const fn = getInitializer(declaration)!;
2220
+ replacement.push(
2221
+ this.factory.created(
2222
+ new FunctionDeclaration(
2223
+ modifiers,
2224
+ asteriskOf(fn),
2225
+ this.factory.createIdentifier(name.text),
2226
+ this.ensureTypeParams(fn, getTypeParameters(fn)),
2227
+ this.updateParamList(fn, getParameters(fn)!),
2228
+ this.ensureType(fn, false),
2229
+ undefined,
2230
+ undefined,
2231
+ ),
2232
+ ),
2233
+ );
2234
+ } else {
2235
+ this.expandoHosts.set(id, this.transformTopLevelDeclaration(declaration));
2236
+ this.exitDiagnosticContext(scope);
2237
+ return true;
2238
+ }
2239
+ this.tracker.reportExpandoFunctionErrors(declaration);
2240
+ if (defaultExport) {
2241
+ if (declaration.parent !== undefined && declaration.parent.kind === SyntaxKind.SourceFile)
2242
+ this.resultHasExternalModuleIndicator = true;
2243
+ this.resultHasScopeMarker = true;
2244
+ replacement.push(this.factory.created(new ExportAssignment(undefined, false, undefined, name)));
2245
+ }
2246
+ this.expandoHosts.set(id, this.factory.createSyntaxList(replacement));
2247
+ if (this.lateStatementReplacements.has(id)) this.lateStatementReplacements.set(id, this.createFullExpandoBlock(id));
2248
+ this.exitDiagnosticContext(scope);
2249
+ return true;
2250
+ }
2251
+
2252
+ /** A function with its assigned properties as a namespace of the same name. */
2253
+ private createFullExpandoBlock(id: Node): Node | undefined {
2254
+ const host = this.expandoHosts.get(id);
2255
+ const addOns = this.expandoMembers.get(id);
2256
+ if (addOns === undefined || host === undefined) return host;
2257
+ let name: Node | undefined = undefined;
2258
+ let modifiers: ModifierList | undefined = undefined;
2259
+ const statements = host instanceof SyntaxList ? host.children : [host];
2260
+ for (const statement of statements) {
2261
+ const statementName = getName(statement);
2262
+ if (statementName === undefined) continue;
2263
+ name = this.factory.cloneNode(statementName, statementName.deepClone());
2264
+ const statementModifiers = getModifiers(statement);
2265
+ if (statementModifiers !== undefined)
2266
+ modifiers = this.factory.createModifierList(statementModifiers.nodes.slice());
2267
+ break;
2268
+ }
2269
+ if (name === undefined) return host;
2270
+ const result = statements.slice();
2271
+ result.push(
2272
+ this.factory.created(
2273
+ new ModuleDeclaration(
2274
+ modifiers,
2275
+ SyntaxKind.NamespaceKeyword,
2276
+ name,
2277
+ this.factory.created(new ModuleBlock(this.factory.createNodeList(addOns))),
2278
+ ),
2279
+ ),
2280
+ );
2281
+ return this.factory.createSyntaxList(result);
2282
+ }
2283
+
2284
+ /** The `this.x = …` members of a JavaScript class, as property declarations. */
2285
+ private collectThisPropertyAssignments(classNode: Node): Node[] {
2286
+ const members = getMembers(classNode)!.nodes;
2287
+ this.seenProperties.clear();
2288
+ for (const member of members) {
2289
+ const name = getName(member);
2290
+ if (name !== undefined) this.seenProperties.add(thisPropertyKey(name, member, isStatic(member)));
2291
+ }
2292
+ this.thisPropertyAssignments = [];
2293
+ const walker = new ThisPropertyWalker(this, classNode);
2294
+ for (const member of members) member.forEachChild(walker);
2295
+ const result = this.thisPropertyAssignments;
2296
+ this.thisPropertyAssignments = [];
2297
+ this.seenProperties.clear();
2298
+ return result;
2299
+ }
2300
+
2301
+ /** Collects a `this.x = …` assignment of a member of `classNode`. */
2302
+ visitThisPropertyAssignment(node: Node, classNode: Node): boolean {
2303
+ if (getAssignmentDeclarationKind(node) !== JSDeclarationKind.ThisProperty) return false;
2304
+ const container = getThisContainer(node, false, false);
2305
+ if (container.parent !== classNode) return false;
2306
+ const isStaticMember =
2307
+ hasSyntacticModifier(container, ModifierFlags.Static) ||
2308
+ container.kind === SyntaxKind.ClassStaticBlockDeclaration;
2309
+ const assignment = node as BinaryExpression;
2310
+ let name: Node | undefined = getElementOrPropertyAccessName(assignment.left);
2311
+ if (name === undefined) return false;
2312
+ const key = thisPropertyKey(name, node, isStaticMember);
2313
+ if (this.resolver.getReferencedMemberValueDeclaration(node) === undefined || this.seenProperties.has(key))
2314
+ return false;
2315
+ this.seenProperties.add(key);
2316
+ const heritage = getHeritageClauses(classNode);
2317
+ if (heritage !== undefined && heritage.nodes.length > 0 && !isClassExtendingNull(heritage)) {
2318
+ // A base class may provide the member; that needs types.
2319
+ this.tracker.reportInferenceFallback(classNode);
2320
+ if (this.resolver.isThisPropertyAssignmentDeclarationRedundant(node)) return false;
2321
+ }
2322
+ if (hasDynamicName(node)) return false;
2323
+ if (getTextOfPropertyName(name) === 'constructor') return false;
2324
+ if (name instanceof Identifier && !isIdentifierText(name.text))
2325
+ name = this.factory.createStringLiteralFromNode(name);
2326
+ const property = this.factory.created(
2327
+ new PropertyDeclaration(
2328
+ isStaticMember
2329
+ ? this.factory.createModifierList([this.factory.createToken(SyntaxKind.StaticKeyword)])
2330
+ : undefined,
2331
+ name,
2332
+ undefined,
2333
+ this.ensureType(node, false),
2334
+ undefined,
2335
+ ),
2336
+ );
2337
+ if (node.parent !== undefined && node.parent.kind === SyntaxKind.ExpressionStatement)
2338
+ this.context.assignCommentRange(property, node.parent);
2339
+ this.thisPropertyAssignments.push(property);
2340
+ return true;
2341
+ }
2342
+
2343
+ // Modifiers, types and parameters
2344
+
2345
+ private createModifiers(flags: ModifierFlags): ModifierList | undefined {
2346
+ const nodes: Node[] = [];
2347
+ for (const kind of modifierKindsInOrder)
2348
+ if ((flags & modifierToFlag(kind)) !== 0) nodes.push(this.factory.createToken((kind | 0) as SyntaxKind));
2349
+ return nodes.length === 0 ? undefined : this.factory.createModifierList(nodes);
2350
+ }
2351
+
2352
+ private ensureModifiers(node: Node): ModifierList | undefined {
2353
+ const parseNode = this.parseNode(node);
2354
+ const currentFlags = getCombinedModifierFlags(parseNode) & ModifierFlags.All;
2355
+ const newFlags = this.ensureModifierFlags(node);
2356
+ if (currentFlags === newFlags) {
2357
+ // Decorators are dropped.
2358
+ const modifiers = getModifiers(node);
2359
+ if (modifiers === undefined) return undefined;
2360
+ let reusable = true;
2361
+ for (const modifier of modifiers.nodes)
2362
+ if (isModifier(modifier) && (modifier.flags & NodeFlags.Reparsed) !== 0) {
2363
+ reusable = false;
2364
+ break;
2365
+ }
2366
+ if (reusable) {
2367
+ const kept: Node[] = [];
2368
+ for (const modifier of modifiers.nodes) if (isModifier(modifier)) kept.push(modifier);
2369
+ return this.factory.createModifierList(kept);
2370
+ }
2371
+ }
2372
+ return this.createModifiers(newFlags);
2373
+ }
2374
+
2375
+ private ensureModifierFlags(node: Node): ModifierFlags {
2376
+ // No `async` or `override` in declaration files, and `public` is implied.
2377
+ let mask = ModifierFlags.All ^ (ModifierFlags.Public | ModifierFlags.Async | ModifierFlags.Override);
2378
+ let additions =
2379
+ this.needsDeclare && node.kind !== SyntaxKind.InterfaceDeclaration ? ModifierFlags.Ambient : ModifierFlags.None;
2380
+ if (node.parent === undefined || node.parent.kind !== SyntaxKind.SourceFile) {
2381
+ mask ^= ModifierFlags.Ambient;
2382
+ additions = ModifierFlags.None;
2383
+ }
2384
+ if (isImplicitlyExportedJSDocDeclaration(node)) additions |= ModifierFlags.Export;
2385
+ return maskModifierFlags(node, mask, additions);
2386
+ }
2387
+
2388
+ private ensureTypeParams(node: Node, params: NodeList | undefined): NodeList | undefined {
2389
+ if (this.isPrivate(this.parseNode(node))) return undefined;
2390
+ const typeParameters = this.visitNodes(params);
2391
+ if (typeParameters !== undefined || getFullSignature(node) === undefined) return typeParameters;
2392
+ // A JSDoc `@type` signature declares the type parameters.
2393
+ const tracker = this.tracker;
2394
+ const oldErrorNameNode = tracker.errorNameNode;
2395
+ tracker.errorNameNode = getName(node);
2396
+ const oldContext = tracker.diagnosticContext;
2397
+ if (!this.suppressNewDiagnosticContexts && canProduceDiagnostics(node))
2398
+ tracker.diagnosticContext = declarationContext(node);
2399
+ const nodes = this.resolver.createTypeParametersOfSignatureDeclaration(
2400
+ this.context,
2401
+ node,
2402
+ this.enclosingDeclaration,
2403
+ NodeBuilderFlags.DeclarationEmit,
2404
+ tracker,
2405
+ );
2406
+ tracker.errorNameNode = oldErrorNameNode;
2407
+ if (!this.suppressNewDiagnosticContexts) tracker.diagnosticContext = oldContext;
2408
+ return nodes === undefined ? undefined : this.factory.createNodeList(nodes);
2409
+ }
2410
+
2411
+ private updateParamList(node: Node, params: NodeList): NodeList {
2412
+ if (this.isPrivate(this.parseNode(node)) || params.nodes.length === 0) return this.factory.createNodeList([]);
2413
+ const results: Node[] = [];
2414
+ for (const parameter of params.nodes) results.push(this.ensureParameterNode(parameter));
2415
+ return this.factory.createNodeList(results);
2416
+ }
2417
+
2418
+ private ensureParameterNode(node: Node): Node {
2419
+ if (node === undefined) return node;
2420
+ return node instanceof ParameterDeclaration ? this.ensureParameter(node) : node;
2421
+ }
2422
+
2423
+ private ensureParameter(p: ParameterDeclaration): Node {
2424
+ const tracker = this.tracker;
2425
+ const oldContext = tracker.diagnosticContext;
2426
+ if (!this.suppressNewDiagnosticContexts) tracker.diagnosticContext = declarationContext(p);
2427
+ let questionToken: Token | undefined = undefined;
2428
+ if (this.resolver.isOptionalParameter(p))
2429
+ questionToken = p.questionToken ?? this.factory.createToken(SyntaxKind.QuestionToken);
2430
+ const result = this.factory.updateParameterDeclaration(
2431
+ p,
2432
+ undefined,
2433
+ p.dotDotDotToken,
2434
+ this.visitBindingName(p.name),
2435
+ questionToken,
2436
+ this.ensureType(p, true),
2437
+ this.ensureNoInitializer(p),
2438
+ );
2439
+ tracker.diagnosticContext = oldContext;
2440
+ return result;
2441
+ }
2442
+
2443
+ private visitBindingName(node: Node): Node {
2444
+ if (node instanceof BindingPattern) {
2445
+ const elements: Node[] = [];
2446
+ let changed = false;
2447
+ for (const element of node.elements.nodes) {
2448
+ const visited = this.visitBindingName(element);
2449
+ if (visited !== element) changed = true;
2450
+ elements.push(visited);
2451
+ }
2452
+ return changed
2453
+ ? this.factory.updateBindingPattern(node, new NodeList(node.elements.pos, node.elements.end, elements))
2454
+ : node;
2455
+ }
2456
+ if (node instanceof BindingElement) {
2457
+ const propertyName = node.propertyName;
2458
+ if (propertyName instanceof ComputedPropertyName && isEntityNameExpression(propertyName.expression, false))
2459
+ this.checkEntityNameVisibility(propertyName.expression, this.enclosingDeclaration);
2460
+ return this.factory.updateBindingElement(
2461
+ node,
2462
+ node.dotDotDotToken,
2463
+ propertyName,
2464
+ node.name === undefined ? undefined : this.visitBindingName(node.name),
2465
+ undefined,
2466
+ );
2467
+ }
2468
+ return node;
2469
+ }
2470
+
2471
+ /** The type of a declaration: its annotation, or the resolver's type; `any` if neither. */
2472
+ private ensureType(node: Node, ignorePrivate: boolean): Node | undefined {
2473
+ // Private declarations have no types, except private parameter properties' parameters.
2474
+ if (!ignorePrivate && this.isPrivate(this.parseNode(node))) return undefined;
2475
+ // Literal constants are written with their initializer instead.
2476
+ if (this.shouldPrintWithInitializer(node)) return undefined;
2477
+ const type = getType(node);
2478
+ if (
2479
+ node.kind !== SyntaxKind.ExportAssignment &&
2480
+ node.kind !== SyntaxKind.BindingElement &&
2481
+ type !== undefined &&
2482
+ (node.kind !== SyntaxKind.Parameter ||
2483
+ !this.resolver.requiresAddingImplicitUndefined(node, this.enclosingDeclaration))
2484
+ ) {
2485
+ const file = this.tracker.currentSourceFile;
2486
+ if (file === undefined || !file.isJS()) return this.visitNode(type);
2487
+ // JSDoc types can need rewriting, which the resolver does.
2488
+ const rewritten = this.resolver.tryJSTypeNodeToTypeNode(
2489
+ this.context,
2490
+ type,
2491
+ this.enclosingDeclaration,
2492
+ this.nodeBuilderFlags(),
2493
+ this.tracker,
2494
+ );
2495
+ if (rewritten !== undefined) return rewritten;
2496
+ }
2497
+ const tracker = this.tracker;
2498
+ const oldErrorNameNode = tracker.errorNameNode;
2499
+ tracker.errorNameNode = getName(node);
2500
+ const oldContext = tracker.diagnosticContext;
2501
+ if (!this.suppressNewDiagnosticContexts && canProduceDiagnostics(node))
2502
+ tracker.diagnosticContext = declarationContext(node);
2503
+ let typeNode: Node | undefined = undefined;
2504
+ if (hasInferredType(node))
2505
+ typeNode = this.resolver.createTypeOfDeclaration(
2506
+ this.context,
2507
+ node,
2508
+ this.enclosingDeclaration,
2509
+ this.nodeBuilderFlags(),
2510
+ tracker,
2511
+ );
2512
+ else if (isFunctionLike(node))
2513
+ typeNode = this.resolver.createReturnTypeOfSignatureDeclaration(
2514
+ this.context,
2515
+ node,
2516
+ this.enclosingDeclaration,
2517
+ this.nodeBuilderFlags(),
2518
+ tracker,
2519
+ );
2520
+ tracker.errorNameNode = oldErrorNameNode;
2521
+ if (!this.suppressNewDiagnosticContexts) tracker.diagnosticContext = oldContext;
2522
+ return typeNode ?? this.keyword(SyntaxKind.AnyKeyword);
2523
+ }
2524
+
2525
+ private nodeBuilderFlags(): NodeBuilderFlags {
2526
+ return this.inClassExpressionDeclaration
2527
+ ? NodeBuilderFlags.DeclarationEmit & ~NodeBuilderFlags.WriteClassExpressionAsTypeLiteral
2528
+ : NodeBuilderFlags.DeclarationEmit;
2529
+ }
2530
+
2531
+ private shouldPrintWithInitializer(node: Node): boolean {
2532
+ return (
2533
+ this.canHaveLiteralInitializer(node) &&
2534
+ getInitializer(node) !== undefined &&
2535
+ this.resolver.isLiteralConstDeclaration(this.context.mostOriginal(node))
2536
+ );
2537
+ }
2538
+
2539
+ private canHaveLiteralInitializer(node: Node): boolean {
2540
+ switch (node.kind) {
2541
+ case SyntaxKind.PropertyDeclaration:
2542
+ case SyntaxKind.PropertySignature:
2543
+ return !this.isPrivate(node);
2544
+ case SyntaxKind.Parameter:
2545
+ case SyntaxKind.VariableDeclaration:
2546
+ return true;
2547
+ }
2548
+ return false;
2549
+ }
2550
+
2551
+ private ensureNoInitializer(node: Node): Node | undefined {
2552
+ if (!this.shouldPrintWithInitializer(node)) return undefined;
2553
+ if (!isPrimitiveLiteralValue(skipParenthesesOnly(getInitializer(node)!), true))
2554
+ this.tracker.reportInferenceFallback(node);
2555
+ return this.resolver.createLiteralConstValue(this.context, this.parseNode(node), this.tracker);
2556
+ }
2557
+
2558
+ private transformImportEquals(declaration: ImportEqualsDeclaration): Node | undefined {
2559
+ if (!this.resolver.isDeclarationVisible(declaration)) return undefined;
2560
+ const reference = declaration.moduleReference;
2561
+ if (reference instanceof ExternalModuleReference)
2562
+ return this.factory.updateImportEqualsDeclaration(
2563
+ declaration,
2564
+ declaration.modifiers,
2565
+ declaration.isTypeOnly,
2566
+ declaration.name,
2567
+ this.factory.updateExternalModuleReference(
2568
+ reference,
2569
+ this.rewriteModuleSpecifier(declaration, reference.expression)!,
2570
+ ),
2571
+ );
2572
+ const tracker = this.tracker;
2573
+ const oldContext = tracker.diagnosticContext;
2574
+ tracker.diagnosticContext = declarationContext(declaration);
2575
+ this.checkEntityNameVisibility(reference, this.enclosingDeclaration);
2576
+ tracker.diagnosticContext = oldContext;
2577
+ return declaration;
2578
+ }
2579
+
2580
+ private transformImportDeclaration(declaration: ImportDeclaration): ImportDeclaration | undefined {
2581
+ const clause = declaration.importClause;
2582
+ // `import "mod"` may be needed for its side effects, like global augmentations.
2583
+ if (clause === undefined) return this.updateImport(declaration, undefined);
2584
+ const phaseModifier = clause.phaseModifier === SyntaxKind.DeferKeyword ? undefined : clause.phaseModifier;
2585
+ // The import clause's visibility is the default binding's.
2586
+ const defaultBinding =
2587
+ clause.name !== undefined && this.resolver.isDeclarationVisible(clause) ? clause.name : undefined;
2588
+ const bindings = clause.namedBindings;
2589
+ if (bindings === undefined) {
2590
+ if (defaultBinding === undefined) return undefined;
2591
+ return this.updateImport(
2592
+ declaration,
2593
+ this.factory.updateImportClause(clause, phaseModifier, defaultBinding, undefined),
2594
+ );
2595
+ }
2596
+ if (bindings instanceof NamespaceImport) {
2597
+ const namespace = this.resolver.isDeclarationVisible(bindings) ? bindings : undefined;
2598
+ if (defaultBinding === undefined && namespace === undefined) return undefined;
2599
+ return this.updateImport(
2600
+ declaration,
2601
+ this.factory.updateImportClause(clause, phaseModifier, defaultBinding, namespace),
2602
+ );
2603
+ }
2604
+ const visibleBindings: Node[] = [];
2605
+ if (bindings instanceof NamedImports)
2606
+ for (const element of bindings.elements.nodes)
2607
+ if (this.resolver.isDeclarationVisible(element)) visibleBindings.push(element);
2608
+ if (visibleBindings.length > 0 || defaultBinding !== undefined) {
2609
+ const namedImports =
2610
+ visibleBindings.length > 0 && bindings instanceof NamedImports
2611
+ ? this.factory.updateNamedImports(bindings, this.factory.createNodeList(visibleBindings))
2612
+ : undefined;
2613
+ return this.updateImport(
2614
+ declaration,
2615
+ this.factory.updateImportClause(clause, phaseModifier, defaultBinding, namedImports),
2616
+ );
2617
+ }
2618
+ // A module augmentation of an export may depend on the import.
2619
+ if (this.resolver.isImportRequiredByAugmentation(declaration)) {
2620
+ if (this.tracker.isolatedDeclarations)
2621
+ this.tracker.addDiagnostic(
2622
+ createDiagnosticForNode(
2623
+ declaration,
2624
+ Diagnostics.Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_supported_with_isolatedDeclarations,
2625
+ [],
2626
+ ),
2627
+ );
2628
+ return this.updateImport(declaration, undefined);
2629
+ }
2630
+ return undefined;
2631
+ }
2632
+
2633
+ private updateImport(declaration: ImportDeclaration, clause: ImportClause | undefined): ImportDeclaration {
2634
+ return this.factory.updateImportDeclaration(
2635
+ declaration,
2636
+ declaration.modifiers,
2637
+ clause,
2638
+ this.rewriteModuleSpecifier(declaration, declaration.moduleSpecifier)!,
2639
+ this.tryGetResolutionModeOverride(declaration.attributes),
2640
+ );
2641
+ }
2642
+
2643
+ // Visibility helpers
2644
+
2645
+ private parseNode(node: Node): Node {
2646
+ return this.context.parseNode(node) ?? node;
2647
+ }
2648
+
2649
+ private isPrivate(node: Node): boolean {
2650
+ return this.resolver.getEffectiveDeclarationFlags(node, ModifierFlags.Private) !== 0;
2651
+ }
2652
+
2653
+ private isDeclarationAndNotVisible(node: Node): boolean {
2654
+ const parseNode = this.parseNode(node);
2655
+ switch (parseNode.kind) {
2656
+ case SyntaxKind.FunctionDeclaration:
2657
+ case SyntaxKind.ModuleDeclaration:
2658
+ case SyntaxKind.InterfaceDeclaration:
2659
+ case SyntaxKind.ClassDeclaration:
2660
+ case SyntaxKind.TypeAliasDeclaration:
2661
+ case SyntaxKind.JSTypeAliasDeclaration:
2662
+ case SyntaxKind.EnumDeclaration:
2663
+ return !this.resolver.isDeclarationVisible(parseNode);
2664
+ // These filter their members' visibility themselves.
2665
+ case SyntaxKind.VariableDeclaration:
2666
+ return !this.getBindingNameVisible(parseNode);
2667
+ case SyntaxKind.ClassStaticBlockDeclaration:
2668
+ return true;
2669
+ }
2670
+ return false;
2671
+ }
2672
+
2673
+ private getBindingNameVisible(element: Node): boolean {
2674
+ if (element.kind === SyntaxKind.OmittedExpression) return false;
2675
+ const name = getName(element);
2676
+ if (name === undefined) return false;
2677
+ if (name instanceof BindingPattern) {
2678
+ // Visible if any element was marked visible, as by referenced aliases.
2679
+ for (const child of name.elements.nodes) if (this.getBindingNameVisible(child)) return true;
2680
+ return false;
2681
+ }
2682
+ return this.resolver.isDeclarationVisible(element);
2683
+ }
2684
+
2685
+ private shouldStripInternal(node: Node): boolean {
2686
+ const file = this.tracker.currentSourceFile;
2687
+ return this.tracker.stripInternal && file !== undefined && this.isInternalDeclaration(node, file);
2688
+ }
2689
+
2690
+ /** Whether a declaration has an `@internal` comment. */
2691
+ private isInternalDeclaration(node: Node, file: SourceFile): boolean {
2692
+ const parseTreeNode = this.context.mostOriginal(node);
2693
+ if ((parseTreeNode.flags & NodeFlags.Synthesized) !== 0) return false;
2694
+ const text = file.text;
2695
+ if (parseTreeNode instanceof ParameterDeclaration) {
2696
+ // The comment can precede the parameter or follow the previous one's comma:
2697
+ // `a, /** @internal */ public b: string`.
2698
+ const parameters = getParameters(parseTreeNode.parent!)!.nodes;
2699
+ const index = parameters.indexOf(parseTreeNode);
2700
+ let ranges: CommentRange[];
2701
+ if (index > 0) {
2702
+ const trailingPos = skipTrivia(text, parameters[index - 1].end + 1, false, true);
2703
+ ranges = commentRanges(getTrailingCommentRanges(text, trailingPos)).concat(
2704
+ commentRanges(getLeadingCommentRanges(text, node.pos)),
2705
+ );
2706
+ } else ranges = commentRanges(getTrailingCommentRanges(text, skipTrivia(text, node.pos, false, true)));
2707
+ return ranges.length > 0 && hasInternalAnnotation(text, ranges[ranges.length - 1]);
2708
+ }
2709
+ if (parseTreeNode.kind === SyntaxKind.JsxText) return false;
2710
+ for (const range of commentRanges(getLeadingCommentRanges(text, parseTreeNode.pos)))
2711
+ if (hasInternalAnnotation(text, range)) return true;
2712
+ return false;
2713
+ }
2714
+ }
2715
+
2716
+ function commentRanges(ranges: CommentRange[] | undefined): CommentRange[] {
2717
+ return ranges ?? [];
2718
+ }
2719
+
2720
+ function hasInternalAnnotation(text: string, range: CommentRange): boolean {
2721
+ return text.substring(range.pos, range.end).indexOf('@internal') >= 0;
2722
+ }
2723
+
2724
+ class DiagnosticScope {
2725
+ readonly context: DiagnosticContext;
2726
+ readonly errorNameNode: Node | undefined;
2727
+ readonly suppressNewDiagnosticContexts: boolean;
2728
+
2729
+ constructor(context: DiagnosticContext, errorNameNode: Node | undefined, suppressNewDiagnosticContexts: boolean) {
2730
+ this.context = context;
2731
+ this.errorNameNode = errorNameNode;
2732
+ this.suppressNewDiagnosticContexts = suppressNewDiagnosticContexts;
2733
+ }
2734
+ }
2735
+
2736
+ const modifierKindsInOrder: SyntaxKind[] = [
2737
+ SyntaxKind.ExportKeyword,
2738
+ SyntaxKind.DeclareKeyword,
2739
+ SyntaxKind.DefaultKeyword,
2740
+ SyntaxKind.ConstKeyword,
2741
+ SyntaxKind.PublicKeyword,
2742
+ SyntaxKind.PrivateKeyword,
2743
+ SyntaxKind.ProtectedKeyword,
2744
+ SyntaxKind.AbstractKeyword,
2745
+ SyntaxKind.StaticKeyword,
2746
+ SyntaxKind.OverrideKeyword,
2747
+ SyntaxKind.ReadonlyKeyword,
2748
+ SyntaxKind.AccessorKeyword,
2749
+ SyntaxKind.AsyncKeyword,
2750
+ SyntaxKind.InKeyword,
2751
+ SyntaxKind.OutKeyword,
2752
+ ];
2753
+
2754
+ function preservedReferences(references: FileReference[]): FileReference[] {
2755
+ const result: FileReference[] = [];
2756
+ for (const reference of references)
2757
+ if (reference.preserve)
2758
+ result.push(new FileReference(-1, -1, reference.fileName, reference.resolutionMode, reference.preserve));
2759
+ return result;
2760
+ }
2761
+
2762
+ /** Whether a node is a declaration (type parameters only when attached). */
2763
+ function isDeclaration(node: Node): boolean {
2764
+ if (node.kind === SyntaxKind.TypeParameter) return node.parent !== undefined;
2765
+ return isDeclarationNode(node);
2766
+ }
2767
+
2768
+ function isEntityName(node: Node): boolean {
2769
+ return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName;
2770
+ }
2771
+
2772
+ function isThisParameterNode(node: Node): boolean {
2773
+ return node instanceof ParameterDeclaration && node.name instanceof Identifier && node.name.text === 'this';
2774
+ }
2775
+
2776
+ /** Declarations whose scope names in their types are resolved from. */
2777
+ function isEnclosingDeclaration(node: Node): boolean {
2778
+ switch (node.kind) {
2779
+ case SyntaxKind.SourceFile:
2780
+ case SyntaxKind.TypeAliasDeclaration:
2781
+ case SyntaxKind.JSTypeAliasDeclaration:
2782
+ case SyntaxKind.ModuleDeclaration:
2783
+ case SyntaxKind.ClassDeclaration:
2784
+ case SyntaxKind.InterfaceDeclaration:
2785
+ case SyntaxKind.IndexSignature:
2786
+ case SyntaxKind.MappedType:
2787
+ case SyntaxKind.VariableDeclaration:
2788
+ return true;
2789
+ }
2790
+ return isFunctionLike(node);
2791
+ }
2792
+
2793
+ function isLateVisibilityPaintedStatement(node: Node): boolean {
2794
+ switch (node.kind) {
2795
+ case SyntaxKind.ImportDeclaration:
2796
+ case SyntaxKind.JSImportDeclaration:
2797
+ case SyntaxKind.ImportEqualsDeclaration:
2798
+ case SyntaxKind.VariableStatement:
2799
+ case SyntaxKind.ClassDeclaration:
2800
+ case SyntaxKind.FunctionDeclaration:
2801
+ case SyntaxKind.ModuleDeclaration:
2802
+ case SyntaxKind.TypeAliasDeclaration:
2803
+ case SyntaxKind.JSTypeAliasDeclaration:
2804
+ case SyntaxKind.InterfaceDeclaration:
2805
+ case SyntaxKind.EnumDeclaration:
2806
+ return true;
2807
+ }
2808
+ return false;
2809
+ }
2810
+
2811
+ function isExternalModuleIndicator(node: Node): boolean {
2812
+ return (
2813
+ isAnyImportOrReExport(node) ||
2814
+ node.kind === SyntaxKind.ExportAssignment ||
2815
+ hasSyntacticModifier(node, ModifierFlags.Export)
2816
+ );
2817
+ }
2818
+
2819
+ /** Whether a statement in a namespace without `export {}` would stop being exported implicitly. */
2820
+ function needsScopeMarker(node: Node): boolean {
2821
+ return (
2822
+ !isAnyImportOrReExport(node) &&
2823
+ node.kind !== SyntaxKind.ExportAssignment &&
2824
+ !hasSyntacticModifier(node, ModifierFlags.Export) &&
2825
+ !isAmbientModule(node)
2826
+ );
2827
+ }
2828
+
2829
+ function hasScopeMarker(statements: NodeList): boolean {
2830
+ for (const statement of statements.nodes)
2831
+ if (statement.kind === SyntaxKind.ExportAssignment || statement.kind === SyntaxKind.ExportDeclaration) return true;
2832
+ return false;
2833
+ }
2834
+
2835
+ function maskModifierFlags(node: Node, mask: ModifierFlags, additions: ModifierFlags): ModifierFlags {
2836
+ let flags = (getCombinedModifierFlags(node) & mask) | additions;
2837
+ // A default export keeps `export` even where exports are stripped, and never has `declare`.
2838
+ if ((flags & ModifierFlags.Default) !== 0 && (flags & ModifierFlags.Export) === 0) flags ^= ModifierFlags.Export;
2839
+ if ((flags & ModifierFlags.Default) !== 0 && (flags & ModifierFlags.Ambient) !== 0) flags ^= ModifierFlags.Ambient;
2840
+ return flags;
2841
+ }
2842
+
2843
+ function isImplicitlyExportedJSDocDeclaration(node: Node): boolean {
2844
+ const parent = node.parent;
2845
+ if (parent === undefined || parent.kind !== SyntaxKind.SourceFile) return false;
2846
+ if (!isExternalOrCommonJSModule(parent as SourceFile)) return false;
2847
+ if (node.kind === SyntaxKind.JSTypeAliasDeclaration) return true;
2848
+ return node.kind === SyntaxKind.ModuleDeclaration && (node.flags & NodeFlags.Reparsed) !== 0;
2849
+ }
2850
+
2851
+ function canHaveModifiers(node: Node): boolean {
2852
+ switch (node.kind) {
2853
+ case SyntaxKind.VariableStatement:
2854
+ case SyntaxKind.FunctionDeclaration:
2855
+ case SyntaxKind.ClassDeclaration:
2856
+ case SyntaxKind.InterfaceDeclaration:
2857
+ case SyntaxKind.TypeAliasDeclaration:
2858
+ case SyntaxKind.EnumDeclaration:
2859
+ case SyntaxKind.ModuleDeclaration:
2860
+ case SyntaxKind.ImportEqualsDeclaration:
2861
+ case SyntaxKind.ImportDeclaration:
2862
+ case SyntaxKind.JSImportDeclaration:
2863
+ case SyntaxKind.ExportAssignment:
2864
+ case SyntaxKind.ExportDeclaration:
2865
+ return true;
2866
+ }
2867
+ return false;
2868
+ }
2869
+
2870
+ /** Kinds whose type the resolver writes from the declaration rather than a signature. */
2871
+ function hasInferredType(node: Node): boolean {
2872
+ switch (node.kind) {
2873
+ case SyntaxKind.Parameter:
2874
+ case SyntaxKind.PropertySignature:
2875
+ case SyntaxKind.PropertyDeclaration:
2876
+ case SyntaxKind.BindingElement:
2877
+ case SyntaxKind.PropertyAccessExpression:
2878
+ case SyntaxKind.ElementAccessExpression:
2879
+ case SyntaxKind.BinaryExpression:
2880
+ case SyntaxKind.CallExpression:
2881
+ case SyntaxKind.VariableDeclaration:
2882
+ case SyntaxKind.ExportAssignment:
2883
+ case SyntaxKind.PropertyAssignment:
2884
+ case SyntaxKind.ShorthandPropertyAssignment:
2885
+ case SyntaxKind.JSDocParameterTag:
2886
+ case SyntaxKind.JSDocPropertyTag:
2887
+ return true;
2888
+ }
2889
+ return false;
2890
+ }
2891
+
2892
+ /** A literal that can be an initializer in a declaration file: a string, number, bigint or boolean. */
2893
+ function isPrimitiveLiteralValue(node: Node, includeBigInt: boolean): boolean {
2894
+ switch (node.kind) {
2895
+ case SyntaxKind.TrueKeyword:
2896
+ case SyntaxKind.FalseKeyword:
2897
+ case SyntaxKind.NumericLiteral:
2898
+ case SyntaxKind.StringLiteral:
2899
+ case SyntaxKind.NoSubstitutionTemplateLiteral:
2900
+ return true;
2901
+ case SyntaxKind.BigIntLiteral:
2902
+ return includeBigInt;
2903
+ case SyntaxKind.PrefixUnaryExpression: {
2904
+ const unary = node as PrefixUnaryExpression;
2905
+ const operand = unary.operand;
2906
+ if (unary.operator === SyntaxKind.MinusToken)
2907
+ return operand instanceof NumericLiteral || (includeBigInt && operand.kind === SyntaxKind.BigIntLiteral);
2908
+ if (unary.operator === SyntaxKind.PlusToken) return operand instanceof NumericLiteral;
2909
+ return false;
2910
+ }
2911
+ }
2912
+ return false;
2913
+ }
2914
+
2915
+ function skipParenthesesOnly(node: Node): Node {
2916
+ let current = node;
2917
+ while (current.kind === SyntaxKind.ParenthesizedExpression) current = getExpression(current)!;
2918
+ return current;
2919
+ }
2920
+
2921
+ /** Skips what passes an expression's type through: parentheses, assignments and commas. */
2922
+ function skipOuterExpressions(node: Node): Node {
2923
+ let current = node;
2924
+ for (;;) {
2925
+ if (current.kind === SyntaxKind.ParenthesizedExpression) current = getExpression(current)!;
2926
+ else if (
2927
+ current instanceof BinaryExpression &&
2928
+ (current.operatorToken.kind === SyntaxKind.EqualsToken || current.operatorToken.kind === SyntaxKind.CommaToken)
2929
+ )
2930
+ current = current.right;
2931
+ else return current;
2932
+ }
2933
+ }
2934
+
2935
+ function getFirstConstructorWithBody(members: NodeList): ConstructorDeclaration | undefined {
2936
+ for (const member of members.nodes)
2937
+ if (member !== undefined && member instanceof ConstructorDeclaration && nodeIsPresent(member.body)) return member;
2938
+ return undefined;
2939
+ }
2940
+
2941
+ function getClassExtendsHeritageElement(node: Node): ExpressionWithTypeArguments | undefined {
2942
+ const clauses = getHeritageClauses(node);
2943
+ if (clauses === undefined) return undefined;
2944
+ for (const clause of clauses.nodes)
2945
+ if (clause instanceof HeritageClause && clause.token === SyntaxKind.ExtendsKeyword) {
2946
+ const first = clause.types.nodes.length > 0 ? clause.types.nodes[0] : undefined;
2947
+ return first !== undefined && first instanceof ExpressionWithTypeArguments ? first : undefined;
2948
+ }
2949
+ return undefined;
2950
+ }
2951
+
2952
+ /** Whether the original of `node` is on one line of its source file. */
2953
+ function isOriginalNodeSingleLine(context: EmitContext, node: Node): boolean {
2954
+ const original = context.mostOriginal(node);
2955
+ if ((original.flags & NodeFlags.Synthesized) !== 0 || original.pos < 0) return false;
2956
+ const text = getSourceFileOfNode(original).text;
2957
+ for (let i = original.pos; i < original.end; i++) {
2958
+ const ch = text.charCodeAt(i);
2959
+ if (ch === 10 || ch === 13) return false;
2960
+ }
2961
+ return true;
2962
+ }
2963
+
2964
+ /** A node known to be present, checked where its type allows `undefined` at runtime. */
2965
+ function defined(node: Node | undefined): Node {
2966
+ if (node === undefined) throw new Error('Expected a node');
2967
+ return node;
2968
+ }
2969
+
2970
+ function asteriskOf(fn: Node): Token | undefined {
2971
+ if (fn !== undefined && fn instanceof FunctionExpression) return fn.asteriskToken;
2972
+ return undefined;
2973
+ }
2974
+
2975
+ /** `const f = function () {}` or `const f = () => {}`. */
2976
+ function isFunctionValuedVariable(node: Node): boolean {
2977
+ if (node.kind !== SyntaxKind.VariableDeclaration) return false;
2978
+ const initializer = getInitializer(node);
2979
+ return (
2980
+ initializer !== undefined &&
2981
+ (initializer.kind === SyntaxKind.FunctionExpression || initializer.kind === SyntaxKind.ArrowFunction)
2982
+ );
2983
+ }
2984
+
2985
+ function appendFlattened(result: Node[], node: Node): boolean {
2986
+ if (node instanceof SyntaxList) for (const child of node.children) result.push(child);
2987
+ else result.push(node);
2988
+ return true;
2989
+ }
2990
+
2991
+ /** The JSDoc `@type` signature of a function-like declaration. */
2992
+ function getFullSignature(node: Node): Node | undefined {
2993
+ if (node instanceof FunctionExpression) return node.fullSignature;
2994
+ if (node instanceof ArrowFunction) return node.fullSignature;
2995
+ if (node instanceof FunctionDeclaration) return node.fullSignature;
2996
+ if (node instanceof MethodDeclaration) return node.fullSignature;
2997
+ if (node instanceof ConstructorDeclaration) return node.fullSignature;
2998
+ if (node instanceof GetAccessorDeclaration) return node.fullSignature;
2999
+ if (node instanceof SetAccessorDeclaration) return node.fullSignature;
3000
+ return undefined;
3001
+ }
3002
+
3003
+ function isCommonJSAliasExport(node: Node): boolean {
3004
+ if (!(node instanceof BinaryExpression) || !(node.right instanceof Identifier)) return false;
3005
+ const symbol = node.symbol;
3006
+ return symbol !== undefined && symbol.declarations.length === 1;
3007
+ }
3008
+
3009
+ function getLeftmostAccessExpression(node: Node): Node {
3010
+ let current = node;
3011
+ while (current.kind === SyntaxKind.PropertyAccessExpression || current.kind === SyntaxKind.ElementAccessExpression)
3012
+ current = getExpression(current)!;
3013
+ return current;
3014
+ }
3015
+
3016
+ /** Whether properties assigned to a function are emitted: one of its declarations has a body. */
3017
+ function shouldEmitFunctionProperties(fn: FunctionDeclaration): boolean {
3018
+ if (fn.body !== undefined) return true;
3019
+ const symbol = fn.symbol;
3020
+ if (symbol === undefined) return false;
3021
+ for (const declaration of symbol.declarations)
3022
+ if (declaration instanceof FunctionDeclaration && declaration.body !== undefined) return true;
3023
+ return false;
3024
+ }
3025
+
3026
+ function isNonContextualKeyword(kind: SyntaxKind): boolean {
3027
+ return (
3028
+ kind >= SyntaxKind.FirstKeyword &&
3029
+ kind <= SyntaxKind.LastKeyword &&
3030
+ !(kind >= SyntaxKind.FirstContextualKeyword && kind <= SyntaxKind.LastContextualKeyword)
3031
+ );
3032
+ }
3033
+
3034
+ function isClassExtendingNull(heritage: NodeList): boolean {
3035
+ if (heritage.nodes.length !== 1) return false;
3036
+ for (const type of (heritage.nodes[0] as HeritageClause).types.nodes)
3037
+ if (getExpression(type)!.kind === SyntaxKind.NullKeyword) return true;
3038
+ return false;
3039
+ }
3040
+
3041
+ function getTextOfPropertyName(name: Node): string {
3042
+ switch (name.kind) {
3043
+ case SyntaxKind.Identifier:
3044
+ case SyntaxKind.PrivateIdentifier:
3045
+ case SyntaxKind.StringLiteral:
3046
+ case SyntaxKind.NumericLiteral:
3047
+ case SyntaxKind.NoSubstitutionTemplateLiteral:
3048
+ return getText(name);
3049
+ }
3050
+ return '';
3051
+ }
3052
+
3053
+ /** The key of a class member for deduplicating `this.x` members: name, staticness and privateness. */
3054
+ function thisPropertyKey(name: Node, node: Node, isStaticMember: boolean): string {
3055
+ const prefix = (isStaticMember ? 's' : 'i') + (name instanceof PrivateIdentifier ? '#' : '.');
3056
+ if (!(name instanceof ComputedPropertyName) && name.kind !== SyntaxKind.ElementAccessExpression) {
3057
+ const text = getTextOfPropertyName(name);
3058
+ if (text !== '' || name instanceof StringLiteral) return prefix + text;
3059
+ }
3060
+ return prefix + '@' + node.pos + ':' + node.end;
3061
+ }
3062
+
3063
+ const enum ExpressionWalkerKind {
3064
+ ModuleExports,
3065
+ Members,
3066
+ }
3067
+
3068
+ /** Walks a whole file for `module.exports =`, assigned properties and CommonJS exports. */
3069
+ class ExpressionWalker extends NodeVisitor {
3070
+ readonly transformer: DeclarationTransformer;
3071
+ readonly kind: ExpressionWalkerKind;
3072
+
3073
+ constructor(transformer: DeclarationTransformer, kind: ExpressionWalkerKind) {
3074
+ super();
3075
+ this.transformer = transformer;
3076
+ this.kind = kind;
3077
+ }
3078
+
3079
+ visitNode(node: Node): boolean {
3080
+ // Only assignments and `Object.defineProperty` calls declare anything.
3081
+ if (node.kind === SyntaxKind.BinaryExpression || node.kind === SyntaxKind.CallExpression) {
3082
+ if (this.kind === ExpressionWalkerKind.ModuleExports) this.transformer.visitModuleExportsAssignment(node);
3083
+ else this.transformer.visitNestedExpression(node);
3084
+ }
3085
+ return node.forEachChild(this);
3086
+ }
3087
+ }
3088
+
3089
+ /** Walks a class member for `this.x = …` assignments. */
3090
+ class ThisPropertyWalker extends NodeVisitor {
3091
+ readonly transformer: DeclarationTransformer;
3092
+ readonly classNode: Node;
3093
+
3094
+ constructor(transformer: DeclarationTransformer, classNode: Node) {
3095
+ super();
3096
+ this.transformer = transformer;
3097
+ this.classNode = classNode;
3098
+ }
3099
+
3100
+ visitNode(node: Node): boolean {
3101
+ this.transformer.visitThisPropertyAssignment(node, this.classNode);
3102
+ return node.forEachChild(this);
3103
+ }
3104
+ }
3105
+
3106
+ /** The text of a JSDoc comment: its text and links, without trailing whitespace. */
3107
+ function getTextOfJSDocComment(comment: NodeList | undefined): string {
3108
+ if (comment === undefined) return '';
3109
+ let text = '';
3110
+ for (const n of comment.nodes) {
3111
+ if (n instanceof JSDocText) text += n.text;
3112
+ else if (
3113
+ n.kind === SyntaxKind.JSDocLink ||
3114
+ n.kind === SyntaxKind.JSDocLinkCode ||
3115
+ n.kind === SyntaxKind.JSDocLinkPlain
3116
+ )
3117
+ text += getSourceTextOfNode(getSourceFileOfNode(n), n);
3118
+ }
3119
+ return text.trimEnd();
3120
+ }